<?php 
include("includes/FCKeditor/fckeditor.php");

$file_name  = "index?page=item_status";
$page_name  = "P/O Number";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $order_id    = intval($_POST['order_id']);
    $po_id       = intval($_POST['po_id']);
    $action      = $_POST['action'];
    $received_by = $_SESSION['user_id'];

    if ($action === '1') {
        $receive_qty      = intval($_POST['receive_qty']);
        $delivery_ref_val = mysqli_real_escape_string($conn, $_POST['delivery_ref'] ?? '');

        $result = $conn->query("SELECT part_number, item_type, quantity, received FROM purchase_order_items_mapping WHERE id = $order_id");
        $order  = $result->fetch_assoc();

        $new_qty_received = $order['received'] + $receive_qty;

        $conn->query("UPDATE purchase_order_items_mapping SET received = $new_qty_received WHERE id = $order_id");
        $conn->query("INSERT INTO purchase_slips (purchase_order_mapp_id, qty_received, received_by, slip_date, supplier_delivery_ref)
                      VALUES ($order_id, $receive_qty, $received_by, NOW(), '$delivery_ref_val')");

        // Only update inventory for non-freetext lines
        if($order['item_type'] != 6){
            $part_number = $order['part_number'];
            $conn->query("UPDATE inventory SET quantity_in_stock = quantity_in_stock + $receive_qty WHERE item_id = '$part_number'");
        }

        $res_q     = mysqli_query($conn, "SELECT id, received, quantity FROM purchase_order_items_mapping WHERE po_id = '$po_id'");
        $all_equal = true;
        while ($row = mysqli_fetch_assoc($res_q)) {
            if ($row['received'] < $row['quantity']) { $all_equal = false; break; }
        }
        if ($all_equal) {
            $conn->query("UPDATE purchase_order SET order_status = 4 WHERE id = '$po_id'");
        }

        $conn->query("UPDATE purchase_order_items_mapping SET is_reviewed = 0, review_notes = '' WHERE id = $order_id");

    } else if ($action == '2') {
        $review_notes = mysqli_real_escape_string($conn, $_POST['review_notes']);
        $conn->query("UPDATE purchase_order_items_mapping SET is_reviewed = 2, review_notes = '$review_notes', updated_by = '$received_by' WHERE id = $order_id");
    }

    $po_id_enc = urlencode(utility::app_crypt($po_id, 'e'));
    header("Location: " . $file_name . "&po_id=" . $po_id_enc . "&id=" . $po_id);
    exit();
}

$po_id_int  = intval($_REQUEST['id']);
$po_details = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM purchase_order WHERE id = '$po_id_int'"));
$order_ref  = utility::getTableFieldById("purchase_order", "order_ref", "id", $po_id_int);

/*
 * JOIN freetext part numbers so each row has resolved_part_number:
 *   - item_type 6  → the freetext string from purchase_order_freetext_parts
 *   - everything else → the integer ID from purchase_order_items_mapping
 */
$orders = $conn->query("
    SELECT m.*,
           CASE WHEN m.item_type = 6 THEN fp.part_number ELSE m.part_number END AS resolved_part_number
    FROM purchase_order_items_mapping m
    LEFT JOIN purchase_order_freetext_parts fp ON fp.po_item_id = m.id
    WHERE m.po_id = '$po_id_int'
");
?>

<style>
body { font-family: Arial, sans-serif; background-color: #f4f6f9; }
#slipModal {
    display: none; position: fixed; z-index: 1000;
    top: 50%; left: 50%; transform: translate(-50%, -50%);
    width: 60%; background: white;
    box-shadow: 0px 4px 16px rgba(0,0,0,0.2);
    padding: 20px; border-radius: 8px;
}
#slipModalBody { margin-top: 10px; max-height: 300px; overflow-y: auto; }
button { padding: 8px 12px; color: white; border: none; border-radius: 4px; cursor: pointer; }
@media screen and (max-width: 768px) { #slipModal { width: 90%; } }
.bg-light-green { background-color: lightgreen !important; }
.bg-light-red   { background-color: lightcoral !important; }
.bulk-bar {
    background: #f8f9fa; border: 1px solid #dee2e6;
    border-radius: 6px; padding: 10px 16px;
    display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 12px;
}
</style>

<section class="content-header headings">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-9">
                <h1><?= $page_name; ?> - <span class="text-danger"><?= $order_ref; ?></span></h1>
            </div>
            <div class="col-sm-2 text-right">
                <button onclick="viewAllSlips()" class="btn btn-warning">View All Slips</button>
            </div>
            <div class="col-sm-1 text-right">
                <?php
                $query_string = isset($_POST['query_string']) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
                $query_string = str_ireplace("page=item_status", "page=view", $query_string);
                ?>
                <button type="button" class="btn btn-success"
                        onclick="window.location.href='index?<?= $query_string; ?>'">Back</button>
            </div>
        </div>
    </div>
</section>

<section class="content card p-1">
    <div class="row">
        <div class="col-12">

            <div class="bulk-bar">
                <strong><i class="fa fa-boxes"></i> Bulk Actions:</strong>
                <button type="button" class="btn btn-primary" id="bulk_bookin_btn" onclick="bulkBookIn()">
                    <i class="fa fa-check-double"></i> Book In All Lines
                </button>
                <span style="font-size:13px;color:#555;">Submits all lines set to <em>Received</em> with a quantity entered.</span>
                <span id="bulk_progress" style="display:none;color:#555;font-size:13px;"><i class="fas fa-sync-alt fa-spin"></i> Processing...</span>
                <span id="bulk_done"     style="display:none;color:green;font-weight:600;"><i class="fa fa-check-circle"></i> All lines booked in successfully!</span>
                <span id="bulk_errors"   style="display:none;color:red;font-weight:600;"></span>
            </div>

            <div class="table-responsive">
                <table id="example1" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Part Number</th>
                            <th>Description</th>
                            <th>Ordered</th>
                            <th>Received</th>
                            <th>Pending</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="po_items_tbody">
                        <?php while ($order = $orders->fetch_assoc()) {

                            // item_type 6 = freetext/non-stocked: not booked into inventory, skip
                            if ($order['item_type'] == 6) { continue; }

                            $rowClass = '';
                            if ($order['is_reviewed'] == 2) {
                                $rowClass = 'bg-light-red';
                            } elseif ($order['quantity'] - $order['received'] <= 0) {
                                $rowClass = 'bg-light-green';
                            }
                            $pending = $order['quantity'] - $order['received'];
                        ?>
                        <tr class="<?= $rowClass ?>"
                            id="item_row_<?= $order['id'] ?>"
                            data-order-id="<?= $order['id'] ?>"
                            data-po-id="<?= $po_id_int ?>"
                            data-ordered-qty="<?= $order['quantity'] ?>"
                            data-pending-qty="<?= $pending ?>">

                            <!-- resolved_part_number = actual part number string (from JOIN) -->
                            <td><?= htmlspecialchars($order['resolved_part_number']) ?></td>
                            <td><?= $order['description'] ?></td>
                            <td><?= $order['quantity'] ?></td>
                            <td class="received-cell"><?= $order['received'] ?></td>
                            <td class="pending-cell"><?= $pending ?></td>
                            <td>
                                <form method="POST" class="single-line-form"
                                      style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                                    <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                    <input type="hidden" name="po_id"    value="<?= $po_id_int ?>">

                                    <?php $currentAction = $order['is_reviewed']; ?>
                                    <select name="action" class="form-control action-select"
                                            id="actionDropdown_<?= $order['id'] ?>"
                                            onchange="handleActionChange(<?= $order['id'] ?>)"
                                            required style="width:150px;">
                                        <option value="1" <?= ($currentAction == '1') ? 'selected' : '' ?>>Received</option>
                                        <option value="2" <?= ($currentAction == '2') ? 'selected' : '' ?>>To be Reviewed</option>
                                    </select>

                                    <input type="number" name="receive_qty" class="form-control receive-qty-input"
                                           id="receiveQty_<?= $order['id'] ?>" min="1" placeholder="Qty"
                                           style="width:80px;display:<?= ($currentAction == '2') ? 'none' : 'block' ?>"
                                           <?= ($currentAction != '2') ? 'required' : '' ?>>

                                    <input type="text" name="delivery_ref" class="form-control delivery-ref-input"
                                           id="deliveryRef_<?= $order['id'] ?>" placeholder="Delivery Ref"
                                           style="width:140px;display:<?= ($currentAction == '2') ? 'none' : 'block' ?>">

                                    <textarea name="review_notes" rows="1" class="form-control review-notes-input"
                                              id="reviewNotes_<?= $order['id'] ?>" placeholder="Enter review notes"
                                              style="width:200px;display:<?= ($currentAction == '2') ? 'block' : 'none' ?>"><?= $order['review_notes'] ?></textarea>

                                    <button type="submit" class="btn btn-info"
                                            id="submitButton_<?= $order['id'] ?>"
                                            style="padding:5px 10px;">Submit</button>

                                    <span id="row_processing_<?= $order['id'] ?>" style="display:none;color:#555;"><i class="fas fa-sync-alt fa-spin"></i></span>
                                    <span id="row_done_<?= $order['id'] ?>"       style="display:none;color:green;"><i class="fa fa-check-circle"></i></span>
                                    <span id="row_error_<?= $order['id'] ?>"      style="display:none;color:red;"><i class="fa fa-times-circle"></i></span>
                                </form>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>

            <div id="slipModal">
                <h3 id="received_item">All Received Slips</h3>
                <div id="slipModalBody"></div>
                <button onclick="closeModal()" class="close-btn mt-2" style="float:right;">Close</button>
            </div>
        </div>
    </div>
</section>

<style>
#slipModal {
    display:none; position:fixed; top:40%; left:50%;
    transform:translate(-50%,-50%);
    background-color:white; box-shadow:0 4px 8px rgba(0,0,0,0.2);
    padding:20px; border-radius:8px; z-index:9999;
    width:100% !important; max-width:800px;
}
#slipModalBody table { width:100%; border-collapse:collapse; }
#slipModalBody th, #slipModalBody td { text-align:left; padding:10px; border:1px solid #ddd; }
#slipModalBody th { background-color:#f4f4f4; font-weight:bold; }
#slipModalBody tr:nth-child(even) { background-color:#f9f9f9; }
.close-btn { background-color:#ff5c5c; color:white; border:none; padding:10px 20px; border-radius:5px; cursor:pointer; }
</style>

<script type="text/javascript">
function handleActionChange(orderId) {
    const dropdown    = document.getElementById(`actionDropdown_${orderId}`);
    const receiveQty  = document.getElementById(`receiveQty_${orderId}`);
    const deliveryRef = document.getElementById(`deliveryRef_${orderId}`);
    const reviewNotes = document.getElementById(`reviewNotes_${orderId}`);
    const submitBtn   = document.getElementById(`submitButton_${orderId}`);

    if (dropdown.value === '1') {
        receiveQty.style.display  = 'inline-block'; receiveQty.required  = true;
        deliveryRef.style.display = 'inline-block';
        reviewNotes.style.display = 'none';         reviewNotes.required = false;
        submitBtn.style.display   = 'inline-block';
    } else if (dropdown.value === '2') {
        reviewNotes.style.display = 'inline-block'; reviewNotes.required = true;
        receiveQty.style.display  = 'none';         receiveQty.required  = false;
        deliveryRef.style.display = 'none';
        submitBtn.style.display   = 'inline-block';
    }
}

// Overship warning
document.addEventListener('DOMContentLoaded', function(){
    document.querySelectorAll('.single-line-form').forEach(function(form){
        form.addEventListener('submit', function(e){
            var row        = form.closest('tr');
            var pendingQty = parseInt(row.dataset.pendingQty) || 0;
            var action     = form.querySelector('.action-select').value;
            var qtyInput   = form.querySelector('.receive-qty-input');
            var qty        = parseInt(qtyInput ? qtyInput.value : 0) || 0;
            if(action === '1' && pendingQty > 0 && qty > pendingQty){
                e.preventDefault();
                var ok = confirm(
                    '⚠️  OVERSHIP WARNING\n\nYou are booking in ' + qty + ' unit(s), but only ' + pendingQty +
                    ' unit(s) remain (' + (qty - pendingQty) + ' over).\n\nCheck with the storeman.\n\nOK to continue, Cancel to go back.'
                );
                if(ok) form.submit();
            }
        });
    });
});

// Bulk book-in
function bulkBookIn(){
    var linesToProcess = [], skipped = 0;
    $('#po_items_tbody tr').each(function(){
        var orderId     = $(this).data('order-id');
        var poId        = $(this).data('po-id');
        var pendingQty  = parseInt($(this).data('pending-qty')) || 0;
        var action      = $('#actionDropdown_'+orderId).val();
        var qty         = parseInt($('#receiveQty_'+orderId).val()) || 0;
        var deliveryRef = $('#deliveryRef_'+orderId).val() || '';
        if(action === '1' && qty > 0){
            linesToProcess.push({ order_id:orderId, po_id:poId, qty:qty,
                isOver:(pendingQty > 0 && qty > pendingQty), pendingQty:pendingQty, delivery_ref:deliveryRef });
        } else if(action === '1') { skipped++; }
    });

    if(!linesToProcess.length){ alert('No lines ready to book in.'); return; }

    var overshipLines = linesToProcess.filter(function(l){ return l.isOver; });
    var msg = 'Book in ' + linesToProcess.length + ' line(s)?';
    if(skipped) msg += '\n\n('+skipped+' line(s) skipped — no quantity.)';
    if(overshipLines.length){
        msg += '\n\n⚠️  OVERSHIP WARNING\n';
        overshipLines.forEach(function(l){ msg += '  • Line '+l.order_id+': '+l.qty+' unit(s), '+(l.qty-l.pendingQty)+' over.\n'; });
        msg += '\nConfirm with storeman before continuing.';
    }
    if(!confirm(msg)) return;

    $('#bulk_bookin_btn').prop('disabled', true);
    $('#bulk_progress').show(); $('#bulk_done').hide(); $('#bulk_errors').hide();
    var errors = [], processed = 0;

    function processNext(index){
        if(index >= linesToProcess.length){
            $('#bulk_progress').hide(); $('#bulk_bookin_btn').prop('disabled', false);
            if(!errors.length){ $('#bulk_done').show(); setTimeout(function(){ location.reload(); }, 1500); }
            else { $('#bulk_errors').text('Errors on '+errors.length+' line(s): '+errors.join(', ')).show(); setTimeout(function(){ location.reload(); }, 2500); }
            return;
        }
        var line = linesToProcess[index];
        $('#row_processing_'+line.order_id).show();
        $.ajax({
            type:'POST',
            url: site_url+'/modules/purchase_order/index.php?page=ajax_actions&action=bulk_bookin_line',
            data:{ order_id:line.order_id, po_id:line.po_id, qty:line.qty,
                   received_by:<?= $_SESSION['user_id'] ?>, delivery_ref:line.delivery_ref },
            success:function(result){
                try{
                    var res = jQuery.parseJSON(result);
                    $('#row_processing_'+line.order_id).hide();
                    if(res.status === 'success'){
                        $('#row_done_'+line.order_id).show();
                        var $row       = $('#item_row_'+line.order_id);
                        var newReceived = parseInt($row.find('.received-cell').text()) + line.qty;
                        var newPending  = parseInt($row.find('.pending-cell').text())  - line.qty;
                        $row.find('.received-cell').text(newReceived);
                        $row.find('.pending-cell').text(newPending);
                        if(newPending <= 0) $row.removeClass('bg-light-red').addClass('bg-light-green');
                        $('#receiveQty_'+line.order_id).val('');
                        $('#deliveryRef_'+line.order_id).val('');
                    } else { $('#row_error_'+line.order_id).show(); errors.push('Line '+line.order_id); }
                } catch(e){ errors.push('Line '+line.order_id); }
                processed++; processNext(index+1);
            },
            error:function(){ $('#row_processing_'+line.order_id).hide(); $('#row_error_'+line.order_id).show(); errors.push('Line '+line.order_id); processed++; processNext(index+1); }
        });
    }
    processNext(0);
}

function viewAllSlips(){
    const poId = <?= $po_id_int ?>;
    if(!poId){ alert('Invalid Purchase Order ID'); return; }
    $("#slipModalBody").html('<p>Loading...</p>');
    $.ajax({
        type:"POST",
        url: site_url+"/modules/purchase_order/index.php?page=ajax_actions&action=get_all_slips",
        data:{ po_id:poId },
        success:function(result){
            try{
                const r = jQuery.parseJSON(result);
                if(r.status === "success" && Object.keys(r.data).length > 0){
                    let html = '<table class="table table-bordered"><thead><tr><th>Part Number</th><th>Description</th><th>Qty Received</th><th>Delivery Ref</th><th>Received Date</th><th>Received By</th></tr></thead><tbody>';
                    Object.keys(r.data).forEach(function(serial){
                        r.data[serial].forEach(function(slip){
                            $('#received_item').html('Received Items for P/O Number - <span style="color:red">'+slip.order_reff+'</span>');
                            html += '<tr><td>'+slip.part_number+'</td><td>'+slip.description+'</td><td>'+slip.qty_received+'</td><td>'+(slip.supplier_delivery_ref||'<em style="color:#aaa;">—</em>')+'</td><td>'+slip.slip_date+'</td><td>'+slip.received_by+'</td></tr>';
                        });
                    });
                    html += '</tbody></table>';
                    $("#slipModalBody").html(html);
                } else { $("#slipModalBody").html('<p>No slips found.</p>'); }
                $("#slipModal").css("display","block");
            } catch(e){ alert('Error fetching slip data.'); }
        },
        error:function(){ alert('Failed to fetch slip data.'); }
    });
}

function closeModal(){ $("#slipModal").css("display","none"); }
</script>