<?php
// view/transaksi_penerimaan.php
require_once '../config/config.php';
if (!isset($_SESSION['user_id'])) {
    header('Location: ../index.php');
    exit;
}

 $activePage = 'transaksi_penerimaan';
 $pageTitle = $lang[$current_lang]['goods_receipt'] ?? 'Penerimaan Barang';

 $pos = $pdo->query("SELECT id, po_number, date FROM purchase_orders WHERE status IN ('pending', 'partial') ORDER BY date DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="<?= $current_lang ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= APP_NAME ?> - <?= $pageTitle ?></title>
    
    <!-- CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.2.96/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="../assets/css/dinar.css" rel="stylesheet">

    <style>
        .trans-card { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 16px; padding: 24px; }
        .table input[type="text"], .table input[type="number"] {
            background: var(--input-bg); border: 1px solid var(--input-border); color: var(--text);
            border-radius: 6px; padding: 5px 10px; width: 100%; min-width: 60px;
        }
        .table input:focus { border-color: var(--accent); outline: none; box-shadow: 0 0 0 2px var(--glow); }
        .table input:read-only { background: var(--secondary); opacity: 0.7; cursor: not-allowed; }
        #tableWrapper { display: none; }
        .action-buttons { display: flex !important; flex-wrap: nowrap; justify-content: center; }
        .dataTables_wrapper { width: 100% !important; }

        /* Checkbox Styling */
        .table input[type="checkbox"] { width: 18px !important; height: 18px !important; min-width: auto !important; cursor: pointer !important; }
        .form-check-input { background-color: var(--input-bg) !important; border: 1px solid var(--text-muted) !important; border-radius: 4px; }
        .form-check-input:checked { background-color: var(--accent) !important; border-color: var(--accent) !important; color: white !important; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23ffffff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='m6 10 3 3 6-6'/%3e%3c/svg%3e") !important; }
        .form-check-input:hover { border-color: var(--accent) !important; box-shadow: 0 0 0 2px var(--glow) !important; }
    </style>
</head>

<body data-theme="<?= $current_theme ?>" class="text-size-<?= $current_text_size ?> btn-size-<?= $current_btn_size ?> icon-size-<?= $current_icon_size ?>">

    <div class="app-wrapper">
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        <?php include 'includes/sidebar.php'; ?>
        
        <main class="main-content">
            <?php include 'includes/header.php'; ?>
            
            <div class="page-content">
                <div class="page-header fade-in">
                    <div>
                        <h1 class="page-title"><?= $pageTitle ?></h1>
                        <p class="page-subtitle"><?= $lang[$current_lang]['process_goods_receipt'] ?? 'Proses penerimaan berdasarkan PO' ?></p>
                    </div>
                    
                    <!-- TAMBAHKAN TOMBOL IMPORT -->
                    <div class="d-flex gap-2">
                        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#modalImportReceipt">
                            <i class="mdi mdi-file-excel"></i> Import Data
                        </button>
                    </div>
                </div>

                <div class="trans-card fade-in">
                    <!-- Form Atas -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold"><?= $lang[$current_lang]['po_number'] ?? 'Nomor PO' ?></label>
                            <select id="selectPO" class="form-select select2-modal" required>
                                <option value="">-- Pilih PO Terlebih Dahulu --</option>
                                <?php foreach($pos as $po): ?>
                                    <option value="<?= $po['id'] ?>">
                                        <?= htmlspecialchars($po['po_number']) ?> (<?= date('d M Y', strtotime($po['date'])) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Invoice Number</label>
                            <input type="text" id="inputInvoice" class="form-control" placeholder="Masukkan No. Invoice Supplier">
                        </div>
                    </div>

                    <hr class="my-4" style="border-color: var(--card-border);">

                    <!-- Table Section -->
                    <div id="tableWrapper">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0"><i class="mdi mdi-table me-2"></i>Daftar Item Diterima</h5>
                            <button class="btn btn-danger btn-sm" id="btnDeleteSelected" disabled>
                                <i class="mdi mdi-trash-can"></i> Hapus Terpilih
                            </button>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-bordered" id="tableItems" style="width: 100%;">
                                <thead>
                                    <tr>
                                        <th width="40" class="text-center"><input type="checkbox" class="form-check-input" id="checkAll"></th>
                                        <th width="120">Item Code</th>
                                        <th>Nama Barang</th>
                                        <th width="100">Supplier</th>
                                        <th width="60">Unit</th>
                                        <th width="80">Qty Order</th>
                                        <th width="80">Qty Terima</th>
                                        <th width="100">Harga</th>
                                        <th width="80" class="text-center">Action</th>
                                    </tr>
                                </thead>
                                <tbody id="tbodyItems"></tbody>
                            </table>
                        </div>

                        <div class="d-flex justify-content-end mt-4">
                            <button class="btn btn-success btn-lg" id="btnSaveTransaction">
                                <i class="mdi mdi-content-save"></i> Simpan Transaksi
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- MODAL IMPORT XLS (BARU) -->
            <div class="modal fade" id="modalImportReceipt" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title"><i class="mdi mdi-file-excel me-2"></i>Import Penerimaan Barang</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <form action="../post/import_receipt.php" method="POST" enctype="multipart/form-data">
                            <div class="modal-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <label class="form-label mb-0">Upload File Excel:</label>
                                    <a href="../get/template_receipt.php" class="btn btn-sm btn-outline-success">
                                        <i class="mdi mdi-download"></i> Download Template
                                    </a>
                                </div>
                                <input type="file" name="file_excel" class="form-control" accept=".xls,.xlsx" required>
                                <small class="text-danger d-block mt-2">
                                    * Sistem akan memvalidasi apakah PO dan Barang ada di database.
                                </small>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                <button type="submit" class="btn btn-success">
                                    <i class="mdi mdi-upload"></i> Proses Import
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <?php include 'includes/footer.php'; ?>
        </main>
    </div>
    
    <!-- SCRIPTS -->
    <script>
        $(document).ready(function() {
            // Init Select2
            $('.select2-modal').select2({ theme: 'default', width: '100%' });

            let dataTableInstance = null;

            function initDataTable() {
                if ($.fn.DataTable.isDataTable('#tableItems')) {
                    return $('#tableItems').DataTable();
                } else {
                    return $('#tableItems').DataTable({
                        responsive: false, scrollX: true, pageLength: 10, ordering: false, autoWidth: false,
                        language: { search: "", searchPlaceholder: "Search...", zeroRecords: "No items" },
                        columnDefs: [{ targets: [0, 8], orderable: false, searchable: false }]
                    });
                }
            }

            dataTableInstance = initDataTable();

            $('#sidebarToggle').on('click', function() {
                setTimeout(function() {
                    if (dataTableInstance && $('#tableWrapper').is(':visible')) {
                        dataTableInstance.columns.adjust();
                    }
                }, 350);
            });

            $('#selectPO').on('change', function() {
                const po_id = $(this).val();
                if(dataTableInstance) dataTableInstance.clear().draw();
                $('#tableWrapper').hide();
                if(!po_id) return;

                $('#tableWrapper').slideDown(300, function(){ dataTableInstance.columns.adjust(); });
                
                $.ajax({
                    url: '../get/get_po_items.php', type: 'GET', data: { id: po_id }, dataType: 'json',
                    success: function(res) {
                        dataTableInstance.clear().draw();
                        if(res.status === 'success' && res.items.length > 0) {
                            res.items.forEach(item => {
                                dataTableInstance.row.add([
                                    `<div class="text-center"><input type="checkbox" class="form-check-input row-check"></div>`,
                                    `<input type="text" class="form-control code-input" value="${item.item_code}" readonly>`,
                                    `<input type="text" class="form-control name-input" value="${item.item_name}">`,
                                    `<input type="text" class="form-control supplier-input" value="${item.supplier_name || '-'}" readonly>`,
                                    `<input type="text" class="form-control unit-input" value="${item.unit || '-'}" readonly>`,
                                    `<input type="number" class="form-control text-center qty-order-input" value="${item.qty}" readonly>`,
                                    `<input type="number" class="form-control text-center qty-receive-input" value="${item.qty}" min="0">`,
                                    `<input type="number" class="form-control price-input" value="${item.price}" readonly>`,
                                    `<div class="text-center action-buttons"><button class="btn btn-sm btn-danger btn-remove-row"><i class="mdi mdi-close"></i></button></div>`
                                ]).draw(false);
                            });
                            dataTableInstance.columns.adjust();
                        } else {
                            Swal.fire('Info', 'PO ini tidak memiliki item.', 'info');
                        }
                    }
                });
            });

            $('#tableItems tbody').on('click', '.btn-remove-row', function() {
                dataTableInstance.row($(this).parents('tr')).remove().draw();
            });

            $('#checkAll').on('click', function() {
                let rows = dataTableInstance.rows({ page: 'current' }).nodes();
                $('input.row-check', rows).prop('checked', this.checked);
                toggleDeleteBtn();
            });

            $('#tableItems tbody').on('click', '.row-check', function() {
                if (!this.checked) $('#checkAll').prop('checked', false);
                toggleDeleteBtn();
            });

            function toggleDeleteBtn() {
                $('#btnDeleteSelected').prop('disabled', $('.row-check:checked').length === 0);
            }

            $('#btnDeleteSelected').click(function() {
                dataTableInstance.rows( function ( idx, data, node ) {
                    return $(node).find('.row-check:checked').length > 0;
                } ).remove().draw();
                $('#checkAll').prop('checked', false);
                toggleDeleteBtn();
            });

            // LOGIKA SIMPAN MANUAL (Dengan Validasi)
            $('#btnSaveTransaction').click(function() {
                let items = [];
                let invoiceNo = $('#inputInvoice').val().trim();
                let poId = $('#selectPO').val();

                if(!poId) { Swal.fire('Error', 'Pilih Nomor PO terlebih dahulu.', 'error'); return; }

                let hasError = false; let errorMsg = ""; let hasSelection = false;

                dataTableInstance.rows().every(function() {
                    let $row = $(this.node());
                    let isChecked = $row.find('.row-check').is(':checked');
                    if (isChecked) {
                        hasSelection = true;
                        let qty_receive = parseInt($row.find('.qty-receive-input').val()) || 0;
                        let qty_order   = parseInt($row.find('.qty-order-input').val()) || 0;
                        let code        = $row.find('.code-input').val();
                        let name        = $row.find('.name-input').val();

                        if (qty_receive > qty_order) {
                            hasError = true; errorMsg = `Item "<b>${name}</b>" (${code}) melebihi Qty PO.<br>Maksimal: <b>${qty_order}</b>, Input: <b>${qty_receive}</b>.`;
                            return false;
                        }
                        if (qty_receive <= 0) return;
                        
                        items.push({ code: code, name: name, supplier: $row.find('.supplier-input').val(), unit: $row.find('.unit-input').val(), qty: qty_receive, price: $row.find('.price-input').val() });
                    }
                });

                if (hasError) { Swal.fire('Validasi Gagal', errorMsg, 'warning'); return; }
                if (!hasSelection) { Swal.fire('Peringatan', 'Tidak ada item yang dipilih.', 'warning'); return; }
                if (items.length === 0) { Swal.fire('Peringatan', 'Item yang dipilih memiliki Qty 0.', 'warning'); return; }

                Swal.fire({ title: 'Simpan Transaksi?', text: "Pastikan Qty Terima sudah benar.", icon: 'question', showCancelButton: true, confirmButtonText: 'Ya, Simpan!' }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: '../post/transaksi_action.php', type: 'POST',
                            data: { action: 'save_receipt', po_id: poId, invoice_no: invoiceNo, items: JSON.stringify(items) }, dataType: 'json',
                            success: function(res) {
                                if(res.status === 'success') Swal.fire('Sukses!', res.msg, 'success').then(() => { location.reload(); });
                                else Swal.fire('Gagal', res.msg, 'error');
                            },
                            error: function(xhr) { Swal.fire('Error', 'Server Error', 'error'); }
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>