<?php
session_start();
include "conn.php";
require_once 'phpqrcode/qrlib.php';

// Pastikan invoice number ada
$invoice_no = $_GET['invoice'] ?? '';
if (!$invoice_no) die("Invoice not specified.");

// Dapatkan invoice
$stmt = $con->prepare("SELECT * FROM invoice WHERE invoice_no = ?");
$stmt->bind_param("s",$invoice_no);
$stmt->execute();
$res = $stmt->get_result();
$invoice = $res->fetch_assoc();
if (!$invoice) die("Invoice not found.");

// Role check: admin boleh lihat semua, selain itu hanya owner
if (($_SESSION['username'] ?? '') !== 'admin' && $invoice['customer_id'] != ($_SESSION['aidi'] ?? 0)) {
    die("Access denied.");
}

// Dapatkan customer info
$customerStmt = $con->prepare("SELECT * FROM ahli WHERE id=?");
$customerStmt->bind_param("i",$invoice['customer_id']);
$customerStmt->execute();
$customerRes = $customerStmt->get_result();
$customer = $customerRes->fetch_assoc();

// Generate QR Code
$dir = "temp/img/qrcode/";
if (!file_exists($dir)) mkdir($dir,0777,true);
$filename = $dir.$invoice_no.".png";
QRcode::png($invoice_no,$filename,QR_ECLEVEL_L,3);

// Status
$status = [
    'invoice_status' => $invoice['invoice_status'] ?? 'Issued',
    'payment_status' => $invoice['payment_status'] ?? 'Pending',
    'packaging_status' => $invoice['packaging_status'] ?? 'Pending',
    'shipping_status' => $invoice['shipping_status'] ?? 'Pending',
    'delivery_status' => $invoice['delivery_status'] ?? 'Pending'
];

// Package info
$package = [
    'id' => $invoice['package_id'],
    'name' => $invoice['package_name'],
    'desc' => $invoice['package_desc'],
    'price' => $invoice['price'],
    'qty_set' => $invoice['qty_set'],
    'qty' => $invoice['qty_total'],
    'discount' => $invoice['discount'],
    'shipping' => $invoice['shipping_fee'],
    'shipping_method' => $invoice['shipping_method'] ?? 'selfcollect'
];

    // 1️⃣ Prepare the package_desc JSON
    $package_desc = $package['desc'];

// Customer display
$customerDisplay = [
    'name' => $customer['nama'] ?? '',
    'address' => $customer['alamat'] ?? '',
    'postcode' => $customer['poskod'] ?? '',
    'city' => $customer['bandar'] ?? '',
    'state' => $customer['negeri'] ?? '',
    'phone' => $customer['telefon'] ?? '',
    'email' => $customer['email'] ?? ''
];

// Subtotal / grand total
$lineTotal = $package['price'] * $package['qty_set'];
$subtotal = $lineTotal;
$discount = $package['discount'];
$shipping = $package['shipping'];
$taxRow = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM setting LIMIT 1"));
$taxRate = isset($taxRow['tax']) ? (float)$taxRow['tax'] : 0;
$taxable = max(0,$subtotal-$discount);
$tax = round($taxable*($taxRate/100),2);
$grand_total_calc = $subtotal - $discount + $shipping + $tax;

// Dapatkan header company (admin)
$headerRow = mysqli_fetch_assoc(mysqli_query($con,"SELECT * FROM ahli WHERE username='admin' ORDER BY id DESC LIMIT 1"));

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Invoice <?= htmlspecialchars($invoice_no) ?></title>
    <link rel="shortcut icon" href="assets2/ico/tls2u.png">
    <!-- BOOTSTRAP STYLES-->
    <link href="assets/css/bootstrap.css" rel="stylesheet" />
     <!-- FONTAWESOME STYLES
    <link href="assets/css/font-awesome.css" rel="stylesheet" /> -->
    <link rel="stylesheet" href="/assets2/fontawesome/css/all.css">  
     <!-- MORRIS CHART STYLES-->
    <link href="assets/js/morris/morris-0.4.3.min.css" rel="stylesheet" />
        <!-- CUSTOM STYLES-->
    <link href="assets/css/custom.css" rel="stylesheet" />
     <!-- GOOGLE FONTS-->
   <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
     <!-- TABLE STYLES-->
     <link rel="stylesheet" href="assets/css/jquery.dataTables.css" />
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
      <script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.js"></script>
      <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.0/css/jquery.dataTables.css">
      <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.1.0/js/dataTables.buttons.min.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.1.0/css/buttons.dataTables.min.css">
      <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.1.0/js/buttons.flash.min.js"></script>
      <script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script>
      <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.1.0/js/buttons.print.min.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.js"></script>
      <script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>
      <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.1.0/js/buttons.html5.min.js"></script>
      <script src="https://www.google.com/recaptcha/api.js"></script>

<style>
            .progress-area {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top:30px;
                gap: 20px;
            }
            
            .progress-tracker {
                display: flex;
                justify-content: space-between;
                flex: 1;
                margin: 0;
                padding: 0;
                list-style: none;
            }
            .progress-tracker li {
                flex: 1;
                text-align: center;
                position: relative;
                font-size: 13px;
                color: #999;
            }
            .progress-tracker li::before {
                content: "";
                width: 20px;
                height: 20px;
                background: #ccc;
                border-radius: 50%;
                display: block;
                margin: 0 auto 8px;
            }
            .progress-tracker li::after {
                content: "";
                position: absolute;
                top: 10px;
                left: 50%;
                width: 100%;
                height: 4px;
                background: #ccc;
                z-index: -1;
            }
            .progress-tracker li:last-child::after {
                display: none;
            }
            .progress-tracker li.active {
                color: #4CAF50;
                font-weight: bold;
            }
            .progress-tracker li.active::before {
                background: #4CAF50;
            }
            .progress-tracker li.paid::before {
                background: #2196F3; /* biru untuk Paid */
            }
            .progress-tracker li.packaged::before {
                background: #9C27B0; /* ungu untuk Packaging */
            }
            .progress-tracker li.shipped::before {
                background: #FF9800; /* oren untuk Shipped */
            }
            .progress-tracker li.delivered::before {
                background: #4CAF50; /* hijau untuk Delivered */
            }
            
            .progress-button button,
            .progress-button a {
                white-space: nowrap;
            }
            
            /* Responsive: biar horizontal scroll bila screen kecil */
            @media(max-width:768px){
                .progress-area {
                    overflow-x: auto;
                    -webkit-overflow-scrolling: touch;
                }
                .progress-tracker {
                    flex-wrap: nowrap;
                    min-width: 600px; /* boleh adjust ikut bilangan step */
                }
                .progress-tracker li {
                    flex: 0 0 auto;
                    min-width: 100px; /* bagi spacing setiap step */
                }
            }
            
            @media print {
                body * {
                    visibility: hidden;
                }
                #printArea, #printArea * {
                    visibility: visible;
                }
                #printArea {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 100%;
                    height: auto;
                }
                @page {
                    size: A4;
                    margin: 10mm;
                }
            }

</style>
</head>
<body>
    <!-- Scrollable container -->
    <div style="overflow-x:auto; -webkit-overflow-scrolling:touch;">
        <div style="width:800px; margin:auto; font-family:Arial, sans-serif; border:1px solid #ccc; padding:20px; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
            <!-- Invoice Print Area -->
            <div id="printArea">
    
                <div id="invoiceContainer">
                    <!-- Header -->
                    <div style="display:flex; align-items:center; justify-content:space-between; border-bottom:0px solid #000; padding-bottom:10px; margin-bottom:20px;">
                    <div style="text-align:left;">
                        <h4 style="margin:0;">
                            <?= $headerRow['nama'] ?>
                            <span class="small">(<?= $headerRow['kp'] ?>)</span>
                        </h4>
                        <small>
                            <?= $headerRow['alamat'] ?>,
                            <?= $headerRow['poskod'] ?>,
                            <?= $headerRow['bandar'] ?>,
                            <?= $headerRow['negeri'] ?> <br>
                            <?= $headerRow['email'] ?> |
                            <?= $headerRow['telefon'] ?>
                        </small>
                    </div>
                    <img src="assets2/ico/tls2u.png" style="height:100px;">
        
                </div>
                
                    <!-- Customer & Invoice Info -->
                    <div style="display:flex;justify-content:space-between;margin-bottom:20px;">
                        <div style="font-size:12px;">
                            <strong>Bill To:</strong><br>
                            <?= htmlspecialchars($customerDisplay['name']) ?><br>
                            <?= htmlspecialchars($customerDisplay['address']) ?><br>
                            <?= htmlspecialchars($customerDisplay['postcode']) ?> <?= htmlspecialchars($customerDisplay['city']) ?>,<br>
                            <?= htmlspecialchars($customerDisplay['state']) ?><br><br>
                            <i class="fa-solid fa-phone"></i> <?= htmlspecialchars($customerDisplay['phone']) ?><br>
                            <i class="fa-solid fa-envelope"></i> <?= htmlspecialchars($customerDisplay['email']) ?>
                        </div>
                        <div style="min-width:250px;text-align:right;font-size:12px;">
                            <h3 style="margin:0;">INVOICE</h3>
                            <div style="display:flex;gap:10px;justify-content:flex-end;align-items:center;">
                                <img src="<?= $filename ?>" style="width:80px;height:80px;">
                                <div>
                                    <div><strong>No:        </strong><?= htmlspecialchars($invoice_no) ?></div>
                                    <div><strong>Date:      </strong><?= date("d/m/Y", strtotime($invoice['created_at'])) ?></div>
                                    <div><strong>Payment:   </strong><?= htmlspecialchars($invoice['payment_method']) ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                
                    <!-- Item Table -->
                    <table width="100%" cellspacing="0" cellpadding="8" style="margin-top:20px; border-collapse:collapse; font-size:13px; font-family:Arial, sans-serif; ">
                        <thead>
                            <tr style="border-top:2px solid #eaeaea;">
                                <th style="text-align:left;     padding:10px 12px; border-bottom:1px solid #e6e6e6;">Item</th>
                                <th style="text-align:center;   padding:10px 12px; border-bottom:1px solid #e6e6e6; width:80px;">Qty</th>
                                <th style="text-align:right;    padding:10px 12px; border-bottom:1px solid #e6e6e6; width:140px;">Unit Price (RM)</th>
                                <th style="text-align:right;    padding:10px 12px; border-bottom:1px solid #e6e6e6; width:160px;">Line Total (RM)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td style="padding:20px 12px; vertical-align:top;">
                                    <strong><?= htmlspecialchars($package['name']) ?></strong>
                                    
                                    <div style="color:#666; font-size:12px; margin-top:6px;">
                                        <?php
                                        if (!empty($package_desc)) {
                                            // Decode JSON string into PHP array
                                            $items = json_decode($package_desc, true);
                                
                                            if (is_array($items) && count($items) > 0) {
                                                echo '<div style="margin-top:8px; color:#555; font-size:12px;">';
                                                foreach ($items as $item) {
                                                    $pid = intval($item['product_id']);
                                                    $productName = '';
                                                    $resProd = mysqli_query($con, "SELECT product_name FROM products WHERE id = $pid");
                                                    if ($resProd && $rowProd = mysqli_fetch_assoc($resProd)) {
                                                        $productName = $rowProd['product_name'];
                                                    }
                                
                                                    echo htmlspecialchars($productName) . ' (x' . intval($item['qty']) . ')<br>';
                                                }
                                                echo '</div>';
                                            } else {
                                                echo '<div style="color:#999;">No items found</div>';
                                            }
                                        }
                                        ?>
                                    </div>
                                </td>

                                <td style="text-align:center; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;"><?= $package['qty_set'] ?></td>
                                <td style="text-align:right; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;"><?= number_format($package['price'],2) ?></td>
                                <td style="text-align:right; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;"><?= number_format($lineTotal,2) ?></td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding-top:10px; padding-right: 12px; "><er>Subtotal</er></td>
                                <td style="text-align:right; padding-top:10px; padding-right: 12px; "><?= number_format($subtotal,2) ?></td>
                            </tr>
                                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding:0px 12px;"><er>Discount</er></td>
                                <td style="text-align:right; padding:0px 12px;">-<?= number_format($discount,2) ?></td>
                            </tr>
                                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding:0px 12px;"><er>Shipping</er></td>
                                <td style="text-align:right; padding:0px 12px;"><?= number_format($shipping,2) ?></td>
                            </tr>
                                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding-bottom:10px; padding-right: 12px;"><er>Tax (<?= $taxRate ?>%)</er></td>
                                <td style="text-align:right; padding-bottom:10px; padding-right: 12px;"><?= number_format($tax,2) ?></td>
                            </tr>
                                    
                            <tr style="background:#f7f7f7; font-weight:700;">
                                <td colspan="3" style="text-align:right; padding:12px 14px; border-top:2px solid #ddd;">Grand Total (RM)</td>
                                <td style="text-align:right; padding:12px 14px; border-top:2px solid #ddd;"><?= number_format($grand_total_calc,2) ?></td>
                            </tr>
                        </tfoot>
                    </table>
                    <p style="font-size:12px; text-align:center; margin:5px;">
                        --- Computer Generated ---
                    </p>
<?php    
                    // --------------------------
                    // Payment Method Handling
                    // --------------------------
                    $message_notif = '';
                    
                    if (($invoice['payment_method']) === 'transfer') {
                        ?>
                        <fieldset style="border:1px solid #ccc; padding:10px 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;">
                                Bank Transfer Information
                            </legend>
                            
                            <!-- Data info at the top -->
                            <div style="text-align:left; margin-bottom:8px;">
                                <span style="font-size:12px;" class="small">Account Name:   </span> <b><?= $headerRow['naakaun'] ?></b><br>
                                <span style="font-size:12px;" class="small">Bank Name:      </span> <b><?= $headerRow['bank'] ?></b><br>
                                <span style="font-size:12px;" class="small">Account No:     </span> <b><?= $headerRow['noakaun'] ?></b>
                            </div>
                        
                            <!-- Instruction -->
                            <div style="text-align:left; font-size:12px;">
                                <p style="margin:0 0 5px 0; font-size:12px;">
                                     Pay invoice <b class="text-danger"><?= $invoice_no ?></b> via bank transfer (details above), then follow the steps below:
                                </p>
                                <ul style="margin-left:20px; font-size:12px;">
                                    <li>Take a screenshot or photo of your payment receipt.</li>
                                    <li>Login to the system and upload the receipt via the <b>Order List</b> menu.</li>
                                    <li>Wait for admin verification. You will be notified once your payment has been confirmed.</li>
                                </ul>
                            </div>
                        </fieldset>
        
        
                        <?php
                    } elseif (($invoice['payment_method']) === 'cash') {
                        ?>
                        <fieldset style="border:1px solid #ccc; padding:10px 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;">
                                Bank Transfer Information
                            </legend>
                            
                            <!-- Instruction -->
                            <div style="text-align:left; margin-bottom:8px; font-size:12px;">
                                <p style="margin:0 0 5px 0; font-size:12px;">
                                    Please settle your invoice <b class="text-danger"><?= $invoice_no ?></b> at the counter, and then follow the steps below:
                                </p>
                                <ul style="margin-left:20px; font-size:12px;">
                                    <li>Make your payment directly at the counter.</li>
                                    <li>Collect your official receipt after payment is completed.</li>
                                    <li>A copy of the receipt will also be sent to your registered email address.</li>
                                </ul>
                            </div>
                        </fieldset>
<?php               }       ?>
            </div>
        </div>
                    
                    
                    
            <!-- Progress Tracker -->
                    <div class="progress-area">
                        <div class="progress-button">
                            <button onclick="window.print()">PRINT</button>
                        </div>
                    </div>
        </div>
    </div>
</body>
</html>
