<?php
// receipt.php - v14.4: Security, display ID from URL, escaped output, mobile/SEO meta
// NOTE: Receipt link token is PERMANENT (no expiry). Links sent via WhatsApp must remain valid indefinitely.
include 'db.php';

$search_id = $_GET['id'] ?? null;
if (!$search_id) { die("Error: No ID provided."); }

// 1. FETCH DATA (Search both job_id AND invoice_id, but prioritize exact job_id match)
// Token is optional; if provided, must match job's stored token. Do NOT add expiry—customer links must not expire.
$token = trim((string)($_GET['token'] ?? ''));
$stmt = $pdo->prepare("SELECT * FROM jobs WHERE job_id = ? LIMIT 1");
$stmt->execute([$search_id]);
$job = $stmt->fetch();

// If not found by job_id, try invoice_id
if (!$job) {
    $stmt = $pdo->prepare("SELECT * FROM jobs WHERE invoice_id = ? LIMIT 1");
    $stmt->execute([$search_id]);
    $job = $stmt->fetch();
}

if (!$job) { die("Receipt not found for ID: " . htmlspecialchars($search_id)); }

// Verify token only when both URL and job have a token (legacy jobs with no token always allowed)
$stored = trim((string)($job['token'] ?? ''));
if ($token !== '' && $stored !== '' && !hash_equals($stored, $token)) {
    // Allow when opened from dashboard (same origin / referer) so staff receipt links always work
    $reqHost = $_SERVER['HTTP_HOST'] ?? '';
    $ref = $_SERVER['HTTP_REFERER'] ?? '';
    $sameOrigin = ($reqHost !== '' && $ref !== '' && stripos($ref, $reqHost) !== false);
    if (!$sameOrigin) {
        die("Invalid receipt access token.");
    }
}

// 2. DATA MAPPING
$job['customer'] = $job['owner_name'] ?? $job['customer'] ?? 'Walk-in Customer';
$job['phone']    = $job['owner_phone'] ?? $job['phone'] ?? '';
$job['model']    = $job['device_name'] ?? $job['model'] ?? '';
$job['repair']   = $job['device_issue'] ?? $job['repair'] ?? '';
$job['price']    = $job['price'] ?? 0;
$job['imei']     = $job['imei'] ?? $job['device_imei'] ?? ''; 

$rawDate = !empty($job['date']) ? $job['date'] : ($job['created_at'] ?? date('Y-m-d'));
$job['date']     = date("d/m/Y", strtotime($rawDate));
$job['branch']   = $job['outlet'] ?? $job['branch'] ?? 'Gombak'; 
$job['warranty'] = $job['warranty'] ?? '1 Month';

// Show the same ID as in the URL (so customer sees what they clicked)
$display_id = $search_id;

// 3. PARSE ITEMS
$items = [];
$rawItems = explode(" || ", $job['repair']);

foreach ($rawItems as $rawItem) {
    $itemData = [
        'desc' => '', 'qty' => '-', 'price' => '-', 'total' => '-', 'sn' => '', 'warranty' => ''
    ];

    $cleanName = $rawItem;
    
    // Extract [W: ...]
    if (preg_match('/\[W: (.*?)\]/', $cleanName, $wMatch)) {
        $itemData['warranty'] = $wMatch[1];
        $cleanName = str_replace($wMatch[0], '', $cleanName);
    }
    
    // Extract [SN: ...]
    if (preg_match('/\[SN: (.*?)\]/', $cleanName, $snMatch)) {
        $itemData['sn'] = $snMatch[1];
        $cleanName = str_replace($snMatch[0], '', $cleanName);
    }
    $cleanName = trim($cleanName);

    // Parse logic: (x1) or (X1) and @ price (case-insensitive for x)
    if (preg_match('/^(.*?) \([xX](\d+)\)\s*@\s*([0-9.]+)/', $cleanName, $matches)) {
        $itemData['desc'] = trim($matches[1]);
        $itemData['qty'] = $matches[2];
        $itemData['price'] = $matches[3];
        $itemData['total'] = number_format((float)$matches[2] * (float)$matches[3], 2);
    } elseif (preg_match('/^(.*?) \([xX](\d+)\)\s*$/', $cleanName, $matches)) {
        $itemData['desc'] = trim($matches[1]);
        $itemData['qty'] = $matches[2];
    } else {
        $itemData['desc'] = $cleanName;
    }
    $items[] = $itemData;
}

// Subtotal from line items when all have price/total (so receipt total is correct even if job.price was not updated)
$displaySubtotal = 0;
foreach ($items as $it) {
    if (isset($it['total']) && $it['total'] !== '-' && is_numeric(str_replace(',', '', $it['total']))) {
        $displaySubtotal += (float)str_replace(',', '', $it['total']);
    }
}
if ($displaySubtotal <= 0) {
    $displaySubtotal = (float)($job['price'] ?? 0);
}

// 4. HEADER LOGIC
$itemCount = count($items);

if ($itemCount > 1) {
    $period = "See Items";
    $tickNo = '&nbsp;&nbsp;'; 
    $tickYes = '&nbsp;&nbsp;'; 
} else {
    $finalWarranty = (!empty($items[0]['warranty'])) ? $items[0]['warranty'] : $job['warranty'];
    $isNoWarranty = ($finalWarranty === 'No Warranty' || empty($finalWarranty));
    $tickNo  = $isNoWarranty ? '&#10003;' : '&nbsp;&nbsp;'; 
    $tickYes = $isNoWarranty ? '&nbsp;&nbsp;' : '&#10003;';
    $period  = $isNoWarranty ? '' : $finalWarranty;
}

$displayImei = $job['imei'];
if (empty($displayImei) && $itemCount === 1 && !empty($items[0]['sn'])) {
    $displayImei = $items[0]['sn'];
}

if (stripos($job['branch'], 'gombak') !== false) {
    $address = "39, Jalan SG 1/6, Taman Sri Gombak<br>68100 Batu Caves, Selangor Malaysia<br>Tel: +6011-2919 0338";
} else {
    $address = "2-G-7, Wisma Rampai, Jalan 34/26<br>Taman Sri Rampai, 53300 Kuala Lumpur<br>Tel: +6010-773 2919";
}

$logo = '<img src="logo.png" style="max-width:220px; height:auto;">'; 
function e($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex, nofollow">
    <title>Receipt <?php echo e($display_id); ?></title>
    <link rel="icon" type="image/png" href="logo.png">
    <link rel="shortcut icon" type="image/png" href="logo.png">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Arial:wght@400;700&display=swap');
        * { box-sizing: border-box; }
        body { font-family: 'Arial', sans-serif; font-size: 12px; margin: 0; padding: 20px; background: #555; }
        .page { background: #fff; width: 210mm; min-height: 297mm; padding: 15mm; margin: 0 auto; position: relative; }
        
        .header { display: flex; justify-content: space-between; margin-bottom: 5px; }
        .logo-area { display: flex; align-items: flex-start; gap: 15px; }
        .company-details { font-size: 11px; line-height: 1.3; font-weight: bold; margin-top: 5px; }
        
        .invoice-title-area { text-align: right; }
        .invoice-big-text { font-size: 32px; font-weight: 900; letter-spacing: 1px; color: #000; }
        .invoice-no { color: red; font-size: 18px; font-weight: bold; margin-top: 2px; }
        
        .info-container { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 5px; margin-top: 10px; }
        .cust-info { width: 58%; }
        .cust-row { display: flex; margin-bottom: 4px; align-items: flex-end; }
        .cust-label { width: 80px; font-weight: normal; font-size: 12px; }
        .cust-val { flex: 1; border-bottom: 1px solid #000; font-weight: bold; font-size: 13px; padding-left: 5px; }
        
        .warranty-box { width: 40%; border: 1px solid #000; display: flex; flex-direction: column; }
        .w-row { display: flex; border-bottom: 1px solid #000; height: 28px; align-items: center; }
        .w-row:last-child { border-bottom: none; }
        .w-check-cell { width: 100px; border-right: 1px solid #000; height: 100%; display: flex; align-items: center; padding-left: 5px; }
        .w-data-cell { flex: 1; height: 100%; display: flex; align-items: center; padding-left: 5px; }
        .check-box { width: 14px; height: 14px; border: 1px solid #000; display: inline-block; text-align: center; line-height: 12px; font-size: 12px; margin-right: 5px; }
        
        /* --- TABLE ADJUSTMENT --- */
        table { width: 100%; border-collapse: collapse; border: 1px solid #000; margin-top: 25px; }
        
        th, td { border: 1px solid #000 !important; }
        th { padding: 5px; background: #fff; font-weight: normal; font-size: 12px; text-align: center; height: 30px; }
        td { padding: 5px; vertical-align: top; font-size: 12px; }
        
        .col-qty { width: 40px; text-align: center; }
        .col-desc { width: auto; }
        .col-price { width: 100px; text-align: right; }
        .col-total { width: 100px; text-align: right; }
        
        .item-meta { font-size: 10px; color: #333; margin-top: 2px; }
        .meta-tag { display: inline-block; margin-right: 10px; background: #eee; padding: 1px 5px; border-radius: 3px; font-weight: bold; border: 1px solid #ddd; }

        .spacer-row td { height: 24px; color: transparent; } 
        
        .footer-section { display: flex; justify-content: space-between; align-items: flex-start; margin-top: -1px; }
        .terms { width: 65%; font-size: 9px; line-height: 1.4; padding-top: 10px; font-style: italic;}
        
        .totals { width: 35%; }
        .total-row { display: flex; justify-content: space-between; border: 1px solid #000; border-top: none; padding: 8px; font-weight: bold; font-size: 14px; }
        
        .signatures { display: flex; justify-content: space-between; margin-top: 5px; align-items: flex-start; }
        .sign-block { width: 30%; }
        .sign-block:last-child { 
            width: auto; 
            margin-left: auto; 
            margin-right: 0; 
            text-align: right; 
        } /* Align Issue By section to the right edge */
        .sign-line { border-bottom: 1px solid #000; margin-bottom: 5px; height: 30px; }
        .sign-label { font-size: 12px; }
        
        /* Company Stamp/Chop Design - Standard Blue Company Chop Style (Landscape Rectangle) */
        .company-stamp {
            width: 250px;
            min-height: 50px;
            border: 2.5px solid #0066cc;
            border-radius: 4px;
            position: relative;
            margin: 2px 0 5px auto; /* Align to right edge */
            background: rgba(255, 255, 255, 0.98);
            padding: 6px 12px;
            box-shadow: 
                0 2px 8px rgba(0, 102, 204, 0.3),
                inset 0 1px 2px rgba(0, 102, 204, 0.1);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
        }
        
        .stamp-inner {
            width: 100%;
            color: #0066cc;
            font-family: 'Arial', 'Microsoft YaHei', sans-serif;
            line-height: 1.5;
            position: relative;
            z-index: 2;
        }
        
        .stamp-brand-name {
            font-size: 16px;
            font-weight: 700;
            letter-spacing: 0.5px;
            margin-bottom: 3px;
            color: #0066cc;
        }
        
        .stamp-company-name {
            font-size: 11px;
            font-weight: 600;
            margin-bottom: 3px;
            color: #0066cc;
        }
        
        .stamp-reg-number {
            font-size: 9px;
            font-weight: 500;
            margin-bottom: 5px;
            color: #0066cc;
            opacity: 0.9;
        }
        
        .stamp-divider {
            width: 90%;
            height: 1px;
            background: #0066cc;
            margin: 4px auto;
            opacity: 0.7;
        }
        
        .stamp-address {
            font-size: 9px;
            font-weight: 500;
            line-height: 1.5;
            color: #0066cc;
            margin-bottom: 4px;
        }
        
        .stamp-contact {
            font-size: 9px;
            font-weight: 500;
            color: #0066cc;
            margin-top: 3px;
        }
        
        /* Decorative corner marks for stamp effect */
        .company-stamp::before {
            content: '';
            position: absolute;
            top: 3px;
            left: 3px;
            width: 8px;
            height: 8px;
            border-top: 1.5px solid #0066cc;
            border-left: 1.5px solid #0066cc;
            opacity: 0.6;
        }
        
        .company-stamp::after {
            content: '';
            position: absolute;
            bottom: 3px;
            right: 3px;
            width: 8px;
            height: 8px;
            border-bottom: 1.5px solid #0066cc;
            border-right: 1.5px solid #0066cc;
            opacity: 0.6;
        }
        
        /* --- COMPUTER GENERATED TEXT STYLE --- */
        .comp-gen { 
            text-align: center; 
            font-size: 11px;      /* Increased slightly */
            font-weight: bold;    /* Made bold */
            font-style: italic; 
            margin-top: 25px; 
            width: 100%; 
            color: #333;          /* Darker grey for readability */
        }

        @media print { 
            body { background: #fff; padding: 0; } 
            .page { width: 100%; height: 100%; margin: 0; box-shadow: none; } 
            .no-print { display: none; } 
            * { -webkit-print-color-adjust: exact; print-color-adjust: exact; } 
        }
        .btn-print { position: fixed; top: 20px; right: 20px; padding: 15px 30px; background: #000; color: #fff; font-weight: bold; cursor: pointer; border: none; border-radius: 5px; z-index:999; }
    </style>
</head>
<body>

<button class="btn-print no-print" onclick="window.print()">PRINT</button>

<div class="page">
    
    <div class="header">
        <div class="logo-area">
            <?php echo $logo; ?>
            <div class="company-details">
                LKF Mobile Enterprise <span style="font-weight:normal; font-size:10px;">002805193-K</span><br>
                <?php echo $address; ?>
            </div>
        </div>
        <div class="invoice-title-area">
            <div class="invoice-big-text">INVOICE</div>
            <div class="invoice-no">No. <?php echo e($display_id); ?></div>
        </div>
    </div>

    <div class="info-container">
        <div class="cust-info">
            <div class="cust-row"><div class="cust-label">Customer:</div><div class="cust-val"><?php echo e($job['customer']); ?></div></div>
            <div class="cust-row"><div class="cust-label">Contact No.:</div><div class="cust-val"><?php echo e($job['phone']); ?></div></div>
        </div>

        <div class="warranty-box">
            <div class="w-row">
                <div class="w-check-cell"><div class="check-box"><?php echo $tickNo; ?></div> No Warranty</div>
                <div class="w-data-cell">Date: &nbsp; <strong><?php echo e($job['date']); ?></strong></div>
            </div>
            <div class="w-row">
                <div class="w-check-cell"><div class="check-box"><?php echo $tickYes; ?></div> Warranty</div>
                <div class="w-data-cell">Period: &nbsp; <strong><?php echo e($period); ?></strong></div>
            </div>
        </div>
    </div>

    <div class="info-container" style="margin-top:0;">
        <div class="cust-info" style="width:100%;">
            <div style="display:flex; gap:10px;">
                <div style="flex:1;" class="cust-row">
                    <div class="cust-label">IMEI/SN:</div>
                    <div class="cust-val"><?php echo e($displayImei); ?></div>
                </div>
                <div style="flex:1;" class="cust-row">
                    <div class="cust-label">Pay Mode:</div>
                    <div class="cust-val"><?php 
                        $paymentMethod = $job['payment_method'] ?? 'Cash';
                        $parts = explode(' + ', $paymentMethod);
                        $formatted = [];
                        foreach ($parts as $part) {
                            $part = trim($part);
                            if (preg_match('/^(.+?)\s*\(RM\s*([\d.]+)\)$/', $part, $matches)) {
                                $formatted[] = $matches[1] . ' (RM ' . number_format($matches[2], 2) . ')';
                            } else {
                                $formatted[] = $part;
                            }
                        }
                        echo e(implode(' + ', $formatted));
                    ?></div>
                </div>
            </div>
        </div>
    </div>

    <table>
        <thead>
            <tr><th class="col-qty">Qty</th><th class="col-desc">Description</th><th class="col-price">Unit Price</th><th class="col-total">Total Price</th></tr>
        </thead>
        <tbody>
            <?php foreach ($items as $item): ?>
            <tr>
                <td class="col-qty"><?php echo e($item['qty']); ?></td>
                <td class="col-desc">
                    <strong><?php echo e($item['desc']); ?></strong>
                    
                    <?php 
                    // Determine warranty for this item
                    $itemWarranty = !empty($item['warranty']) ? $item['warranty'] : $job['warranty'];
                    $itemHasNoWarranty = ($itemWarranty === 'No Warranty' || empty($itemWarranty));
                    
                    // Show meta if: SN exists, OR (multiple items with warranty), OR no warranty
                    if($item['sn'] || ($itemCount > 1 && $item['warranty']) || $itemHasNoWarranty): ?>
                    <div class="item-meta">
                        <?php if($item['sn']) echo '<span class="meta-tag">SN: ' . e($item['sn']) . '</span>'; ?>
                        <?php if($itemCount > 1 && $item['warranty']) echo '<span class="meta-tag">Warranty: ' . e($item['warranty']) . '</span>'; ?>
                        <?php if($itemHasNoWarranty) echo '<span class="meta-tag">Warranty: No Warranty</span>'; ?>
                    </div>
                    <?php endif; ?>
                </td>
                <td class="col-price"><?php echo e($item['price']); ?></td>
                <td class="col-total"><?php echo e($item['total']); ?></td>
            </tr>
            <?php endforeach; ?>
            
            <?php for($i=0; $i<(12 - count($items)); $i++): ?>
            <tr class="spacer-row"><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
            <?php endfor; ?>
        </tbody>
    </table>

    <div class="footer-section">
        <div class="terms">
            *All goods sold are not returnable & not refundable.<br>
            *Warranty is void if the warranty seals have been broken, altered or peeled off.<br>
            *Warranty does not cover any LCD/LED screen crack, water damage, or effected by battery bulging.<br>
            *Warranty does not cover any product has been tampered with, repaired or modified by nonauthorized personnel.
        </div>
        <div class="totals">
            <div class="total-row"><span>SUB TOTAL</span><span>RM <?php echo number_format($displaySubtotal, 2); ?></span></div>
        </div>
    </div>

    <div class="signatures">
        <div class="sign-block"><div class="sign-label">Received By:</div><div class="sign-line"></div></div>
        <div class="sign-block">
            <div class="sign-label">Issue By:</div>
            <div class="company-stamp">
                <div class="stamp-inner">
                    <div class="stamp-brand-name">Fon2Fix</div>
                    <div class="stamp-company-name">LKF Mobile Enterprise</div>
                    <div class="stamp-reg-number">(002805193-K)</div>
                    <div class="stamp-divider"></div>
                    <div class="stamp-address">
                        39, Jalan SG 1/6<br>
                        Taman Sri Gombak<br>
                        68100, Selangor.
                    </div>
                    <div class="stamp-contact">H/P: 011-2919 0338</div>
                </div>
            </div>
            <div class="sign-line"></div>
        </div>
    </div>

    <div class="comp-gen">This is a computer generated receipt, no signature is needed</div>

</div>
</body>
</html>