<?php
// invoice.php - Fixed Connection & Data Mapping

// 1. INCLUDE SHARED DB CONNECTION
include 'db.php';

// 2. GET ID SAFELY
$job_id = $_GET['id'] ?? null;

if (!$job_id) {
    die("Error: No ID provided.");
}

// 3. FETCH DATA (Using the centralized connection)
if (isset($pdo)) {
    // PDO Connection (Standard) - Using prepared statements for security
    $stmt = $pdo->prepare("SELECT * FROM jobs WHERE job_id = ?");
    $stmt->execute([$job_id]);
    $job = $stmt->fetch();
} elseif (isset($connection)) {
    // MySQLi Fallback (If db.php uses mysqli) - Using prepared statements for security
    $stmt = mysqli_prepare($connection, "SELECT * FROM jobs WHERE job_id = ?");
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "s", $job_id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $job = mysqli_fetch_assoc($result);
        mysqli_stmt_close($stmt);
    } else {
        die("Database query failed. Check db.php");
    }
} else {
    die("Database connection failed. Check db.php");
}

if (!$job) {
    die("Job Sheet not found for ID: " . htmlspecialchars($job_id));
}

// 4. MAP DATABASE COLUMNS TO TEMPLATE VARIABLES
// We map the actual DB columns (owner_name, etc.) to what this design expects (customer, etc.)
$job['customer'] = $job['owner_name'] ?? $job['customer'] ?? 'Walk-in Customer';
$job['phone']    = $job['owner_phone'] ?? $job['phone'] ?? '';
$job['model']    = $job['device_name'] ?? $job['model'] ?? 'Unknown Device';
$job['repair']   = $job['device_issue'] ?? $job['repair'] ?? 'Check Device';
$job['imei']     = $job['imei'] ?? '';
$job['passcode'] = $job['passcode'] ?? '';
$job['status']   = $job['status'] ?? 'Pending';
$job['price']    = $job['price'] ?? 0;
$job['deposit']  = $job['deposit'] ?? 0;
// Date & Branch
$rawDate = $job['created_at'] ?? $job['date'] ?? date('Y-m-d');
$job['date']     = date("d/m/Y", strtotime($rawDate));
$job['branch']   = $job['outlet'] ?? $job['branch'] ?? 'Gombak';

// --- PATTERN DRAWING FUNCTION ---
function drawPattern($sequence_str) {
    preg_match_all('/\d+/', $sequence_str, $matches);
    $seq = $matches[0];
    if (empty($seq)) return $sequence_str;
    $size = 60; $gap = 20; $padding = 10;
    $coords = [];
    for($r=0; $r<3; $r++) { for($c=0; $c<3; $c++) { $num = ($r * 3) + $c + 1; $coords[$num] = ['x' => $padding + ($c * $gap), 'y' => $padding + ($r * $gap)]; } }
    $svg = '<svg width="'.$size.'" height="'.$size.'" style="vertical-align:middle; background:#f0f0f0; border:1px solid #ccc; border-radius:4px;">';
    foreach($coords as $p) { $svg .= '<circle cx="'.$p['x'].'" cy="'.$p['y'].'" r="2" fill="#999" />'; }
    $points = []; foreach($seq as $num) { if(isset($coords[$num])) $points[] = $coords[$num]['x'] . ',' . $coords[$num]['y']; }
    if (count($points) > 1) { $polyline = implode(' ', $points); $svg .= '<polyline points="'.$polyline.'" fill="none" stroke="black" stroke-width="2" />'; }
    foreach($seq as $num) { if(isset($coords[$num])) { $svg .= '<circle cx="'.$coords[$num]['x'].'" cy="'.$coords[$num]['y'].'" r="3" fill="black" />'; } }
    $svg .= '</svg>';
    return $svg . ' <span style="font-size:10px; color:#555;">(' . implode('-', $seq) . ')</span>';
}

$logoHtml = '<div style="text-align:center; margin-bottom: 15px;"><img src="logo.png" style="width: 180px; height: auto;"></div>';
if (stripos($job['branch'], 'gombak') !== false) {
    $headerHtml = $logoHtml . '<h3 style="margin:0; text-transform:uppercase;">FON2FIX (Gombak)</h3><p style="margin:5px 0; font-size:0.9rem;">LKF Mobile Enterprise 002805193-K, 39, Jalan SG 1/6, Taman Sri Gombak, 68100 Batu Caves, Selangor<br><strong>Tel: 011-2919 0338</strong></p>';
} else {
    $headerHtml = $logoHtml . '<h3 style="margin:0; text-transform:uppercase;">FON2FIX (Sri Rampai)</h3><p style="margin:5px 0; font-size:0.9rem;">2-G-7, Wisma Rampai, Jalan 34/26, Taman Sri Rampai, KL<br><strong>Tel: 010-773 2919</strong></p>';
}
function e($str) { return htmlspecialchars(isset($str) ? $str : '', ENT_QUOTES, 'UTF-8'); }
$price = floatval($job['price']); $deposit = floatval($job['deposit']); $balance = $price - $deposit;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Job Sheet <?php echo e($job['job_id']); ?></title>
    <link rel="icon" type="image/png" href="logo.png">
    <link rel="shortcut icon" type="image/png" href="logo.png">
    <style>
        body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; padding: 20px; color: #000; font-size: 14px; max-width: 800px; margin: 0 auto; background: #fff;}
        .header { text-align: center; margin-bottom: 20px; }
        .box-container { border: 2px solid #000; padding: 0; margin-bottom: 15px; }
        .box-header { background: #eee; border-bottom: 1px solid #000; padding: 5px 10px; font-weight: bold; text-transform: uppercase; font-size: 12px; }
        .box-content { padding: 10px; }
        .row { display: flex; justify-content: space-between; margin-bottom: 5px; }
        .label { font-weight: bold; width: 100px; display: inline-block; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { border: 1px solid #000; padding: 8px; text-align: left; }
        th { background: #eee; font-size: 12px; text-transform: uppercase; }
        .terms { font-size: 10px; text-align: justify; color: #444; margin: 20px 0; line-height: 1.3; }
        .signatures { display: flex; justify-content: space-between; margin-top: 50px; }
        .sign-line { width: 40%; border-top: 1px solid #000; text-align: center; padding-top: 5px; font-weight: bold; }
        .print-btn { text-align: center; margin-bottom: 20px; }
        @media print { .print-btn { display: none; } body { padding: 0; } }
        
        .stamp-paid { color:green; border: 3px solid green; padding: 5px 10px; transform: rotate(-5deg); display:inline-block; font-size:20px; font-weight:bold; }
        .stamp-partial { color:orange; border: 3px solid orange; padding: 5px 10px; transform: rotate(-5deg); display:inline-block; font-size:20px; font-weight:bold; }
        .stamp-unpaid { color:red; border: 3px solid red; padding: 5px 10px; transform: rotate(-5deg); display:inline-block; font-size:20px; font-weight:bold; }
    </style>
</head>
<body>
    <div class="print-btn"><button onclick="window.print()">🖨 Print / Save as PDF</button></div>
    <div class="header"><?php echo $headerHtml; ?></div>
    
    <div style="display:flex; gap: 20px; margin-bottom: 20px;">
        <div style="flex:1; border: 1px solid #000; padding: 10px;">
            <div class="row"><span class="label">Customer:</span> <span><?php echo e($job['customer']); ?></span></div>
            <div class="row"><span class="label">Phone:</span> <span><?php echo e($job['phone']); ?></span></div>
            <div class="row"><span class="label">Date In:</span> <span><?php echo e($job['date']); ?></span></div>
        </div>
        <div style="flex:1; border: 1px solid #000; padding: 10px;">
            <div class="row"><span class="label">Job ID:</span> <span style="font-weight:bold; font-size:16px"><?php echo e($job['job_id']); ?></span></div>
            <div class="row"><span class="label">Status:</span> <span><?php echo e($job['status']); ?></span></div>
        </div>
    </div>

    <div class="box-container">
        <div class="box-header">Device Details</div>
        <div class="box-content">
            <div class="row">
                <span style="width:50%"><strong>Model:</strong> <?php echo e($job['model']); ?></span>
                <span style="width:50%"><strong>IMEI:</strong> <?php echo e($job['imei']); ?></span>
            </div>
            <div class="row" style="margin-top:5px;">
                <span style="width:50%; display:flex; align-items:center;">
                    <strong>Passcode:</strong>&nbsp; 
                    <?php if (strpos($job['passcode'], 'Pattern:') !== false) { echo drawPattern($job['passcode']); } else { echo e($job['passcode']); } ?>
                </span>
            </div>
        </div>
    </div>

    <table>
        <thead><tr><th>Service / Repair Description</th><th style="width:120px; text-align:right">Cost</th></tr></thead>
        <tbody><tr><td style="height: 60px; vertical-align: top;"><?php echo e($job['repair']); ?></td><td style="text-align:right; vertical-align: top;">RM <?php echo number_format($price, 2); ?></td></tr></tbody>
    </table>
    
    <?php if (!empty($job['remarks'])): ?>
    <div style="margin-top: 15px; border: 1px dashed #444; padding: 8px; background: #f9f9f9; font-size:12px;"><strong>📝 Remarks:</strong><br><?php echo nl2br(e($job['remarks'])); ?></div>
    <?php endif; ?>

    <div style="margin-top: 20px; border-top: 2px solid #000; padding-top: 15px;">
        <div style="float: left; width: 50%;">
            <?php 
                $status = strtoupper($job['payment_status'] ?? 'UNPAID');
                if($status == 'PAID') echo '<div class="stamp-paid">PAID</div>';
                elseif($status == 'PARTIAL') echo '<div class="stamp-partial">PARTIAL / DEPO</div>';
                else echo '<div class="stamp-unpaid">UNPAID</div>';
            ?>
        </div>
        <div style="float: right; text-align: right; width: 50%;">
            <div style="margin-bottom: 5px;">Total Amount: RM <?php echo number_format($price, 2); ?></div>
            <?php if ($deposit > 0): ?>
                <div style="margin-bottom: 5px; color: #666;">Less Deposit: - RM <?php echo number_format($deposit, 2); ?></div>
            <?php endif; ?>
            <?php 
                $paymentMethod = $job['payment_method'] ?? 'Cash';
                if (!empty($paymentMethod)) {
                    // Parse and format payment methods with amounts
                    $parts = explode(' + ', $paymentMethod);
                    $formatted = [];
                    foreach ($parts as $part) {
                        $part = trim($part);
                        // Check if it already has amount format: "Method (RM X)"
                        if (preg_match('/^(.+?)\s*\(RM\s*([\d.]+)\)$/', $part, $matches)) {
                            $formatted[] = $matches[1] . ' (RM ' . number_format($matches[2], 2) . ')';
                        } else {
                            $formatted[] = $part;
                        }
                    }
                    echo '<div style="margin-bottom: 5px; color: #666; font-size: 12px;">Payment: ' . htmlspecialchars(implode(' + ', $formatted)) . '</div>';
                }
            ?>
            <div style="font-size: 20px; font-weight: bold; margin-top: 10px; border-top: 1px solid #ccc; padding-top: 5px;">
                <?php if($status == 'PAID'): ?>
                    Balance Due: RM 0.00
                <?php else: ?>
                    Balance Due: RM <?php echo number_format($balance, 2); ?>
                <?php endif; ?>
            </div>
        </div>
        <div style="clear:both;"></div>
    </div>

    <div class="terms">
        <strong>Terms & Conditions:</strong><br>
        1. Fon2Fix is not responsible for any data loss during the repair process. Please backup your data beforehand.<br>
        2. Warranty covers the replaced part only. Physical damage or water damage voids the warranty.<br>
        3. Devices not collected within 60 days will be disposed of.<br>
    </div>

    <div class="signatures">
        <div class="sign-line">Customer Signature<br><span style="font-weight:normal; font-size:10px">I agree to the terms above</span></div>
        <div class="sign-line">LKF Mobile Enterprise 002805193-K</div>
    </div>
</body>
</html>