<?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>Order 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">Order Status:</label>
      <select id="status" name="status" class="form-control" style="max-width:160px;">
          <option value="">-- All --</option>
          <option value="Issued"    <?= (($_GET['status'] ?? '')=='Issued')?'selected':'' ?>>Issued</option>
          <option value="Completed" <?= (($_GET['status'] ?? '')=='Completed')?'selected':'' ?>>Completed</option>
          <option value="Cancelled" <?= (($_GET['status'] ?? '')=='Cancelled')?'selected':'' ?>>Cancelled</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 Invoices
                    </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><i class="fa fa-truck">             </i> </th>
                                        <th><i class="fa fa-dollar-sign">       </i> </th>
                                        <th><i class="fa fa-dollar-sign">       </i> Payment</th>
                                        <th><i class="fa fa-box">               </i> Packaging</th>
                                        <th><i class="fa fa-truck">             </i> Shipping</th>
                                        <th><i class="fa fa-check-circle">      </i> Delivery</th>
                                        <th><i class="fa fa-tasks">             </i> Order 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.invoice_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.invoice_no, i.customer_id, i.created_at, i.payment_method, i.shipping_method,
                   i.invoice_status, i.order_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);

// =======================
// Status Badge Function
// =======================
if (!function_exists('statusBadge')) {
    function statusBadge($status, $type='cash') {
        // Default icon ikut type
        $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;
            default: $icon = 'fa-circle-question'; break;
        }

        // Warna ikut status
        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 'Counter':   $color = '#28a745'; // green - order completed
                            break;
                        case 'Handover':   $color = '#28a745'; // green - order completed
                            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);
    }
}

// =======================
// Resolve Order Status
// =======================
if (!function_exists('resolveOrderStatus')) {
    function resolveOrderStatus($row) {
        // Cancel & Failed always take priority
        if (($row['payment_status'] ?? '') === 'Failed') return 'Failed';
        if (($row['delivery_status'] ?? '') === 'Cancelled' || ($row['payment_status'] ?? '') === 'Cancelled') return 'Cancelled';
        if (($row['delivery_status'] ?? '') === 'Returned' || ($row['shipping_status'] ?? '') === 'Returned') return 'Refund';

        // Payment stage
        if (($row['payment_status'] ?? '') === 'Pending') return 'Pending';
        if (($row['payment_status'] ?? '') === 'Processing') return 'Processing';
        if (($row['payment_status'] ?? '') === 'Paid') {
            // Packaging stage
            if (($row['packaging_status'] ?? '') === 'Pending') return 'Pending';
            if (($row['packaging_status'] ?? '') === 'Processing') return 'Processing';
            if (($row['packaging_status'] ?? '') === 'Packed') {
                // Shipping stage
                if (($row['shipping_status'] ?? '') === 'Pending') return 'Pending';
                if (($row['shipping_status'] ?? '') === 'Waiting') return 'Waiting';
                if (($row['shipping_status'] ?? '') === 'Counter') {
                    // Delivery stage SELFCOLLECT
                    if (($row['delivery_status'] ?? '') === 'Handover') return 'Completed';
                }
                if (($row['shipping_status'] ?? '') === 'Shipped') {
                    // Delivery stage COURIER
                    if (($row['delivery_status'] ?? '') === 'Pending') return 'Pending';
                    if (($row['delivery_status'] ?? '') === 'Out for Delivery') return 'Completed';
                    if (($row['delivery_status'] ?? '') === 'Delivered') return 'Completed';
                    if (($row['delivery_status'] ?? '') === 'In Transit') return 'Completed';
                }
                if (($row['shipping_status'] ?? '') === 'Delivered') return 'Completed';
            }
        }

        // Default fallback
        return 'Pending';
    }
}

// =======================
// Order Status Badge
// =======================
if (!function_exists('orderStatusBadge')) {
    function orderStatusBadge($row) {
        // Dapatkan status akhir ikut rules
        $status = resolveOrderStatus($row);

        // Tentukan process type untuk icon
        switch ($status) {
            case 'Failed':
            case 'Cancelled':
            case 'Refund':
                $processType = 'order'; 
                break;

            case 'Pending':
            case 'Processing':
                if (($row['payment_status'] ?? '') !== 'Paid') {
                    $processType = 'payment';
                } elseif (($row['packaging_status'] ?? '') !== 'Packed') {
                    $processType = 'packaging';
                } elseif (($row['shipping_status'] ?? '') !== 'Shipped') {
                    $processType = 'shipping';
                } else {
                    $processType = 'delivery';
                }
                break;
            case 'Waiting':
                $processType = 'shipping';
                break;
            case 'Completed':
                $ship = strtolower($row['shipping_status'] ?? '');
                $deliver = strtolower($row['delivery_status'] ?? '');
            
                if ($ship === 'Counter' && $deliver === 'Handover') {
                    $processType = 'order';
                } elseif ($ship === 'Shipped' && in_array($deliver, ['In Transit', 'Out for Delivery'])) {
                    $processType = 'order';
                } else {
                    $processType = 'order';
                }
                break;

            default:
                $processType = 'order';
                break;
        }

        return statusBadge($status, $processType);
    }
}

// =======================
//     Table Rendering
// ======================= -->
 while ($row = mysqli_fetch_assoc($result)) { 
 
        // 🧩 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-people-carry-box text-primary" data-bs-toggle="tooltip" title="Self Collect"></i>',
                    'courier'     => '<i class="fa-solid fa-truck text-success" data-bs-toggle="tooltip" title="Courier Delivery"></i>',
                    'default'     => '<i class="fa-solid fa-box text-secondary" data-bs-toggle="tooltip" title="Other Shipping Method"></i>'
                  ],
                  'payment' => [
                    'cash'          => '<i class="fa-solid fa-money-bill-wave text-success" data-bs-toggle="tooltip" title="Cash Payment"></i>',
                    'transfer'      => '<i class="fa-solid fa-building-columns text-info" data-bs-toggle="tooltip" title="Bank Transfer"></i>',
                    'onlinebanking' => '<i class="fa-solid fa-globe text-warning" data-bs-toggle="tooltip" title="Online Banking"></i>',
                    'default'       => '<i class="fa-solid fa-credit-card text-muted" data-bs-toggle="tooltip" title="Other Payment Method"></i>'
                  ]
                ];

        
        $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><?= $shipping_icon ?></td>
                                    <td><?= $payment_icon  ?></td>
                                    <!-- Individual process stages -->
                                    <td><?= statusBadge($row['payment_status'], 'payment') ?></td>
                                    <td><?= statusBadge($row['packaging_status'], 'packaging') ?></td>
                                    <td><?= statusBadge($row['shipping_status'], 'shipping') ?></td>
                                    <td><?= statusBadge($row['delivery_status'], 'delivery') ?></td>
                                
                                    <!-- Final Order Status -->
                                    <td><?= orderStatusBadge($row) ?></td>
                                    
                                    <!-- Action Buttons -->
                                    <td style="padding:5px; text-align:center;">
                                        <!-- Invoice Icon -->
                                        <a target="_blank" href="view_invoice.php?invoice=<?= urlencode($row['invoice_no']) ?>" 
                                           data-toggle="tooltip" 
                                           title="View Invoice" 
                                           style="margin-right:10px;">
                                            <i class="fa-2x fa-solid fa-file-invoice-dollar action-icon"></i>
                                        </a>
                                    
                                        <!-- Receipt Icon (only if Paid) -->
                                        <?php if (strtolower($row['payment_status']) === 'paid'): ?>
                                            <a target="_blank" href="view_receipt.php?invoice=<?= urlencode($row['invoice_no']) ?>" 
                                               data-toggle="tooltip" 
                                               title="View Receipt">
                                                <i class="fa-2x fa-solid fa-receipt action-icon"></i>
                                            </a>
                                        <?php else: ?>
                                            <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 endif; ?>
                                    </td>
                                </tr>
<?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <!--End Advanced Tables -->
            </div>
        </div>
    </div>
    <!-- /. PAGE INNER  -->
</div>
<?php
    include "_footer2.php";
}
?>
