<?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>Payment 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">Payment 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="Paid" <?= (($_GET['status'] ?? '')=='Paid')?'selected':'' ?>>Paid</option>
                <option value="Failed" <?= (($_GET['status'] ?? '')=='Failed')?'selected':'' ?>>Failed</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 btn-danger">Reset</a>
    </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 Payments
                    </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>Product</th>
                                        <th>Grand Total</th>
                                        <th><i class="fa fa-credit-card"></i> Payment Type</th>
                                        <th><i class="fa fa-dollar-sign"></i> Payment Status</th>
                                        <th>Action</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', 'finance', '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.payment_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.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,
                   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 = '#f0ad4e'; break; // orange
                case 'Processing':   $color = '#0275d8'; break; // blue
                case 'Paid':         $color = '#5cb85c'; break; // green
                case 'Failed':       $color = '#d9534f'; break; // red
                case 'Packed':       $color = '#5bc0de'; break; // light blue
                case 'Shipped':      $color = '#6c757d'; break; // gray
                case 'Delivered':    $color = '#28a745'; break; // green
                case 'Cancelled':    $color = '#dc3545'; break; // red
                case 'Issued':       $color = '#007bff'; break; // primary blue
                case 'Completed':    $color = '#28a745'; break; // green
                default:             $color = '#f8f9fa'; $icon='fa-question-circle'; 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)) {
?>
                                    <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><b>RM <?= number_format($row['grand_total'],2) ?></b></td>
                                        <td><?= $row['payment_method'] ?></td>
                                        <td class="payment_status"><?= statusBadge($row['payment_status'], 'payment') ?></td>
                                        
                                        <td style="padding:5px; text-align:center; vertical-align: middle;">
                                            <div style="display: flex; align-items: center; justify-content: center; gap: 10px;">
                                                <!-- Invoice Icon Always Active -->
                                                <a target="_blank" href="view_invoice.php?invoice=<?= urlencode($row['invoice_no']) ?>" 
                                                   data-toggle="tooltip" 
                                                   title="View Invoice">
                                                    <i class="fa-2x fa-solid fa-file-invoice-dollar action-icon"></i>
                                                </a>
                                        
                                                <?php if ($row['payment_status'] == 'Pending' && $row['payment_method'] == 'transfer') : ?>
                                                    <!-- Upload Receipt -->
                                                    <a href="#" 
                                                       data-toggle="modal" 
                                                       data-target="#uploadModal" 
                                                       data-invoice="<?= htmlspecialchars($row['invoice_no']) ?>"
                                                       title="Upload Receipt">
                                                        <i class="fa-2x fa-solid fa-file-arrow-up" style="color:red;"></i>
                                                    </a>
                                        
                                                <?php elseif (($row['payment_status'] == 'Pending' && $row['payment_method'] == 'cash') && ( ($_SESSION['role']   == 'admin' ) || ($_SESSION['role']   == 'cashier') ) ): ?>
                                                    <!-- Cash Payment -->
                                                    <a href="#" 
                                                       data-toggle="modal" 
                                                       data-target="#payCashModal"
                                                       data-amount="<?= $row['grand_total'] ?>"
                                                       data-invoice="<?= htmlspecialchars($row['invoice_no']) ?>"
                                                       title="Cash Payment">
                                                        <i class="fa-2x fa-solid fa-cash-register" style="color:red;"></i>
                                                    </a>
                                        
                                                <?php elseif ($row['payment_status'] == 'Pending') : ?>
                                                    <!-- Disabled Receipt -->
                                                    <span data-toggle="tooltip" title="Receipt unavailable until payment made">
                                                        <i class="fa-2x fa-solid fa-receipt action-icon" style="color:#ccc; opacity:0.5; cursor:not-allowed;"></i>
                                                    </span>
                                        
                                                <?php elseif ($row['payment_status'] == 'Processing' && $row['payment_method'] == 'transfer') : ?>
                                                    <!-- Transfer Receipt -->
                                                    <a href="#" 
                                                       data-toggle="modal" 
                                                       data-target="#TransReceiptModal" 
                                                       data-invoice="<?= htmlspecialchars($row['invoice_no']) ?>"
                                                       title="Payment Confirmation">
                                                        <i class="fa-2x fa-solid fa-receipt text-muted"></i>
                                                    </a>
                                        
                                                <?php else: ?>
                                                    <!-- Final Receipt -->
                                                    <a target="_blank" href="view_receipt.php?invoice=<?= urlencode($row['invoice_no']) ?>" 
                                                       title="View Receipt">
                                                        <i class="fa-2x fa-solid fa-receipt action-icon"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </td>



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

                                            <!-- Upload Receipt Modal -->
                                                <div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
                                                  <div class="modal-dialog" role="document">
                                                    <form id="uploadForm" method="post" action="pay_receipt.php" enctype="multipart/form-data">
                                                        <div class="modal-content">
                                                            <div class="modal-header" style="background: #222d32; color: #b8c7ce;">
                                                              <h5 class="modal-title" id="uploadModalLabel"> Payment </h5>
                                                              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                <span aria-hidden="true">&times;</span>
                                                              </button>
                                                            </div>
                                                    
                                                            <div class="modal-body">
                                                              <!-- Hidden Invoice -->
                                                              <input type="hidden" name="invoice_no" id="modalInvoiceNo">
                                                    
                                                              <div class="text-center mb-3">
                                                                <span style="font-size:14px;">Invoice NO:</span>
                                                                <h2 class="mt-1" style="color:red;"><strong><span id="textInvoiceNo"></span></strong></h2>
                                                              </div>
                                                              
                                                        <div class="col-md-12" style="padding-top:20px;">
                                                            <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;"> Upload Receipt </legend>
                                                                
                                                                <!-- Preview -->
                                                              <div id="previewContainer" class="text-center mb-3" style="display:none;">
                                                                <img id="previewImage" src="" class="img-thumbnail" style="max-height:200px;" alt="Receipt Preview">
                                                              </div>
                                                                
                                                              <!-- Upload Receipt -->
                                                                <div class="mb-4">
                                                                  <label class="form-label fw-bold"><i class="fa fa-image me-1"></i> Upload Receipt (Image)</label>
                                                                  <input type="file" name="receipt_file" id="receiptFile" accept="image/*" capture="environment" class="form-control form-control-lg" required>
                                                                  <small class="form-text text-muted">Accepted formats: jpg, jpeg, png, heic</small>
                                                                </div>
                                                                <br>
                                                                <div class="row g-3 pt-3">
                                                            
                                                                  <!-- Transfer Date -->
                                                                  <div class="col-md-6">
                                                                    <div class="form-floating">
                                                                      <label for="transferDate"><i class="fa fa-calendar me-1"></i> Transfer Date</label>
                                                                      <input type="date" name="transfer_date" id="transferDate" class="form-control form-control-lg" placeholder="Transfer Date" required>
                                                                      
                                                                    </div>
                                                                  </div>
                                                            
                                                                  <!-- Transfer Time -->
                                                                  <div class="col-md-6">
                                                                    <div class="form-floating">
                                                                      <label for="transferTime"><i class="fa fa-clock me-1"></i> Transfer Time</label>
                                                                      <input type="time" name="transfer_time" id="transferTime" class="form-control form-control-lg" placeholder="Transfer Time" required>
                                                                      
                                                                    </div>
                                                                  </div>
                                                            
                                                                </div>
                                                            </fieldset>
                                                        </div>
                                                    
                                                            <div class="modal-footer">
                                                              <button type="submit" id="submitBtn" class="btn btn-success">
                                                                <span id="btnText">Submit</span>
                                                                <span id="btnSpinner" class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                                                              </button>
                                                              <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                                            </div>
                                                          </div>
                                                        </div>
                                                    </form>
                                                  </div>
                                                </div>
                                                

                                            <!-- Cash Payment Modal -->
                                            <div class="modal fade" id="payCashModal" tabindex="-1" role="dialog" aria-labelledby="payCashModalLabel" aria-hidden="true">
                                              <div class="modal-dialog" role="document">
                                                <form id="payCashForm" class="modal-content">
                                                  <div class="modal-header" style="background:#222d32; color:#b8c7ce;">
                                                    <h5 class="modal-title"><i class="fa fa-cash-register"></i> Payment </h5>
                                                    <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
                                                  </div>
                                            
                                                  <div class="modal-body">
                                            
                                                    <!-- Hidden fields -->
                                                    <input type="hidden" name="invoice_no" id="modalInvoiceNoCash">
                                                    <input type="hidden" name="pay_amount" id="hiddenPayAmount" value="0.00">
                                                    <input type="hidden" name="pay_balance" id="hiddenPayBalance" value="0.00">
                                            
                                                    <!-- Invoice -->
                                                    <div class="text-center mb-4">
                                                      <span style="font-size:14px;">Invoice NO:</span>
                                                      <h2 class="mt-1 text-danger"><strong><span id="displayInvoice"></span></strong></h2>
                                                    </div>
                                                    <div class="col-md-12" style="padding-top:20px;">
                                                        <fieldset style="border:1px solid #ccc; padding-bottom: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;"> Pay CASH </legend>

                                                            <div class="col-md-12" style="padding:10px 50px 10px 50px">
                                                                    <!-- Amount -->
                                                                    <div class="row align-items-center py-3">
                                                                      <div class="col-6 label-col">Amount (RM)</div>
                                                                      <div class="col-6">
                                                                        <input id="amountInput" type="text"
                                                                               class="form-control form-control-xl  text-right"
                                                                               value="0.00" readonly>
                                                                      </div>
                                                                    </div>
                                                            
                                                                    <!-- Pay -->
                                                                    <div class="row align-items-center py-3">
                                                                      <div class="col-6 label-col">Pay (RM)</div>
                                                                      <div class="col-6">
                                                                        <input id="payInput" type="text" class="form-control form-control-xl  text-right" value="0.00" autocomplete="off">
                                                                      </div>
                                                                    </div>
                                                            
                                                                    <!-- Balance -->
                                                                    <div class="row align-items-center py-3">
                                                                      <div class="col-6 label-col">Balance (RM)</div>
                                                                      <div class="col-6">
                                                                        <input id="balanceInput" type="text"
                                                                               class="form-control form-control-xl  text-right"
                                                                                value="0.00" autocomplete="off" readonly>
                                                                      </div>
                                                                    </div>
                                                            
                                                                    <div class="mt-3 text-muted small text-center">
                                                                      Type numbers on phone/PC keypad. Backspace deletes. Enter submits.
                                                                    </div>
                                                                  </div>
                                                        </fieldset>
                                                    </div>
                                                  <div class="modal-footer">
                                                    <button type="submit" class="btn btn-success btn-lg px-4">
                                                      <i class="fa fa-check"></i> Confirm Payment
                                                    </button>
                                                    <button type="button" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button>
                                                  </div>
                                                </form>
                                              </div>
                                                </form>
                                              </div>
                                            </div>

                                            <!-- Receipt Modal -->
                                            <div class="modal fade" id="receiptModal" tabindex="-1" role="dialog">
                                              <div class="modal-dialog modal-lg" role="document" style="max-width:800px;">
                                                <div class="modal-content">
                                                  <div class="modal-header" style="background:#222d32; color:#b8c7ce;">
                                                    <h5 class="modal-title"><i class="fa fa-receipt"></i> Receipt</h5>
                                                    <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
                                                  </div>
                                                  <div class="modal-body p-0">
                                                    <iframe id="receiptFrame" src="" style="width:100%; height:800px; border:none;"></iframe>
                                                  </div>
                                                  <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary btn-lg" data-dismiss="modal">Close</button>
                                                  </div>
                                                </div>
                                              </div>
                                            </div>

                                            <style>
                                              .input-clean {
                                                border: none !important;
                                                box-shadow: none !important;
                                                background: transparent;
                                                font-size: 2rem;
                                                font-weight: bold;
                                                color: #333;
                                              }
                                              .label-col {
                                                font-weight: bold;
                                                font-size: 1.1rem;
                                              }
                                              #payInput {
                                                background-color: #E8E8E8; /* light grey */
                                              }
                                              .form-control-xl {
                                                font-size: 3rem;       /* large text */
                                                height: 100px;         /* tall box */
                                                padding: 20px;         /* inner space */
                                                border-radius: 12px;   /* nice corners */
                                                width: 100%;           /* always full width */
                                                max-width: 100%;       /* no overflow */
                                              }
                                            
                                              /* Responsive adjustments */
                                              @media (max-width: 768px) {
                                                .form-control-xl {
                                                  font-size: 2rem;     /* slightly smaller on tablets */
                                                  height: 80px;
                                                  padding: 15px;
                                                }
                                              }
                                            
                                              @media (max-width: 480px) {
                                                .form-control-xl {
                                                  font-size: 1.5rem;   /* smaller on mobile */
                                                  height: 70px;
                                                  padding: 12px;
                                                }
                                              }
                                            </style>
                                            
                                            <script>
                                            (function(){
                                              const modal = $('#payCashModal');
                                              const invoiceEl = document.getElementById('displayInvoice');
                                              const modalInvoiceNoCash = document.getElementById('modalInvoiceNoCash');
                                              const amountInput = document.getElementById('amountInput');
                                              const payInput = document.getElementById('payInput');
                                              const balanceInput = document.getElementById('balanceInput');
                                              const hiddenPay = document.getElementById('hiddenPayAmount');
                                              const hiddenBal = document.getElementById('hiddenPayBalance');
                                            
                                              let raw = ""; // raw digits in cents
                                              let amount = 0.00;
                                              let ignoreNextInputEvent = false;
                                            
                                              const fmt = v => Number(v).toLocaleString('en-MY', {minimumFractionDigits:2, maximumFractionDigits:2});
                                              const centsToRinggit = s => s ? parseInt(s,10)/100 : 0.00;
                                            
                                              function render(){
                                                const pay = centsToRinggit(raw);
                                                payInput.value = fmt(pay);
                                                hiddenPay.value = pay.toFixed(2);
                                                const bal = pay - amount;
                                                balanceInput.value = fmt(bal);
                                                hiddenBal.value = fmt(bal);
                                              }
                                            
                                              function pushDigit(d){
                                                raw = (raw + d).replace(/^0+/, '');
                                                if(raw.length>12) raw = raw.slice(-12);
                                                render();
                                              }
                                            
                                              function backspace(){
                                                raw = raw.slice(0,-1);
                                                render();
                                              }
                                            
                                              function reset(){
                                                raw = "";
                                                payInput.value = "0.00";
                                                hiddenPay.value = "0.00";
                                                balanceInput.value = "0.00";
                                                hiddenBal.value = "0.00";
                                              }
                                            
                                              // open modal
                                              modal.on('show.bs.modal', function(e){
                                                const trg = e.relatedTarget;
                                                modalInvoiceNoCash.value = trg.getAttribute('data-invoice')||'';
                                                invoiceEl.textContent = modalInvoiceNoCash.value || '-';
                                                amount = parseFloat(trg.getAttribute('data-amount')) || 0;
                                                amountInput.value = fmt(amount);
                                                reset();
                                                setTimeout(()=>{ payInput.focus(); },200);
                                              });
                                            
                                              // keyboard
                                              payInput.addEventListener('keydown', function(e){
                                                if(e.key >= '0' && e.key <= '9'){ e.preventDefault(); pushDigit(e.key); }
                                                else if(e.key==='Backspace' || e.key==='Delete'){ e.preventDefault(); backspace(); }
                                                else if(e.key==='Enter'){ return; } 
                                                else { e.preventDefault(); }
                                              });
                                            
                                              payInput.addEventListener('input', function(){
                                                if(ignoreNextInputEvent){ ignoreNextInputEvent=false; return; }
                                                const digits = this.value.replace(/\D/g,'');
                                                raw = digits;
                                                render();
                                              });
                                            
                                              payInput.addEventListener('paste', function(e){
                                                e.preventDefault();
                                                const txt = (e.clipboardData||window.clipboardData).getData('text')||'';
                                                const digits = txt.replace(/\D/g,'');
                                                raw = (raw+digits).replace(/^0+/, '');
                                                render();
                                              });
                                            
                                            })();
                                            document.addEventListener("DOMContentLoaded", function() {
                                                document.getElementById("payInput").focus();
                                            });
                                            // Auto-select all text on focus
                                            payInput.addEventListener('focus', function(){
                                              this.select();
                                            });
                                            
                                            // Submit via AJAX
                                            $('#payCashForm').submit(function(e){
                                                e.preventDefault();
                                        
                                                $.ajax({
                                                    url: 'pay_cash.php',
                                                    type: 'POST',
                                                    data: $(this).serialize(),
                                                    dataType: 'json',
                                                    success: function(data){
                                                        if(data.status === "success"){
                                                            $('#payCashModal').modal('hide');
                                                            
                                                            // Load receipt in iframe
                                                            $('#receiptFrame').attr('src', "https://vip.tls2u.com/view_receipt.php?invoice=" + encodeURIComponent(data.invoice));
                                                    
                                                            // Show modal
                                                            $('#receiptModal').modal('show');
                                                    
                                                            // When iframe loads, trigger print
                                                            $('#receiptFrame').off('load').on('load', function() {
                                                                this.contentWindow.focus();  // focus iframe
                                                                this.contentWindow.print();  // auto print
                                                            });
                                                    
                                                            // Reload page when modal closes
                                                            $('#receiptModal').off('hidden.bs.modal').on('hidden.bs.modal', function(){
                                                                location.reload();
                                                            });
                                                            
                                                        } else {
                                                            alert("Error: " + data.message);
                                                        }
                                                    },
                                                    error: function(xhr, status, error){
                                                        alert("AJAX Error: " + error + "\nResponse: " + xhr.responseText);
                                                    }
                                                });
                                            });

                                            
                                            
                                            </script>






                                            <!-- Preview Transfer Receipt Modal -->
                                                <div class="modal fade" id="TransReceiptModal" tabindex="-1" role="dialog">
                                                  <div class="modal-dialog" role="document">
                                                    <form id="uploadFormView" method="post" action="pay_validate.php" enctype="multipart/form-data">
                                                      <div class="modal-content">
                                                        <div class="modal-header" style="background:#222d32;color:#b8c7ce;">
                                                          <h5 class="modal-title">Payment</h5>
                                                          <button type="button" class="close" data-dismiss="modal">&times;</button>
                                                        </div>
                                                
                                                            <div class="modal-body">
                                                              <input type="hidden" name="invoice_no" id="viewInvoiceNo">
                                                
                                                                <div class="text-center mb-3">
                                                                <span>Invoice NO:</span>
                                                                <h2 style="color:red;">
                                                                  <strong><span id="viewInvoiceText"></span></strong>
                                                                </h2>
                                                              </div>
                                                              
                                                              <div class="col-md-12" style="padding-top:20px;">
                                                                 <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;"> Payment Confirmation </legend>

                                                                      <!-- Preview Slip -->
                                                                    <div id="receiptPreviewContainers" class="text-center mb-3">
                                                                        <img id="receiptPreviewImages" src="" class="img-thumbnail" style="max-height:200px; display:none;" alt="Receipt Preview">
                                                                    </div>
                                                                    
                                                              
                                                                    <div class="row justify-content-center text-center " style="margin-left:100px; padding-top:20px;">
                                                                      <div class="pl-3 col-md-5 text-left">
                                                                        <div class="form-group">
                                                                          <label class="mb-1"><i class="fa fa-calendar"></i> Transfer Date</label>
                                                                          <div id="transferDate" class="font-weight-bold">-</div>
                                                                        </div>
                                                                      </div>
                                                                    
                                                                      <div class="pl-3 col-md-5 text-left">
                                                                        <div class="form-group">
                                                                          <label class="mb-1"><i class="fa fa-clock"></i> Transfer Time</label>
                                                                          <div id="transferTime" class="font-weight-bold">-</div>
                                                                        </div>
                                                                      </div>
                                                                    </div>
                                                                    
                                                                    <div class="row justify-content-center text-center" style="margin-left:100px; ">
                                                                      <div class="pl-3 col-md-5 text-left">
                                                                        <div class="form-group">
                                                                          <label class="mb-1"><i class="fa fa-money-bill"></i> Amount to Pay</label>
                                                                          <div class="font-weight-bold text-success">RM <span id="amountPay" >0.00</span></div>
                                                                        </div>
                                                                      </div>
                                                                    
                                                                      <div class="pl-3 col-md-5 text-left">
                                                                        <div class="form-group">
                                                                          <label class="mb-1"><i class="fa fa-credit-card"></i> Payment Method</label>
                                                                          <div id="paymentMethod" class="font-weight-bold">-</div>
                                                                        </div>
                                                                      </div>
                                                                    </div>
                                                                </fieldset>
                                                              </div>
                                                            </div>
                                                            <div class="modal-footer">
                                                              <button type="submit" name="action" value="reject" class="btn btn-danger">Reject</button>
                                                              <button type="submit" name="action" value="valid" class="btn btn-success">Valid</button>
                                                              <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                                            </div>
                                                        </div>
                                                    </form>
                                                  </div>
                                                </div>



                                                
                                                <script>
                                                    // Set invoice number when modal opens
                                                    $('#uploadModal').on('show.bs.modal', function (event) {
                                                      var button = $(event.relatedTarget);
                                                      var invoice = button.data('invoice');
                                                      
                                                      // match IDs in your HTML
                                                      $('#modalInvoiceNo').val(invoice);
                                                      $('#textInvoiceNo').text(invoice);
                                                      $('#previewContainer').hide();
                                                    });
                                                    
                                                    // Set invoice number when modal opens
                                                    $('#payCashModal').on('show.bs.modal', function (event) {
                                                      var button = $(event.relatedTarget);
                                                      var invoice = button.data('invoice');
                                                      
                                                      // match IDs in your HTML
                                                      $('#modaCashlInvoiceNo').val(invoice);
                                                      $('#textCashInvoiceNo').text(invoice);
                                                      $('#previewCashContainer').hide();
                                                    });
                                                    
                                                    $('#TransReceiptModal').on('show.bs.modal', function (event) {
                                                        var modal = $(this); // scope everything to this modal
                                                        var button = $(event.relatedTarget);
                                                        var invoice = button.data('invoice');
                                                    
                                                        // Reset modal fields
                                                        modal.find('#viewInvoiceNo').val(invoice);
                                                        modal.find('#viewInvoiceText').text(invoice);
                                                        modal.find('#transferDate').text('-');
                                                        modal.find('#transferTime').text('-');
                                                        modal.find('#amountPay').text('0.00');
                                                        modal.find('#paymentMethod').text('-');
                                                        modal.find('#receiptPreviewImages').hide();
                                                    
                                                        // Check if receipt exists
                                                        var imgPath = 'uploads/receipts/' + invoice + '.jpg';
                                                        $.get(imgPath)
                                                            .done(function() {
                                                                modal.find('#receiptPreviewImages').attr('src', imgPath).show();
                                                            })
                                                            .fail(function() {
                                                                modal.find('#receiptPreviewImages').hide();
                                                            });
                                                    
                                                        // Fetch invoice data via AJAX
                                                        $.getJSON('get_invoice.php', { invoice_no: invoice })
                                                            .done(function(res) {
                                                                if(res.success) {
                                                                     // Format date from YYYY-MM-DD to DD/MM/YYYY
                                                                        let dateParts = res.transfer_date.split('-'); // ['2025','10','10']
                                                                        let formattedDate = dateParts[2] + '/' + dateParts[1] + '/' + dateParts[0];
                                                            
                                                                        modal.find('#transferDate').text(formattedDate || '-');
                                                                        modal.find('#transferTime').text(res.transfer_time || '-');
                                                                        modal.find('#amountPay').text(res.amount_pay || '0.00');
                                                                        modal.find('#paymentMethod').text(res.payment_method || '-');
                                                                } else {
                                                                    console.warn('Invoice data not found:', invoice);
                                                                }
                                                            })
                                                            .fail(function() {
                                                                console.error("Failed to fetch invoice data for invoice:", invoice);
                                                            });
                                                    });



                                                    
                                                  // Preview gambar resit
                                                  document.getElementById("receiptFile").addEventListener("change", function(){
                                                    const [file] = this.files;
                                                    if (file) {
                                                      document.getElementById("previewContainer").style.display = "block";
                                                      document.getElementById("previewImage").src = URL.createObjectURL(file);
                                                    }
                                                  });
                                                
                                                    $(document).ready(function() {
                                                        $("#uploadForm").on("submit", function(e) {
                                                            e.preventDefault();
                                                    
                                                            var $submitBtn = $("#submitBtn");
                                                            var $btnText = $("#btnText");
                                                            var $btnSpinner = $("#btnSpinner");
                                                    
                                                            $submitBtn.prop("disabled", true);
                                                            $btnText.text("Uploading...");
                                                            $btnSpinner.removeClass("d-none");
                                                    
                                                            var formData = new FormData(this);
                                                    
                                                            $.ajax({
                                                                url: "pay_receipt.php",
                                                                type: "POST",
                                                                data: formData,
                                                                processData: false,
                                                                contentType: false,
                                                                success: function(response) {
                                                                    console.log("Server response:", response);
                                                    
                                                                    var res;
                                                                    try {
                                                                        res = typeof response === "object" ? response : JSON.parse(response);
                                                                    } catch (err) {
                                                                        alert("Unexpected response from server: " + response);
                                                                        return;
                                                                    }
                                                    
                                                                    if (res.status === "success") {
                                                                        $("#uploadModal").modal("hide");
                                                                        alert("Receipt uploaded successfully. Status updated to Processing.");
                                                    
                                                                        // Find the table row
                                                                        var $row = $("a[data-invoice='" + res.invoice_no + "']").closest("tr");
                                                    
                                                                        // Update the receipt icon
                                                                        var $iconContainer = $row.find("td").eq(-1).find("div"); // adjust if div is not last td
                                                                        $iconContainer.find("i.fa-receipt, i.fa-file-arrow-up").remove();
                                                                        $iconContainer.append('<i class="fa-2x fa-solid fa-receipt text-muted" title="Receipt under review"></i>');
                                                    
                                                                        // Update the payment status cell text
                                                                        $row.find("td.payment_status").text("Processing");
                                                                    } else {
                                                                        alert(res.message || "Failed to upload receipt.");
                                                                    }
                                                                },
                                                                error: function() {
                                                                    alert("Upload failed. Something went wrong. Please try again.");
                                                                },
                                                                complete: function() {
                                                                    $submitBtn.prop("disabled", false);
                                                                    $btnText.text("Submit");
                                                                    $btnSpinner.addClass("d-none");
                                                                }
                                                            });
                                                        });
                                                    });




                                                </script>


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