<?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!');

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3 no-print">
            <h4 class="page-title mb-0"><i class="fas fa-file-invoice me-2"></i>Repair Invoice - <?= htmlspecialchars($job['job_no']) ?></h4>
            <div>
                <a href="print_repair_invoice.php?id=<?= $id ?>" class="btn btn-primary" target="_blank"><i class="fas fa-print me-1"></i> Print</a>
                <a href="view_repair_job.php?id=<?= $id ?>" class="btn btn-info"><i class="fas fa-eye me-1"></i> View Job</a>
                <a href="repair_jobs.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="text-center mb-4">
                    <img src="<?= htmlspecialchars(getShopLogoUrl()) ?>?v=<?= time() ?>" alt="Logo" style="max-height:60px;margin-bottom:5px;" onerror="this.style.display='none'">
                    <h3 class="fw-bold"><?= htmlspecialchars($shop_name) ?></h3>
                    <p class="mb-0"><?= nl2br(htmlspecialchars($shop_address)) ?></p>
                    <p class="mb-0">Phone: <?= htmlspecialchars($shop_phone) ?><?= $shop_email ? ' | Email: ' . htmlspecialchars($shop_email) : '' ?></p>
                </div>
                <hr>
                <h5 class="text-center fw-bold" style="color:#1a237e;">REPAIR INVOICE</h5>
                <div class="row mb-4">
                    <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">
                        <strong>Job #:</strong> <?= htmlspecialchars($job['job_no']) ?><br>
                        <strong>Date:</strong> <?= formatDate($job['created_at']) ?><br>
                        <strong>Technician:</strong> <?= htmlspecialchars($job['technician_name'] ?? 'Unassigned') ?><br>
                        <strong>Status:</strong> <?= getStatusBadge($job['repair_status']) ?>
                    </div>
                </div>

                <h6 class="fw-bold" style="border-bottom:1px solid #ddd;padding-bottom:5px;">Device Information</h6>
                <table class="table table-sm mb-4">
                    <tr><td width="150">Brand:</td><td><?= htmlspecialchars($job['device_brand'] ?? '-') ?></td></tr>
                    <tr><td>Model:</td><td><?= htmlspecialchars($job['device_model'] ?? '-') ?></td></tr>
                    <tr><td>IMEI/Serial:</td><td><code><?= htmlspecialchars($job['device_imei'] ?? '-') ?></code></td></tr>
                    <tr><td>Color:</td><td><?= htmlspecialchars($job['device_color'] ?? '-') ?></td></tr>
                    <tr><td>Problem:</td><td><?= nl2br(htmlspecialchars($job['problem_description'])) ?></td></tr>
                </table>

                <?php if (count($parts) > 0): ?>
                <h6 class="fw-bold" style="border-bottom:1px solid #ddd;padding-bottom:5px;">Spare Parts Used</h6>
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead class="table-light"><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><?= formatCurrency($p['selling_price']) ?></td><td><?= formatCurrency($p['total_price']) ?></td></tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <?php if ($job['repair_warranty_days'] > 0): ?>
                        <p class="mb-1"><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; ?>
                        <?php if (count($payments) > 0): ?>
                        <p class="mb-1"><strong>Payment Method(s):</strong>
                        <?php
                        $methods = array_unique(array_column($payments, 'payment_method'));
                        echo htmlspecialchars(implode(', ', $methods));
                        ?>
                        </p>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless">
                            <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 class="fw-bold" style="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 class="text-danger fw-bold"><td>Balance Due:</td><td class="text-end"><?= formatCurrency($job['due_amount']) ?></td></tr>
                        </table>
                    </div>
                </div>

                <hr>
                <p class="text-center text-muted small mb-0"><?= nl2br(htmlspecialchars($invoice_footer)) ?></p>
                <p class="text-center text-muted small mb-0" style="margin-top:30px;">Authorized Signature</p>
                <p class="text-center mb-0">_________________________</p>
            </div>
        </div>
    </div>
</div>

<style media="print">
    .sidebar, .navbar, .footer, .no-print, .btn { display: none !important; }
    .content-wrapper { margin: 0 !important; padding: 0 !important; width: 100% !important; }
    .card { box-shadow: none !important; border: 1px solid #ddd !important; }
</style>
<?php include __DIR__ . '/../includes/footer.php'; ?>
