<?php
$page_header = "Create Manual Work Order";
?>

<section class="content-header">
    <h1><?= $page_header; ?></h1>
</section>

<style>
.error-message   { color:#dc3545; font-size:12px; display:none; margin-top:5px; }
.order-qty-error { border-color:#dc3545 !important; }
#groupDetailsModal .modal-dialog,
#groupPickModal .modal-dialog,
#setModal .modal-dialog {
    max-width: 800px !important;
    width: 800px !important;
}
.mw-checkbox-row { display:flex; align-items:center; gap:8px; }
.mw-mandatory-tag { color:#c0392b; font-weight:bold; font-size:11px; }
.mwo-card-header{
    position: relative;
}

.back-btn{
    position: absolute;
    right: 20px;      /* right edge of the header */
    top: 50%;
    transform: translateY(-50%);
}
</style>

<section class="content">
    <div class="row">
        <div class="col-lg-12">
            <div class="card mwo-card">
                <div class="card-header mwo-card-header position-relative">
    <h3 class="card-title mb-0">Create Manual Work Order</h3>

    <a href="index?page=view" class="btn btn-light btn-sm back-btn">
        <i class=""></i> Back
    </a>
</div>
                <div class="card-body">

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><i class=""></i> Customer</label>
                                <?php echo $gsi->getCustomercodeListNew("customer", "", "100%", false, "form-control select2", "mwCustomer", ""); ?>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><i class=""></i> Required Date</label>
                                <input type="date" id="mwRequiredDate" name="required_date" class="form-control" required>
                            </div>
                        </div>
                    </div>

                  

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><i class=""></i> Part Number</label>
                                <?php echo $gsi->getPartNumberListNew("part_number", "", "100%", false, "form-control select2", "mwPartNumber", ""); ?>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><i class=""></i> Qty</label>
                                <input type="number" id="mwOrderQty" name="order_qty" class="form-control" min="0.0001" step="any" placeholder="Enter quantity">
                                <div id="mwQtyError" class="error-message">Please enter a valid quantity</div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mwo-option-card">
                                <input type="checkbox" id="mwGroupCheck" name="group_check" value="1">
                                <label for="mwGroupCheck">Group</label>
                                <span id="mwGroupMandatoryTag" class="mw-mandatory-tag" style="display:none;">Mandatory</span>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mwo-option-card">
                                <input type="checkbox" id="mwSetCheck" name="set_check" value="1">
                                <label for="mwSetCheck">Set</label>
                            </div>
                        </div>
                    </div>

                </div><!-- /.card-body -->

                <div class="card-footer mwo-card-footer">
                    <button type="button" id="mwSubmitBtn" class="btn mwo-btn-primary">
                        <span class="btn-text"><i class="fa fa-check"></i> Create Work Order</span>
                        <span class="spinner-border spinner-border-sm" style="display:none;"></span>
                    </button>
                    <a href="index?page=view" class="btn mwo-btn-secondary">Cancel</a>
                </div>

            </div><!-- /.card -->
        </div><!-- /.col -->
    </div><!-- /.row -->
</section>

<style>
.mwo-card {
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.08);
    border: 1px solid #e9ecef;
    overflow: hidden;
}
.mwo-card-header {
    background-color: #9c4893;
    padding: 15px 20px;
    border-bottom: none;
}
.mwo-card-header .card-title {
    color: #fff;
    font-weight: 600;
}
.mwo-card-header .card-title i { margin-right: 8px; }

.card-body {
    padding: 24px 30px;
}

.form-group label {
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 6px;
    display: block;
}
.form-group label i {
    width: 16px;
    color: #3498db;
    margin-right: 6px;
}

.mwo-divider {
    border-top: 1px solid #e9ecef;
    margin: 10px 0 20px;
}

.mwo-option-card {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 16px;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    background: #f8f9fa;
    margin-bottom: 5px;
}
.mwo-option-card input[type="checkbox"] {
    width: 16px;
    height: 16px;
    cursor: pointer;
}
.mwo-option-card label {
    margin: 0;
    font-weight: 500;
    color: #2c3e50;
    cursor: pointer;
}

.mwo-card-footer {
    background-color: #f8f9fa;
    padding: 16px 30px;
    border-top: 1px solid #e9ecef;
    display: flex;
    gap: 10px;
}
.mwo-btn-primary {
    background-color: #9c4893;
    border-color: #9c4893;
    color: #fff;
    padding: 8px 24px;
    font-weight: 500;
}
.mwo-btn-primary:hover {
    background-color: #7e3a76;
    border-color: #7e3a76;
    color: #fff;
}
.mwo-btn-secondary {
    background-color: #fff;
    border: 1px solid #ced4da;
    color: #495057;
    padding: 8px 24px;
}
.mwo-btn-secondary:hover {
    background-color: #f1f1f1;
}

@media (max-width: 767px) {
    .col-md-6 { width: 100%; }
}
</style>

<!-- Group picker (optional-group candidate list) -->
<div class="modal fade" id="groupPickModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Select Group</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body"><div id="groupItemsContainer"></div></div>
        </div>
    </div>
</div>

<!-- Group details (member quantities) -->
<div id="groupDetailsModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Group Details</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body"><p>Loading details...</p></div>
        </div>
    </div>
</div>

<!-- Set items -->
<div class="modal fade" id="setModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Set Items</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body"><div id="setItemsContainer"></div></div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
let currentGroupId = 0;

function showButtonSpinner(button) {
    button.prop('disabled', true);
    button.find('.btn-text').hide();
    button.find('.spinner-border-sm').show();
}
function hideButtonSpinner(button) {
    button.prop('disabled', false);
    button.find('.btn-text').show();
    button.find('.spinner-border-sm').hide();
}


$('[name="part_number"]').on('change', function () {
    let partId = $(this).val();
    let $groupCheck = $('#mwGroupCheck');
    let $setCheck   = $('#mwSetCheck');
    let $mandatoryTag = $('#mwGroupMandatoryTag');

    $groupCheck.prop('checked', false).prop('disabled', false);
    $setCheck.prop('checked', false).prop('disabled', false);
    $mandatoryTag.hide();

    if (!partId) return;

    $.ajax({
        url: site_url + '/modules/work_order_management/index.php?page=ajax_actions_manual&action=fetch_part_meta',
        type: 'POST',
        dataType: 'json',
        data: { part_id: partId },
        success: function (res) {
            if (res.group_type === 'mandatory') {
                $groupCheck.prop('checked', true).prop('disabled', true);
                $mandatoryTag.show();
            } else if (res.group_type === 'none') {
                $groupCheck.prop('disabled', true);
            }
            if (res.has_set) {
                $setCheck.prop('checked', true);
            } else {
                $setCheck.prop('disabled', true);
            }
        }
    });
});

function mwValidateForm() {
    let valid = true;
    let $qty = $('#mwOrderQty');
    let val  = parseFloat($qty.val());
    if (!val || val <= 0) { $qty.addClass('order-qty-error'); $('#mwQtyError').show(); valid = false; }
    else { $qty.removeClass('order-qty-error'); $('#mwQtyError').hide(); }

    if (!$('[name="part_number"]').val()) { alert('Please select a part number.'); valid = false; }
    if (!$('[name="customer"]').val())   { alert('Please select a customer.'); valid = false; }
    if (!$('#mwRequiredDate').val()) { alert('Please select a required date.'); valid = false; }
    return valid;
}

$('#mwSubmitBtn').on('click', function () {
    if (!mwValidateForm()) return;
    let button = $(this);
    showButtonSpinner(button);

    let partId = $('[name="part_number"]').val();
    let qty    = parseFloat($('#mwOrderQty').val());
    let groupChecked = $('#mwGroupCheck').is(':checked');
    let setChecked   = $('#mwSetCheck').is(':checked');

    let mainItem = { groupItemId: partId, quantity: qty };

    window._mwPendingOrder = {
        orderData:     [mainItem],
        setChecked:    setChecked,
        customer:      $('[name="customer"]').val(),
        required_date: $('#mwRequiredDate').val()
    };
    currentGroupId = 0;

    if (groupChecked) {
        $.ajax({
            url: site_url + '/modules/work_order_management/index.php?page=ajax_actions_manual&action=check_group_type',
            type: 'POST',
            dataType: 'json',
            data: { part_id: partId },
            success: function (res) {
                if (res.group_type === 'mandatory') {
                    currentGroupId = res.group_id;
                    fetchGroupDetails(res.group_id, mainItem);
                } else if (res.group_type === 'mandatory_multiple') {
                    hideButtonSpinner(button);
                    let html = '<table class="table"><tr><th>Group Number</th><th>Action</th></tr>';
                    res.groups.forEach(function (g) {
                        html += '<tr><td>' + g.group_number + ' <span class="badge badge-danger">Mandatory</span></td>'
                              + '<td><button class="btn btn-sm btn-primary" onclick="selectMandatoryGroup(' + g.group_id + ')">Select</button></td></tr>';
                    });
                    html += '</table>';
                    $('#groupItemsContainer').html(html);
                    $('#groupPickModal').modal('show');
                } else if (res.group_type === 'optional') {
                    $.ajax({
                        url: site_url + '/modules/work_order_management/index.php?page=ajax_actions_manual&action=fetch_group_items',
                        type: 'POST',
                        data: { part_id: partId, order_qty: qty },
                        success: function (response) {
                            hideButtonSpinner(button);
                            $('#groupItemsContainer').html(response);
                            $('#groupPickModal').modal('show');
                            $(document).off('click', '.group-item-row_1').on('click', '.group-item-row_1', function () {
                                $('#groupPickModal').modal('hide');
                                currentGroupId = $(this).data('group-id');
                                fetchGroupDetails(currentGroupId, mainItem);
                            });
                        },
                        error: function () { hideButtonSpinner(button); alert('Error fetching group items.'); }
                    });
                } else {
                    // No group on this part after all — fall through to set/submit.
                    afterGroupStep(button);
                }
            },
            error: function () { hideButtonSpinner(button); alert('Error checking group type.'); }
        });
    } else {
        afterGroupStep(button);
    }
});

function fetchGroupDetails(groupId, mainItem) {
    $.ajax({
        url: site_url + '/modules/work_order_management/index.php?page=ajax_actions_manual&action=fetch_group_details',
        type: 'POST',
        data: { group_id: groupId, part_id: mainItem.groupItemId, order_qty: mainItem.quantity },
        success: function (response) {
            $('#groupDetailsModal .modal-body').html(response);
            $('#groupDetailsModal').modal('show');
            hideButtonSpinner($('#mwSubmitBtn'));
        },
        error: function () { hideButtonSpinner($('#mwSubmitBtn')); alert('Error fetching group details.'); }
    });
}

function selectMandatoryGroup(groupId) {
    currentGroupId = groupId;
    $('#groupPickModal').modal('hide');
    fetchGroupDetails(groupId, window._mwPendingOrder.orderData[0]);
}

$(document).on('click', '#submitGroupOrder', function () {
    const orderData = [];
    $('#groupDetailsModal .group-item-row').each(function () {
        let qty = parseFloat($(this).find('.group-item-qty').val()) || 0;
        if (qty > 0) orderData.push({ groupItemId: $(this).data('group-item-id'), quantity: qty });
    });
    window._mwPendingOrder.orderData = orderData;
    $('#groupDetailsModal').modal('hide');
    afterGroupStep($('#mwSubmitBtn'));
});


function afterGroupStep(button) {
    if (window._mwPendingOrder.setChecked) {
        showButtonSpinner(button);
        $.ajax({
            url: site_url + '/modules/work_order_management/index.php?page=ajax_actions_manual&action=fetch_set_items',
            type: 'POST',
            data: { orderData: JSON.stringify(window._mwPendingOrder.orderData) },
            success: function (response) {
                hideButtonSpinner(button);
                if (response.indexOf('No set items found') !== -1) {
                    mwFinalSubmit([]);
                } else {
                    $('#setItemsContainer').html(response);
                    $('#setModal').modal('show');
                }
            },
            error: function () { hideButtonSpinner(button); alert('An error occurred while fetching set items.'); }
        });
    } else {
        mwFinalSubmit([]);
    }
}

$(document).on('click', '#submitSetOrder', function () {
    const setorderData = [];
    $('#setItemsContainer .set-item-row').each(function () {
        if ($(this).find('.set-group-checkbox').is(':checked')) {
            let partIds = $(this).data('part-ids').toString().split(',');
            let setId   = $(this).data('set-id');
            partIds.forEach(pid => { if (pid.trim() !== '') setorderData.push({ setItemId: pid.trim(), setId: setId }); });
        }
    });
    $('#setModal').modal('hide');
    mwFinalSubmit(setorderData);
});
function mwFinalSubmit(setorderData) {
    let button = $('#mwSubmitBtn');
    showButtonSpinner(button);
    let p = window._mwPendingOrder;
    $.ajax({
        url: site_url + '/modules/work_order_management/index.php?page=ajax_actions_manual&action=create_manual_work_order',
        type: 'POST',
        dataType: 'json',
        data: {
            orderData:     JSON.stringify(p.orderData),
            setorderData:  JSON.stringify(setorderData),
            group_id:      currentGroupId,
            customer:      p.customer,
            required_date: p.required_date
        },
        success: function (res) {
            hideButtonSpinner(button);
            if (res.status === 'success') {
                alert(res.message || 'Manual work order created.');
                window.location.href = 'index?page=view';
            } else {
                alert(res.message || 'Failed to create work order.');
            }
        },
        error: function () { hideButtonSpinner(button); alert('An unexpected error occurred.'); }
    });
}
</script>