<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';

$id = (int)($_GET['id'] ?? 0);
if (!$id) { die('Invalid job ID.'); }

$pdo = getDB();
$stmt = $pdo->prepare("
    SELECT rj.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address,
           u.name as technician_name, cr.name as created_by_name
    FROM repair_jobs rj
    LEFT JOIN customers c ON rj.customer_id = c.id
    LEFT JOIN users u ON rj.assigned_technician_id = u.id
    LEFT JOIN users cr ON rj.created_by = cr.id
    WHERE rj.id = ?
");
$stmt->execute([$id]);
$job = $stmt->fetch();
if (!$job) { die('Job not found.'); }

$parts = $pdo->prepare("SELECT rjp.*, p.product_name FROM repair_job_parts rjp JOIN products p ON rjp.product_id = p.id WHERE rjp.repair_job_id = ?");
$parts->execute([$id]);
$parts = $parts->fetchAll();

$payments = $pdo->prepare("SELECT p.*, u.name as received_by_name FROM payments p LEFT JOIN users u ON p.received_by = u.id WHERE p.payment_type = 'repair' AND p.reference_id = ?");
$payments->execute([$id]);
$payments = $payments->fetchAll();

$shop_name = getSetting('shop_name', 'DigiMobiz');
$shop_address = getSetting('shop_address', '');
$shop_phone = getSetting('shop_phone', '');
$shop_email = getSetting('shop_email', '');
$invoice_footer = getSetting('invoice_footer', 'Thank you for your business!');
$currency = getSetting('currency_symbol', 'Rs.');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Repair Invoice - <?= htmlspecialchars($job['job_no']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; background: #fff; padding: 20px; }
        .invoice-box { max-width: 800px; margin: auto; padding: 20px; border: 1px solid #eee; border-radius: 8px; }
        .header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #1a237e; padding-bottom: 15px; }
        .header img { max-height: 60px; margin-bottom: 5px; }
        .header h3 { color: #1a237e; font-weight: 700; margin-bottom: 2px; }
        .header p { margin-bottom: 0; color: #666; font-size: 0.9rem; }
        .invoice-title { text-align: center; font-size: 1.4rem; font-weight: 700; color: #1a237e; margin: 15px 0; }
        table.details { width: 100%; font-size: 0.9rem; }
        table.details td { padding: 3px 5px; }
        table.items { width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 0.9rem; }
        table.items th { background: #1a237e; color: #fff; padding: 8px; text-align: left; font-size: 0.85rem; }
        table.items td { padding: 6px 8px; border-bottom: 1px solid #ddd; }
        table.items tr:nth-child(even) { background: #f8f9fa; }
        .total-table { width: 100%; max-width: 350px; margin-left: auto; font-size: 0.9rem; }
        .total-table td { padding: 4px 8px; }
        .footer-text { text-align: center; margin-top: 20px; padding-top: 10px; border-top: 1px solid #ddd; font-size: 0.85rem; color: #666; }
        .btn-print { text-align: center; margin: 20px 0; }
        @media print {
            .btn-print { display: none; }
            body { padding: 0; }
            .invoice-box { border: none; padding: 0; }
        }
        @media (max-width: 576px) {
            .invoice-box { padding: 10px; }
            .row .col-6 { width: 100%; }
        }
    </style>
</head>
<body>
    <div class="btn-print">
        <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print me-1"></i> Print</button>
        <a href="view_repair_job.php?id=<?= $id ?>" class="btn btn-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
    </div>

    <div class="invoice-box">
        <div class="header">
            <img src="<?= htmlspecialchars(getShopLogoUrl()) ?>?v=<?= time() ?>" alt="Logo" onerror="this.style.display='none'">
            <h3><?= htmlspecialchars($shop_name) ?></h3>
            <p><?= nl2br(htmlspecialchars($shop_address)) ?></p>
            <p>Phone: <?= htmlspecialchars($shop_phone) ?> <?= $shop_email ? '| Email: ' . htmlspecialchars($shop_email) : '' ?></p>
        </div>

        <div class="invoice-title">REPAIR INVOICE</div>

        <div class="row">
            <div class="col-6">
                <strong>Customer:</strong><br>
                <?= htmlspecialchars($job['customer_name'] ?? '-') ?><br>
                <?= htmlspecialchars($job['customer_phone'] ?? '') ?><br>
                <?= nl2br(htmlspecialchars($job['customer_address'] ?? '')) ?>
            </div>
            <div class="col-6 text-end">
                <table class="details" style="margin-left:auto;">
                    <tr><td><strong>Job No:</strong></td><td><?= htmlspecialchars($job['job_no']) ?></td></tr>
                    <tr><td><strong>Invoice Date:</strong></td><td><?= date('Y-m-d') ?></td></tr>
                    <tr><td><strong>Status:</strong></td><td><?= htmlspecialchars($job['repair_status']) ?></td></tr>
                    <tr><td><strong>Technician:</strong></td><td><?= htmlspecialchars($job['technician_name'] ?? 'Unassigned') ?></td></tr>
                </table>
            </div>
        </div>

        <hr>
        <table class="details">
            <tr><td width="120"><strong>Device:</strong></td><td><?= htmlspecialchars($job['device_brand'] ?? '') ?> <?= htmlspecialchars($job['device_model'] ?? '') ?></td></tr>
            <tr><td><strong>IMEI/Serial:</strong></td><td><code><?= htmlspecialchars($job['device_imei'] ?? '-') ?></code></td></tr>
            <tr><td><strong>Color:</strong></td><td><?= htmlspecialchars($job['device_color'] ?? '-') ?></td></tr>
            <tr><td><strong>Problem:</strong></td><td><?= nl2br(htmlspecialchars($job['problem_description'])) ?></td></tr>
        </table>

        <?php if (count($parts) > 0): ?>
        <h6 style="margin-top:15px;font-weight:700;">Spare Parts Used</h6>
        <table class="items">
            <thead><tr><th>#</th><th>Part Name</th><th>Qty</th><th>Unit Price</th><th>Total</th></tr></thead>
            <tbody>
                <?php $i = 1; foreach ($parts as $p): ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlspecialchars($p['product_name']) ?></td>
                    <td><?= $p['quantity'] ?></td>
                    <td><?= $currency ?> <?= number_format($p['selling_price'], 2) ?></td>
                    <td><?= $currency ?> <?= number_format($p['total_price'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>

        <table class="total-table">
            <tr><td>Parts Total:</td><td class="text-end"><?= formatCurrency($job['parts_total']) ?></td></tr>
            <tr><td>Labour Charge:</td><td class="text-end"><?= formatCurrency($job['labour_charge']) ?></td></tr>
            <?php if ($job['discount_amount'] > 0): ?>
            <tr><td>Discount:</td><td class="text-end text-danger">-<?= formatCurrency($job['discount_amount']) ?></td></tr>
            <?php endif; ?>
            <tr style="font-weight:700;font-size:1.1rem;border-top:2px solid #1a237e;"><td>Final Amount:</td><td class="text-end"><?= formatCurrency($job['final_amount']) ?></td></tr>
            <tr><td>Advance Paid:</td><td class="text-end"><?= formatCurrency($job['advance_payment']) ?></td></tr>
            <tr><td>Total Paid:</td><td class="text-end text-success"><?= formatCurrency($job['paid_amount']) ?></td></tr>
            <tr style="font-weight:700;color:#c62828;"><td>Balance Due:</td><td class="text-end"><?= formatCurrency($job['due_amount']) ?></td></tr>
        </table>

        <?php if (count($payments) > 0): ?>
        <h6 style="margin-top:10px;font-weight:700;">Payment Summary</h6>
        <table class="items">
            <thead><tr><th>Date</th><th>Method</th><th>Amount</th><th>Received By</th></tr></thead>
            <tbody>
                <?php foreach ($payments as $pmt): ?>
                <tr>
                    <td><?= formatDate($pmt['payment_date'], 'Y-m-d') ?></td>
                    <td><?= htmlspecialchars($pmt['payment_method']) ?></td>
                    <td><?= formatCurrency($pmt['amount']) ?></td>
                    <td><?= htmlspecialchars($pmt['received_by_name'] ?? 'System') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>

        <?php if ($job['repair_warranty_days'] > 0): ?>
        <p style="margin-top:10px;font-size:0.85rem;">
            <strong>Repair Warranty:</strong> <?= $job['repair_warranty_days'] ?> days
            <?php if ($job['repair_warranty_start_date']): ?>
            (<?= formatDate($job['repair_warranty_start_date']) ?> to <?= formatDate($job['repair_warranty_end_date']) ?>)
            <?php endif; ?>
        </p>
        <?php endif; ?>

        <div class="footer-text">
            <p><?= nl2br(htmlspecialchars($invoice_footer)) ?></p>
            <p style="margin-top:30px;">Authorized Signature</p>
            <p style="margin-top:5px;">_________________________</p>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
