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

 $activePage = 'po_list';
 $pageTitle = $lang[$current_lang]['po_list'];

// Query Utama: Langsung ambil supplier_name dari tabel PO
 $stmt = $pdo->query("
    SELECT 
        po.id,
        po.po_number,
        po.date,
        po.supplier_name,
        po.status,
        po.comments,
        poi.item_code,
        poi.item_name,
        poi.qty,
        poi.unit,
        poi.price
    FROM purchase_orders po
    LEFT JOIN purchase_order_items poi ON po.id = poi.po_id
    ORDER BY po.date DESC, po.id DESC
");
 $po_data = $stmt->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>
        .action-buttons { display: flex !important; flex-wrap: nowrap !important; gap: 4px; align-items: center; justify-content: center; }
        .action-buttons .btn { padding: 0.25rem 0.5rem; font-size: 0.8rem; }
        .table td, .table th { white-space: nowrap; vertical-align: middle; }
        
        .btn-import { background: linear-gradient(135deg, #198754, #157347); border: none; color: #fff; }
        .btn-import:hover { background: linear-gradient(135deg, #157347, #146c43); color: #fff; transform: translateY(-2px); box-shadow: 0 4px 15px rgba(25, 135, 84, 0.4); }
    </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">Kelola Purchase Order Barang</p>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <?php if ($_SESSION['role'] == 'admin'): ?>
                        <button class="btn btn-success btn-import" data-bs-toggle="modal" data-bs-target="#modalImport">
                            <i class="mdi mdi-file-excel"></i> Import XLS
                        </button>
                        <?php endif; ?>

                        <?php if ($_SESSION['role'] !== 'guest'): ?>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalForm">
                            <i class="mdi mdi-plus"></i> <?= $lang[$current_lang]['add_new'] ?>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="card fade-in">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table data-table" style="width: 100%;">
                                <thead>
                                    <tr>
                                        <th width="50">No</th>
                                        <th><?= $lang[$current_lang]['po_number'] ?></th>
                                        <th><?= $lang[$current_lang]['po_date'] ?></th>
                                        <!-- KOLOM SUPPLIER (LANGSUNG DARI DB) -->
                                        <th><?= $lang[$current_lang]['supplier'] ?? 'Supplier' ?></th>
                                        <th>Kode Barang</th>
                                        <th>Nama Barang</th>
                                        <th>Qty</th>
                                        <th>Unit</th>
                                        <th>Harga</th>
                                        <th>Status</th>
                                        <th>Komentar</th>
                                        <th width="100" class="text-center"><?= $lang[$current_lang]['action'] ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $no=1; foreach($po_data as $row): ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><strong><?= htmlspecialchars($row['po_number']) ?></strong></td>
                                        <td><?= date('d M Y', strtotime($row['date'])) ?></td>
                                        <!-- DATA SUPPLIER -->
                                        <td><?= htmlspecialchars($row['supplier_name'] ?? '-') ?></td>
                                        <td><?= htmlspecialchars($row['item_code']) ?></td>
                                        <td><?= htmlspecialchars($row['item_name']) ?></td>
                                        <td><?= $row['qty'] ?></td>
                                        <td><?= htmlspecialchars($row['unit']) ?></td>
                                        <td><?= number_format($row['price'], 0, ',', '.') ?></td>
                                        <td>
                                            <?php 
                                            $status_class = 'bg-secondary';
                                            if($row['status'] == 'pending') $status_class = 'bg-warning';
                                            if($row['status'] == 'completed') $status_class = 'bg-success';
                                            if($row['status'] == 'partial') $status_class = 'bg-info';
                                            ?>
                                            <span class="badge <?= $status_class ?>"><?= $lang[$current_lang][$row['status']] ?? ucfirst($row['status']) ?></span>
                                        </td>
                                        <td><?= htmlspecialchars($row['comments']) ?></td>
                                        <td>
                                            <?php if ($_SESSION['role'] == 'admin'): ?>
                                            <div class="action-buttons">
                                                <button class="btn btn-sm btn-secondary" onclick='editData(<?= json_encode($row) ?>)' title="Edit">
                                                    <i class="mdi mdi-pencil"></i>
                                                </button>
                                                <form action="../post/po_action.php" method="POST" class="d-inline" id="formDel_<?= $row['id'] ?>">
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                                    <button type="button" class="btn btn-sm btn-danger btn-delete" onclick="confirmDeletePO('formDel_<?= $row['id'] ?>', '<?= $row['po_number'] ?>')">
                                                        <i class="mdi mdi-trash-can"></i>
                                                    </button>
                                                </form>
                                            </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- MODAL IMPORT XLS -->
            <div class="modal fade" id="modalImport" 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 Data PO</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <form action="../post/po_import.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_po.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,.csv" required>
                                <small class="text-danger">Kolom Supplier diisi manual di file Excel.</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>

            <!-- MODAL ADD/EDIT -->
            <div class="modal fade" id="modalForm" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="modalTitle">Tambah PO</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <form action="../post/po_action.php" method="POST" id="formPO">
                            <div class="modal-body">
                                <input type="hidden" name="action" value="add">
                                <input type="hidden" name="id" id="hiddenId">
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">No PO</label>
                                        <input type="text" name="po_number" id="inputPONumber" class="form-control" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Tanggal</label>
                                        <input type="date" name="date" id="inputDate" class="form-control" required value="<?= date('Y-m-d') ?>">
                                    </div>
                                </div>

                                <!-- INPUT SUPPLIER (TEXT BIASA) -->
                                <div class="mb-3">
                                    <label class="form-label">Nama Supplier</label>
                                    <input type="text" name="supplier_name" id="inputSupplierName" class="form-control" placeholder="Ketik Nama Supplier" required>
                                </div>

                                <hr class="my-2">
                                <h6 class="mb-3 text-muted">Detail Barang</h6>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Kode Barang</label>
                                        <input type="text" name="item_code" id="inputItemCode" class="form-control" placeholder="Scan/Input Kode lalu Enter" required>
                                        <small class="text-muted">Tekan Enter untuk isi otomatis.</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Nama Barang</label>
                                        <input type="text" name="item_name" id="inputItemName" class="form-control" readonly>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Qty</label>
                                        <input type="number" name="qty" id="inputQty" class="form-control" required min="1" value="1">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Unit</label>
                                        <input type="text" name="unit" id="inputUnit" class="form-control" readonly>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Harga</label>
                                        <input type="number" name="price" id="inputPrice" class="form-control" required>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Status</label>
                                    <select name="status" id="inputStatus" class="form-select">
                                        <option value="pending">Pending</option>
                                        <option value="partial">Partial</option>
                                        <option value="completed">Completed</option>
                                    </select>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Komentar</label>
                                    <textarea name="comments" id="inputComments" class="form-control" rows="2"></textarea>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                <button type="submit" class="btn btn-primary">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <?php include 'includes/footer.php'; ?>
        </main>
    </div>
    
    <script>
        // Autofill Logic (Sama seperti sebelumnya)
        $('#inputItemCode').on('keypress blur', function(e) {
            if (e.type === 'blur' || e.which === 13) {
                e.preventDefault();
                var code = $(this).val().trim();
                if(code.length > 0) {
                    $.ajax({
                        url: '../get/get_item_by_code.php',
                        type: 'GET',
                        data: { code: code },
                        dataType: 'json',
                        success: function(res) {
                            if(res.status === 'success') {
                                $('#inputItemName').val(res.data.name);
                                $('#inputUnit').val(res.data.unit);
                                $('#inputPrice').val(res.data.price);
                                $('#inputQty').focus().select();
                            } else {
                                $('#inputItemName').val('').prop('readonly', false);
                                $('#inputUnit').val('').prop('readonly', false);
                                $('#inputPrice').val('');
                                $('#inputItemName').focus();
                            }
                        }
                    });
                }
            }
        });

        // Edit Data Logic
        function editData(data) {
            $('#modalTitle').text('Edit PO');
            $('input[name="action"]').val('edit');
            $('#hiddenId').val(data.id);
            
            $('#inputPONumber').val(data.po_number);
            $('#inputDate').val(data.date);
            
            // Set Supplier Name Value
            $('#inputSupplierName').val(data.supplier_name);

            $('#inputStatus').val(data.status);
            $('#inputComments').val(data.comments);
            
            $('#inputItemCode').val(data.item_code);
            $('#inputItemName').val(data.item_name);
            $('#inputUnit').val(data.unit);
            $('#inputQty').val(data.qty);
            $('#inputPrice').val(data.price);
            
            $('#inputItemName').prop('readonly', true);
            $('#inputUnit').prop('readonly', true);
            
            var modal = new bootstrap.Modal(document.getElementById('modalForm'));
            modal.show();
        }

        // Reset Form
        document.getElementById('modalForm').addEventListener('hidden.bs.modal', function () {
            document.getElementById('formPO').reset();
            $('#modalTitle').text('Tambah PO');
            $('input[name="action"]').val('add');
            $('#hiddenId').val('');
            $('#inputSupplierName').val(''); // Reset text input
            $('#inputItemName').prop('readonly', true);
            $('#inputUnit').prop('readonly', true);
        });

        // Delete Confirmation
        function confirmDeletePO(formId, itemName) {
            Swal.fire({
                title: 'Hapus Data?',
                text: "PO \""+itemName+"\" akan dihapus permanen!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Hapus!',
                cancelButtonText: 'Batal',
                customClass: { confirmButton: 'btn btn-danger me-2', cancelButton: 'btn btn-secondary' },
                buttonsStyling: false
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById(formId).submit();
                }
            });
        }
    </script>
</body>
</html>