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

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

// Get 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.");

// Customer
$cust = mysqli_fetch_assoc(mysqli_query($con,"SELECT * FROM ahli WHERE id=".$invoice['customer_id']));

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

// QR
$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);

// Calculation (rounded 2 decimals)
$lineTotal      = round($invoice['price'] * $invoice['qty_set'], 2);
$subtotal       = round($lineTotal, 2);
$discount       = round($invoice['discount'], 2);
$shipping       = round($invoice['shipping_fee'], 2);
$tax            = round($invoice['tax'], 2);
$taxableAmount  = $subtotal - $discount;
$taxRate        = ($taxableAmount > 0) ? round(($tax / $taxableAmount) * 100, 2) : 0;
$grand          = round($subtotal - $discount + $shipping + $tax, 2);

// Payment summary from JSON
$payment_sum = json_decode($invoice['payment_sum'] ?? "{}", true);

$pay_amount  = isset($payment_sum['pay_amount'])
    ? round(floatval($payment_sum['pay_amount']), 2)
    : round($grand, 2);

$pay_balance = isset($payment_sum['pay_balance'])
    ? round(floatval($payment_sum['pay_balance']), 2)
    : round($grand - $pay_amount, 2);

if ($invoice['payment_status'] == "Paid") {
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Receipt <?= htmlspecialchars($invoice_no) ?></title>
<style>
body {
    font-family: monospace, Arial;
    font-size: 12px;
    width: 58mm; /* for thermal printer */
    margin: 0 auto;
}
.receipt { text-align: center; }
.line { border-top:1px dashed #000; margin:4px 0; }
td { font-size:12px; }
</style>
</head>
<body>  

    <div style="overflow-x:auto; -webkit-overflow-scrolling:touch;">
        <div style="width:150px; 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;">
            <div id="printArea">
                <!-- Logo on Top -->
                <div style="text-align:center; margin-bottom:10px;">
                    <img src="assets2/ico/tls2u.png" style="max-width:120px; height:auto;">
                </div>
                <div class="receipt">
                    <h3><?= htmlspecialchars($headerRow['nama']) ?></h3>
                    <div><?= htmlspecialchars($headerRow['alamat']) ?>, <?= htmlspecialchars($headerRow['bandar']) ?></div>
                    <div><?= htmlspecialchars($headerRow['telefon']) ?></div>
                    <div class="line"></div>
                    <strong>PAYMENT RECEIPT</strong><br>
                    No: <?= htmlspecialchars($invoice_no) ?><br>
                    Date: <?= date("d/m/Y",strtotime($invoice['created_at'])) ?><br>
                    Method: <?= strtoupper(htmlspecialchars($invoice['payment_method'])) ?><br>
                    <div class="line"></div>
                </div>
                
                <table width="100%" cellspacing="0" cellpadding="2">
                    <tr>
                        <td colspan="3"><?= htmlspecialchars($invoice['package_name']) ?></td>
                    </tr>
                    <tr>
                        <td><?= (int)$invoice['qty_set'] ?> x <?= number_format($invoice['price'],2) ?></td>
                        <td align="right">RM</td>
                        <td align="right"><?= number_format($lineTotal,2) ?></td>
                    </tr>
                    <tr><td colspan="3"><div class="line"></div></td></tr>
                    <tr>
                        <td colspan="2" align="right">Subtotal</td>
                        <td align="right"><?= number_format($subtotal,2) ?></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="right">Discount</td>
                        <td align="right">-<?= number_format($discount,2) ?></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="right">Shipping</td>
                        <td align="right"><?= number_format($shipping,2) ?></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="right">Tax (<?= $taxRate ?>%)</td>
                        <td align="right"><?= number_format($tax,2) ?></td>
                    </tr>
                    <tr><td colspan="3"><div class="line"></div></td></tr>
                    <tr>
                        <td colspan="2" align="right"><strong>Total</strong></td>
                        <td align="right"><strong><?= number_format($grand,2) ?></strong></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="right">Amount Paid</td>
                        <td align="right"><?= number_format($pay_amount,2) ?></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="right">Balance</td>
                        <td align="right"><?= number_format($pay_balance,2) ?></td>
                    </tr>
                </table>
                
                <div class="receipt">
                    <div class="line"></div>
                    Customer: <?= htmlspecialchars($cust['nama']) ?><br>
                    <?= htmlspecialchars($cust['telefon']) ?><br>
                    <img src="<?= $filename ?>" style="width:100px;height:100px"><br>
                    --- Thank You ---
                </div>
            </div>
        </div>
    </div>

<!-- Centered Print Button -->
<div style="text-align:center; margin-top:20px;">
    <button onclick="printDiv('printArea')">PRINT</button>
</div>

<script>
function printDiv(divId) {
    var printContents = document.getElementById(divId).innerHTML;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}
</script>

</body>
</html>

<?php } else {
   header("Location: /dashboard.php");
}
?>
