<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (isset($_SESSION['aW1iZXN0cmEuY29tLm15']) <> $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']);
} else {
    include "_header2.php";
    include "_navtop.php";
    include "_navside.php";
    include "_functions.php";
    require "conn.php";
?>
<style>
    .badge-custom {
        padding: 8px 12px;
        font-size: 0.9em;
    }
</style>

<div id="page-wrapper">
    <div id="page-inner">
        <div class="row">
            <div class="col-md-12">
                <h2>Packaging List</h2>
            </div>
        </div>
        <hr />

<!-- Filter form -->
<form method="get" class="mb-3">
  <div style="display:flex; gap:20px; flex-wrap:wrap; align-items:flex-end;">

    <div class="form-group mb-2 d-inline-block">
      <label for="invoice_no">Invoice No:</label>
      <input type="text" id="invoice_no" name="invoice_no" 
             value="<?= htmlspecialchars($_GET['invoice_no'] ?? '') ?>" 
             placeholder="Search Invoice No..." 
             class="form-control" 
             style="max-width:200px;">
    </div>

    <div class="form-group mb-2 d-inline-block">
      <label for="month">Month:</label>
      <input type="month" id="month" name="month" 
             value="<?= htmlspecialchars($_GET['month'] ?? '') ?>"
             class="form-control" 
             style="max-width:160px;">
    </div>

    <div class="form-group mb-2 d-inline-block">
      <label for="status">Packaging Status:</label>
            <select id="status" name="status" class="form-control mx-2">
                <option value="">-- All --</option>
                <option value="Pending"     <?= (($_GET['status'] ?? '')=='Pending')?'selected':'' ?>>Pending</option>
                <option value="Processing"  <?= (($_GET['status'] ?? '')=='Processing')?'selected':'' ?>>Processing</option>
                <option value="Packed"      <?= (($_GET['status'] ?? '')=='Packed')?'selected':'' ?>>Packed</option>
            </select>
    </div>

    <div class="form-group mb-2 d-inline-block">
        <button type="submit" class="btn btn-primary">Search</button>
        <a href="<?= basename($_SERVER['PHP_SELF']); ?>" class="btn ml-2 btn-danger"><i class="fa-solid fa-rotate"></i> Reset</a>
        <button id="csvBtn" class="btn btn-info ml-2"><i class="fa-solid fa-file-csv"></i> Export </button>
        <button id="printBtn" type="button" class="btn btn-warning ml-2"><i class="fa-solid fa-print"></i> Print </button>
        
    </div>
  </div>
</form>
        <br>
        <div class="row">
            <div class="col-md-12">
                <!-- Advanced Tables -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        List of All Packaging
                    </div>
                    <div class="panel-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Invoice No</th>
                                        <th>Customer</th>
                                        <th>Date</th>
                                        <th>Package</th>
                                        <th>Product</th>
                                        <th><i class="fa fa-truck"> </i> Shipping Method</th>
                                        <th><i class="fa fa-box">   </i> Packaging Status</th>
                                        <th><center> Action  </center></th>
                                    </tr>
                                </thead>
                                <tbody>
<?php
    $c = 1;
    $where = " WHERE 1=1 ";

    // Role-based filter
    //if ($_SESSION['username'] !== 'admin') {
    //    $aidi = (int)$_SESSION['aidi'];
    //    $where .= " AND i.customer_id = $aidi ";
    //}
    // Role-based filter
    if (!in_array($_SESSION['role'], ['admin', 'packaging', 'cashier'])) {
        $aidi = (int)$_SESSION['aidi'];
        $where .= " AND i.customer_id = $aidi ";
    }
    	

    // filter bulan
    if (!empty($_GET['month'])) {
        $month = mysqli_real_escape_string($con, $_GET['month']);
        $where .= " AND DATE_FORMAT(i.created_at, '%Y-%m') = '$month' ";
    }

    // filter status
    if (!empty($_GET['status'])) {
        $status = mysqli_real_escape_string($con, $_GET['status']);
        $where .= " AND i.packaging_status = '$status' ";
    }
    
    // 🔍 filter invoice_no
    if (!empty($_GET['invoice_no'])) {
        $invoice_no = mysqli_real_escape_string($con, $_GET['invoice_no']);
        $where .= " AND i.invoice_no LIKE '%$invoice_no%' ";
    }

    $sql = "SELECT i.id, i.grand_total, i.package_name, i.package_desc, i.invoice_no, i.customer_id, i.created_at, i.payment_method,
                   i.invoice_status, i.payment_status, i.packaging_status, i.shipping_status, i.delivery_status, i.payment_method, i.shipping_method,
                   a.username
            FROM invoice i
            LEFT JOIN ahli a ON i.customer_id = a.id
            $where
            ORDER BY i.created_at DESC";

    $result = mysqli_query($con, $sql);

    // Function to color code status with icons
        function statusBadge($status, $type='cash') {
            $icon = '';
            switch($type){
                case 'order': $icon = 'fa-tasks'; break;
                case 'invoice': $icon = 'fa-file-invoice'; break;
                case 'payment': $icon = 'fa-dollar-sign'; break;
                case 'transfer': $icon = 'fa-money-bill-transfer'; break;
                case 'cash': $icon = 'fa-money-bill-wave'; break;
                case 'fpx': $icon = 'fa-building-columns'; break;
                case 'packaging': $icon = 'fa-box'; break;
                case 'shipping': $icon = 'fa-truck'; break;
                case 'delivery': $icon = 'fa-check-circle'; break;
            }
        
            // Set colors inline
            switch($status){
                        case 'Pending':     $color = '#ffc107'; // amber - waiting for payment/action
                            break;
                        case 'Processing':  $color = '#0dcaf0'; // light blue - in progress
                            break;
                        case 'Paid':        $color = '#28a745'; // green - payment successful
                            break;
                        case 'Packed':      $color = '#28a745'; // green - item packed
                            break;
                        case 'Shipped':     $color = '#28a745'; // green - shipped out
                            break;
                        case 'In Transit':  $color = '#0d6efd'; // blue - on the way
                            break;
                        case 'Delivered':   $color = '#198754'; // dark green - delivered successfully
                            break;
                        case 'Completed':   $color = '#28a745'; // green - order completed
                            break;
                        case 'Waiting':      $color = '#6c757d'; // gray - standby
                            break;
                        case 'Failed':      $color = '#dc3545'; // red - failed
                            break;
                        case 'Cancelled':   $color = '#212529'; // black - cancelled
                            break;
                        case 'Issued':      $color = '#007bff'; // blue - invoice issued
                            break;
                        case 'Refund':      $color = '#6f42c1'; // purple - refund in process
                            break;
                        default:            $color = '#adb5bd'; // light gray - unknown status
                            break;
                    }
        
            return '<span class="badge badge-custom" style="
                        background-color: '.$color.';
                        color: #fff;
                        padding: 0.4em 0.75em;
                        font-size: 0.9em;
                        border-radius: 1rem;">
                        <i class="fa-solid '.$icon.'"></i></span> '.htmlspecialchars($status);
        }


    while ($row = mysqli_fetch_assoc($result)) {

    // Decode JSON products (assume saved in invoice table column `products`)
    $productList = [];
    if (!empty($row['package_desc'])) { // <-- if you actually store JSON here, change to correct column name
        $items = json_decode($row['package_desc'], true);

        if (is_array($items)) {
            $ids = array_column($items, 'product_id');
            if (!empty($ids)) {
                $idList = implode(",", array_map('intval', $ids));
                $sqlProd = "SELECT id, product_name FROM products WHERE id IN ($idList)";
                $resProd = mysqli_query($con, $sqlProd);

                $productMap = [];
                while ($p = mysqli_fetch_assoc($resProd)) {
                    $productMap[$p['id']] = $p['product_name'];
                }

                foreach ($items as $it) {
                    $pid  = (int)$it['product_id'];
                    $qty  = (int)$it['qty'];
                    $name = $productMap[$pid] ?? 'Unknown';
                    $productList[] = $name . " (x" . $qty . ")";
                }
            }
        }
    }

    $productDisplay = !empty($productList) ? implode("<br>", $productList) : "-";   
        
            // 🧩 Extract values
            $shipping_method  = strtolower(trim($row['shipping_method']));
            $payment_method   = strtolower(trim($row['payment_method']));
           
            // ✅ Font Awesome icon sets
            $icons = [
                      'shipping' => [
                        'selfcollect' => '<i class="fa-solid fa-store text-primary"></i> Self Collect',
                        'courier'     => '<i class="fa-solid fa-truck text-success"></i> Courier',
                        'default'     => '<i class="fa-solid fa-box text-secondary"></i> Other'
                      ],
                      'payment' => [
                        'cash'          => '<i class="fa-solid fa-money-bill-wave text-success"></i> Cash',
                        'transfer'      => '<i class="fa-solid fa-building-columns text-info"></i> Bank Transfer',
                        'onlinebanking' => '<i class="fa-solid fa-laptop text-warning"></i> Online Banking',
                        'default'       => '<i class="fa-solid fa-credit-card text-muted"></i> Payment'
                      ]
                    ];
    
            
            $shipping_icon = $icons['shipping'][$shipping_method] ?? $icons['shipping']['default'];
            $payment_icon  = $icons['payment'][$payment_method] ?? $icons['payment']['default'];
        
        
        
        
?>
                                    <tr>
                                        <td><?= $c++ ?></td>
                                        <td><?= htmlspecialchars($row['invoice_no']) ?></td>
                                        <td><code><?= htmlspecialchars($row['username'] ?? '-') ?></code></td>
                                        <td><?= date("d/m/Y", strtotime($row['created_at'])) ?></td>
                                        <td><?= $row['package_name'] ?></td>
                                        <td><?= $productDisplay ?></td>
                                        <td><?= $shipping_icon ?></td>
                                        <td class="packaging_status"><?= statusBadge($row['packaging_status'], 'packaging') ?></td>
                                        
                                        <td style="padding:5px; text-align:center; vertical-align: middle;">
                                            <div style="display: flex; align-items: center; justify-content: center; gap: 10px;">
                                                <!-- Action column icon -->
                                                <a href="#" 
                                                       data-toggle="modal" 
                                                       data-target="#PackagingModal" 
                                                       data-invoice="<?= htmlspecialchars($row['invoice_no']) ?>"
                                                       title="Payment Confirmation">
                                                        <i class="fa-2x fa-solid fa-qrcode text-primary"></i>
                                                </a>
                                            </div>
                                        </td>



                                    </tr>
<?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <!--End Advanced Tables -->
            </div>
        </div>
    </div>
    <!-- /. PAGE INNER  -->
</div>


                                            <!-- Packaging Modal -->
<div class="modal fade" id="PackagingModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header" style="background:#222d32;color:#b8c7ce;">
          <h5 class="modal-title">Packaging Label</h5>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <div class="modal-body">
          <input type="hidden" name="invoice_no" id="pkgInvoiceNo">

          
          <!-- Label Info -->
          <div class="col-md-12">
              <fieldset style="border:1px solid #ccc; padding:15px; margin-bottom:15px; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                <legend style="padding:0 10px; font-size:12px; border:none; width:auto;"> Packaging Details </legend>
                <div id="printLabelArea" class="col-md-12">
                    <!-- Flex Container -->
                    <div style="display:flex; align-items:center; gap:20px;">
                      
                      <!-- QR Preview -->
                      <div>
                        <img id="pkgQrImage" src="" alt="QR Code" style="height:100px; width:100px;">
                      </div>
                
                      <!-- Details -->
                      <div>
                        <h3>
                          <strong><span id="pkgInvoiceText" style="color:red;"></span></strong>
                        </h3>
                        <div class="text-muted" style="font-size:20px;">
                          <span id="pkgNameText"></span>
                        </div>
                      </div>
                
                    </div>
                </div>
              </fieldset>
            </div>

        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-success" onclick="printLabel()">
            <i class="fa fa-print"></i> Print
          </button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </div>
  </div>
</div>

<script>
  // Show modal and load data
  $('#PackagingModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var invoice = button.data('invoice');
    var pkgName = button.closest('tr').find('td:nth-child(5)').text();

    $('#pkgInvoiceNo').val(invoice);
    $('#pkgInvoiceText').text(invoice);
    $('#pkgNameText').text(pkgName);   // ✅ Show package name

    // Load QR Code
    var imgPath = 'temp/img/qrcode/' + invoice + '.png';
    $('#pkgQrImage').attr('src', imgPath).show();

    // Fetch product data from server
    $.getJSON('get_product.php', { invoice_no: invoice }, function(res) {
      if(res.success) {
        var rows = "";
        var totalQty = 0;

        if(res.products && res.products.length > 0) {
          res.products.forEach(function(p) {
            rows += "<tr><td>" + p.product_name + "</td><td class='text-center'>" + p.qty + "</td></tr>";
            totalQty += parseInt(p.qty);
          });
        } else {
          rows = "<tr><td colspan='2' class='text-center text-muted'>No products found</td></tr>";
        }

        $("#pkgProductList").html(rows);
        $("#pkgItemCount").text(res.products.length);
        $("#pkgTotalQty").text(totalQty);
      } else {
        $("#pkgProductList").html("<tr><td colspan='2' class='text-center text-danger'>Data not found</td></tr>");
        $("#pkgItemCount").text("-");
        $("#pkgTotalQty").text("-");
      }
    }).fail(function() {
      $("#pkgProductList").html("<tr><td colspan='2' class='text-center text-danger'>Failed to load</td></tr>");
    });
  });
  
  
document.getElementById("printBtn").addEventListener("click", function(e) {
  e.preventDefault();

  let rows = document.querySelectorAll("#dataTables-example tbody tr");
  if (rows.length === 0) {
    alert("No data found to print.");
    return;
  }

  // Build all labels
  let allContent = "";
  rows.forEach(row => {
    let invoice = row.querySelector("td:nth-child(2)").innerText.trim();
    let pkgName = row.querySelector("td:nth-child(5)").innerText.trim();

    allContent += `
      <div class="label">
        <div class="qr">
          <img src="temp/img/qrcode/${invoice}.png" alt="${invoice}">
        </div>
        <div class="details">
          <h3>${invoice}</h3>
          <div>${pkgName}</div>
        </div>
      </div>
    `;
  });

  // Open print window
  let printWindow = window.open('', '', 'height=800,width=1000');
  printWindow.document.write('<html><head><title>Print Labels</title>');
  printWindow.document.write(`
    <style>
      /* 🔑 Set label size: change to match your roll (e.g. 100mm x 50mm, 58mm x 40mm) */
      @page {
        size: 50mm 30mm;
        margin: 0;
      }
      body {
        margin: 0;
        padding: 0;
        font-family: Arial, sans-serif;
      }
      .label {
        width: 50mm;
        height: 30mm;
        padding: 2mm;
        display: flex;
        align-items: center;
        gap: 5px;
        box-sizing: border-box;
        page-break-after: always;
      }
      .qr img {
        width: 15mm;
        height: 15mm;
      }
      .details {
        font-size: 10px;
        line-height: 1.2em;
        flex: 1;
        overflow: hidden;
      }
      .details h3 {
        margin: 0;
        font-size: 12px;
        color: red;
      }
      .details div {
        font-size: 10px;
        color: #333;
      }
    </style>
  `);
  printWindow.document.write('</head><body>');
  printWindow.document.write(allContent);
  printWindow.document.write('</body></html>');
  printWindow.document.close();

  // Auto print & close
  printWindow.onload = function() {
    printWindow.focus();
    printWindow.print();
    printWindow.onafterprint = function() {
      printWindow.close();
      showPrintSuccess(); // your custom success alert
    };
  };
});

  
  
function printLabel() {
  var content = document.getElementById("printLabelArea").outerHTML;

  var printWindow = window.open('', '', 'height=600,width=800');
  printWindow.document.write('<html><head><title>Print Label</title>');
  printWindow.document.write('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">');
  printWindow.document.write('<style> body { padding:30px; font-family:Arial; } h3{margin:0;} </style>');
  printWindow.document.write('</head><body>');
  printWindow.document.write(content);
  printWindow.document.write('</body></html>');
  printWindow.document.close();

  printWindow.onload = function() {
    printWindow.focus();
    printWindow.print();

    // ✅ Detect when print is finished
    printWindow.onafterprint = function() {
      printWindow.close();

      // Close the modal
      $('#PackagingModal').modal('hide');

      // Show success message
      showPrintSuccess();
    };
  };
}

// ✅ Reusable success notification
function showPrintSuccess() {
  let alertBox = document.createElement("div");
  alertBox.className = "alert alert-success alert-dismissible fade show";
  alertBox.style.position = "fixed";
  alertBox.style.top = "20px";
  alertBox.style.right = "20px";
  alertBox.style.zIndex = "9999";
  alertBox.innerHTML = `
    <strong>✅ Print Success!</strong> Your packaging label has been printed.
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  `;
  document.body.appendChild(alertBox);

  // Auto remove after 3 sec
  setTimeout(() => {
    alertBox.remove();
  }, 3000);
}
</script>



<?php
    include "_footer2.php";
}
?>
