<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); require_once __DIR__ . '/../includes/db.php'; ?>
<div class="page-purchase_orders">
<div class="container-fluid p-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4>Purchase Orders</h4>
    <button id="btnAddPO" class="btn btn-primary">Add Purchase Order</button>
  </div>
  <div class="card shadow-sm">
    <div class="card-body">
      <div class="d-flex flex-wrap gap-2 align-items-center mb-3">
        <div class="input-group" style="max-width: 420px;">
          <input type="text" id="poSearch" class="form-control" placeholder="Search by PO number, supplier...">
          <button class="btn btn-outline-secondary" id="btnPOSearch"><i class="bi bi-search"></i></button>
        </div>
        <div class="d-flex align-items-center gap-2">
          <span class="badge rounded-pill bg-warning-subtle text-warning border po-filter" data-status="pending">Pending</span>
          <span class="badge rounded-pill bg-info-subtle text-info border po-filter" data-status="confirmed">Confirmed</span>
          <span class="badge rounded-pill bg-secondary-subtle text-secondary border po-filter" data-status="shipped">Shipped</span>
          <span class="badge rounded-pill bg-success-subtle text-success border po-filter" data-status="received">Received</span>
          <span class="badge rounded-pill bg-info border po-filter" data-status="">All</span>
        </div>
        <input type="hidden" id="poStatusFilter" value="">
      </div>
      <div class="table-responsive">
        <table id="po-table" class="table table-hover table-striped table-bordered align-middle">
          <thead>
            <tr>
              <th>PO Number</th>
              <th>Supplier</th>
              <th>Order Date</th>
              <th>Expected Delivery</th>
              <th>Status</th>
              <th>Total Amount</th>
              <th data-orderable="false">Actions</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
  </div>
 </div>

 <input type="hidden" id="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>" />

 <!-- Invoices Modal -->
 <div class="modal fade" id="poInvoicesModal" tabindex="-1" aria-hidden="true">
   <div class="modal-dialog modal-lg">
     <div class="modal-content">
       <div class="modal-header">
         <h5 class="modal-title">Commercial Invoices for <span id="poi_po_no"></span></h5>
         <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
       </div>
       <div class="modal-body">
         <div class="row g-3 mb-3">
           <div class="col-12">
             <form id="poInvoiceUploadForm" enctype="multipart/form-data">
               <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
               <input type="hidden" name="po_id" id="poi_po_id">
               <div class="row g-2 align-items-end">
                 <div class="col-md-3">
                   <label class="form-label">Invoice No</label>
                   <input type="text" class="form-control" name="invoice_no">
                 </div>
                 <div class="col-md-3">
                   <label class="form-label">Invoice Date</label>
                   <input type="date" class="form-control" name="invoice_date">
                 </div>
                 <div class="col-md-3">
                   <label class="form-label">Amount</label>
                   <input type="number" step="0.01" class="form-control" name="amount">
                 </div>
                 <div class="col-md-3">
                   <label class="form-label">Currency</label>
                   <input type="text" class="form-control" name="currency" placeholder="USD">
                 </div>
                 <div class="col-12">
                   <label class="form-label">Upload File</label>
                   <input type="file" class="form-control" name="file" accept="application/pdf,image/*">
                 </div>
                 <div class="col-12">
                   <button type="submit" class="btn btn-primary">Upload</button>
                 </div>
               </div>
             </form>
           </div>
         </div>
         <div class="table-responsive">
           <table class="table table-sm" id="poi_table">
             <thead>
               <tr>
                 <th>No</th>
                 <th>Date</th>
                 <th>Amount</th>
                 <th>File</th>
                 <th>Uploaded</th>
                 <th>Actions</th>
               </tr>
             </thead>
             <tbody></tbody>
           </table>
         </div>
       </div>
       <div class="modal-footer">
         <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
       </div>
     </div>
   </div>
 </div>

 <?php $suppliersRes = db()->query('SELECT id, name, currency FROM suppliers ORDER BY name'); ?>
<div class="modal fade" id="poModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Purchase Order Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="poForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" id="poId" name="id">
          <input type="hidden" id="items_json" name="items_json">
          <div class="row g-3">
            <div class="col-md-6">
              <div class="mb-2">
                <label class="form-label">Order No</label>
                <div class="input-group">
                  <input type="text" class="form-control" id="order_no" name="order_no" placeholder="Auto-generate if left blank">
                  <button class="btn btn-outline-secondary" type="button" id="btnGenPONo">Generate</button>
                </div>
              </div>
              <div class="mb-2">
                <label class="form-label">Supplier Name <span class="text-danger">*</span></label>
                <select class="form-select" id="supplier_id" name="supplier_id" required>
                  <option value="">-- Select Supplier --</option>
                  <?php while($row = $suppliersRes ? $suppliersRes->fetch_assoc() : null): ?>
                    <option value="<?php echo (int)$row['id']; ?>" data-currency="<?php echo htmlspecialchars($row['currency'] ?? 'USD'); ?>"><?php echo htmlspecialchars($row['name']); ?></option>
                  <?php endwhile; ?>
                </select>
              </div>
              <div class="mb-2">
                <label class="form-label">Supplier Email</label>
                <input type="email" class="form-control" id="supplier_email" name="supplier_email" placeholder="Auto-filled from supplier">
              </div>
              <div class="mb-2">
                <label class="form-label">Order Date <span class="text-danger">*</span></label>
                <input type="date" class="form-control" id="order_date" name="order_date" required>
              </div>
              <div class="mb-2">
                <label class="form-label">Status <span class="text-danger">*</span></label>
                <select class="form-select" id="status" name="status" required>
                  <option value="pending">Pending</option>
                  <option value="confirmed">Confirmed</option>
                  <option value="shipped">Shipped</option>
                  <option value="received">Received</option>
                  <option value="cancelled">Cancelled</option>
                </select>
              </div>
              <div class="row g-2">
                <div class="col-md-4">
                  <label class="form-label">Ship Mode</label>
                  <div class="input-group">
                    <select class="form-select" id="ship_mode" name="ship_mode"></select>
                    <button class="btn btn-outline-primary" type="button" id="btnAddShipMode">Add</button>
                  </div>
                </div>
                <div class="col-md-4">
                  <label class="form-label">Delivery Term</label>
                  <div class="input-group">
                    <select class="form-select" id="delivery_term" name="delivery_term"></select>
                    <button class="btn btn-outline-primary" type="button" id="btnAddDeliveryTerm">Add</button>
                  </div>
                </div>
                <div class="col-md-4">
                  <label class="form-label">Payment Term</label>
                  <div class="input-group">
                    <select class="form-select" id="payment_term" name="payment_term"></select>
                    <button class="btn btn-outline-primary" type="button" id="btnAddPaymentTerm">Add</button>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-2">
                <label class="form-label">Contact Person</label>
                <input type="text" class="form-control" id="supplier_contact" name="supplier_contact" placeholder="Auto-filled from supplier">
              </div>
              <div class="mb-2">
                <label class="form-label">Expected Delivery Date</label>
                <input type="date" class="form-control" id="expected_date" name="expected_date">
              </div>
              <div class="mb-2">
                <label class="form-label">Total Amount (<span class="po-cur-code">USD</span>)</label>
                <div class="input-group">
                  <span class="input-group-text po-currency-prefix">$</span>
                  <input type="number" step="0.01" class="form-control" id="total_amount" name="total_amount" value="0">
                </div>
              </div>
              <div class="mb-2">
                <label class="form-label">Notes</label>
                <textarea class="form-control" id="notes" name="notes" rows="4"></textarea>
              </div>
            </div>
          </div>

          <hr>
          <h6 class="mb-2">Items</h6>
          <div class="table-responsive">
            <table class="table table-sm align-middle" id="po-items-table">
              <thead class="table-light">
                <tr>
                  <th style="width:60px;">No</th>
                  <th>Description</th>
                  <th style="width:120px;">HS Code</th>
                  <th style="width:140px;">Qty(SQM)</th>
                  <th style="width:180px;">Unit Price (<span class="po-cur-code">USD</span>)</th>
                  <th style="width:200px;">Line Total (<span class="po-cur-code">USD</span>)</th>
                  <th style="width:220px;">Note</th>
                  <th style="width:60px;"></th>
                </tr>
              </thead>
              <tbody></tbody>
              <tfoot>
                <tr>
                  <td colspan="5" class="text-end"><strong>Total</strong></td>
                  <td>
                    <div class="input-group">
                      <span class="input-group-text po-currency-prefix">$</span>
                      <input type="number" step="0.01" class="form-control" id="items_total" readonly>
                    </div>
                  </td>
                  <td></td>
                  <td></td>
                </tr>
              </tfoot>
            </table>
          </div>
          <button type="button" class="btn btn-outline-primary btn-sm" id="btnAddItem">Add Item</button>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>
</div>

<!-- DataTables (Bootstrap 5) -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

<script>
  (function(){
    if (!$('.page-purchase_orders').length) return;
    // Delay init slightly so any async row rendering completes
    $(function(){
      setTimeout(function(){
        // Destroy and re-init if already initialized (safety when navigating)
        if ($.fn.DataTable) {
          const existing = $.fn.dataTable.isDataTable('#po-table');
          if (existing) { $('#po-table').DataTable().destroy(); }
          $('#po-table').DataTable({
            dom: 'lfrtip',
            pageLength: 10,
            lengthMenu: [[10,25,50,100,-1],[10,25,50,100,'All']],
            order: [],
            autoWidth: false,
            responsive: true,
            language: { search: 'Filter:' },
            columnDefs: [ { orderable: false, targets: -1 } ]
          });
        }
      }, 100);
    });
  })();
</script>
