<?php
require_once __DIR__ . '/includes/header.php';

use App\Repositories\PurchaseRepository;
use App\Services\PaymentService;

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$txId = $_GET['tx'] ?? '';
$purchaseRepo = new PurchaseRepository();
$paymentService = new PaymentService();

// Fetch purchase details
$stmt = db()->prepare("
    SELECT p.*, c.brand, c.model, c.year, c.city, u.name as seller_name, u.phone as seller_phone
    FROM purchases p
    JOIN cars c ON p.car_id = c.id
    JOIN users u ON c.user_id = u.id
    WHERE p.transaction_id = ? AND (p.user_id = ? OR ?)
");
$isAdmin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
$stmt->execute([$txId, $_SESSION['user_id'], $isAdmin]);
$data = $stmt->fetch();

if (!$data) {
    echo "<div class='container' style='padding: 5rem; text-align: center;'><h1>Invoice not found.</h1><a href='dashboard.php' class='btn btn-primary'>Back to Dashboard</a></div>";
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// Generate verification hash if missing (for legacy or just-in-time check)
$verificationHash = $data['verification_token'] ?: $paymentService->generateVerificationToken($data['transaction_id'], $data['total_amount']);
?>

<div class="container" style="max-width: 900px; padding: 4rem 0;">
    <div id="receipt" class="glass receipt-box" style="padding: 4rem; background: #fff; color: #1a1a1a; position: relative; overflow: hidden; border-radius: 0; border: 1px solid #ddd; box-shadow: 0 20px 50px rgba(0,0,0,0.1);">
        <!-- Watermark -->
        <div class="receipt-watermark" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(-45deg); font-size: 8rem; font-weight: 900; color: rgba(46, 213, 115, 0.08); pointer-events: none; z-index: 0; white-space: nowrap;">ENTERPRISE VERIFIED</div>

        <div class="flex justify-between align-center mb-3" style="position: relative; z-index: 1; border-bottom: 2px solid #f0f0f0; padding-bottom: 2rem;">
            <div>
                <h1 class="fw-black text-gold" style="font-size: 2.5rem; margin: 0; filter: brightness(0.8);">AfgCars Enterprise</h1>
                <p style="color: #666; font-weight: 600; letter-spacing: 1px; text-transform: uppercase; font-size: 0.8rem; margin-top: 0.5rem;">Secure Vehicle Transaction Module</p>
            </div>
            <div style="text-align: right;">
                <h2 class="fw-black" style="margin: 0; color: #333;">OFFICIAL INVOICE</h2>
                <p style="color: #888; font-weight: 700; margin-top: 0.5rem;">Invoice #: <span style="color: #333;"><?= htmlspecialchars($data['reference_number'] ?: 'INV-'.$data['id']) ?></span></p>
                <p style="color: #888; font-weight: 700;">Date: <span style="color: #333;"><?= date('M d, Y', strtotime($data['created_at'])) ?></span></p>
                <p style="color: #888; font-weight: 700;">Status: <span class="badge badge-primary"><?= strtoupper($data['status']) ?></span></p>
            </div>
        </div>

        <div class="grid grid-2 mb-3" style="position: relative; z-index: 1; gap: 4rem;">
            <div>
                <h4 style="border-bottom: 1px solid #eee; padding-bottom: 0.5rem; margin-bottom: 1.5rem; color: #aaa; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 2px; font-weight: 800;">Buyer Information</h4>
                <p class="fw-black" style="font-size: 1.2rem; margin-bottom: 0.5rem; color: #333;"><?= htmlspecialchars($data['buyer_name']) ?></p>
                <p style="margin-bottom: 0.3rem; color: #666; font-weight: 500;"><?= htmlspecialchars($data['buyer_email']) ?></p>
                <p style="margin-bottom: 0.3rem; color: #666; font-weight: 500;"><?= htmlspecialchars($data['buyer_phone']) ?></p>
                <p class="fw-black" style="color: var(--primary-color); margin-top: 1.5rem; filter: brightness(0.8);">Transaction ID: <br><span style="font-size: 0.8rem; font-family: monospace;"><?= htmlspecialchars($data['transaction_id']) ?></span></p>
            </div>
            <div>
                <h4 style="border-bottom: 1px solid #eee; padding-bottom: 0.5rem; margin-bottom: 1.5rem; color: #aaa; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 2px; font-weight: 800;">Seller Information</h4>
                <p class="fw-black" style="font-size: 1.2rem; margin-bottom: 0.5rem; color: #333;"><?= htmlspecialchars($data['seller_name']) ?></p>
                <p style="margin-bottom: 0.3rem; color: #666; font-weight: 500;">Status: Verified Premium Merchant</p>
                <p style="margin-bottom: 0.3rem; color: #666; font-weight: 500;"><?= htmlspecialchars($data['seller_phone']) ?></p>
                <p style="margin-bottom: 0.3rem; color: #666; font-weight: 500;"><?= htmlspecialchars($data['city']) ?>, Afghanistan</p>
            </div>
        </div>

        <div class="mb-3" style="position: relative; z-index: 1;">
            <table style="width: 100%; border-collapse: collapse; border: 1px solid #eee;">
                <thead>
                    <tr style="background: #fcfcfc; text-align: left;">
                        <th style="padding: 1.2rem; border-bottom: 2px solid #eee; color: #333;">Item Description</th>
                        <th style="padding: 1.2rem; border-bottom: 2px solid #eee; text-align: right; color: #333;">Amount (USD)</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td style="padding: 1.5rem 1.2rem; border-bottom: 1px solid #eee;">
                            <div class="fw-black" style="font-size: 1.3rem; color: #333;"><?= htmlspecialchars($data['brand'] . ' ' . $data['model']) ?></div>
                            <div style="color: #888; font-size: 0.9rem; margin-top: 0.5rem; font-weight: 500;"><?= $data['year'] ?> Model Vehicle - Base Price</div>
                        </td>
                        <td style="padding: 1.5rem 1.2rem; border-bottom: 1px solid #eee; text-align: right; font-weight: 800; font-size: 1.3rem; color: #333;">$<?= number_format($data['base_price'], 2) ?></td>
                    </tr>
                    <tr>
                        <td style="padding: 1rem 1.2rem; border-bottom: 1px solid #eee;">
                            <div style="color: #666; font-weight: 600;">Marketplace Service Fee</div>
                        </td>
                        <td style="padding: 1rem 1.2rem; border-bottom: 1px solid #eee; text-align: right; font-weight: 700; color: #333;">$<?= number_format($data['marketplace_fee'], 2) ?></td>
                    </tr>
                    <tr>
                        <td style="padding: 1rem 1.2rem; border-bottom: 1px solid #eee;">
                            <div style="color: #666; font-weight: 600;">Automotive Sales Tax</div>
                        </td>
                        <td style="padding: 1rem 1.2rem; border-bottom: 1px solid #eee; text-align: right; font-weight: 700; color: #333;">$<?= number_format($data['tax'], 2) ?></td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr style="background: #fafafa;">
                        <td style="padding: 2.5rem 1.2rem; text-align: right; font-weight: 700; font-size: 1.2rem; color: #666;">Total Payable Amount</td>
                        <td style="padding: 2.5rem 1.2rem; text-align: right; font-weight: 900; font-size: 2.2rem; color: var(--primary-color); filter: brightness(0.8);">$<?= number_format($data['total_amount'], 2) ?></td>
                    </tr>
                </tfoot>
            </table>
        </div>

        <div class="grid" style="grid-template-columns: 1fr 3fr; gap: 2rem; margin-top: 3rem; position: relative; z-index: 1;">
            <div style="background: #f9f9f9; padding: 1.5rem; display: flex; align-items: center; justify-content: center; border: 1px solid #eee; border-radius: 10px;">
                <!-- Placeholder for QR Code -->
                <div style="text-align: center;">
                    <div style="width: 120px; height: 120px; background: #333; padding: 10px; border-radius: 5px; position: relative;">
                        <div style="width: 100%; height: 100%; background: #fff; border: 5px solid #333; display: grid; grid-template-columns: repeat(4, 1fr);">
                            <?php for($i=0;$i<16;$i++): ?>
                                <div style="background: <?= rand(0,1) ? '#000' : '#fff' ?>;"></div>
                            <?php endfor; ?>
                        </div>
                    </div>
                    <p style="font-size: 0.6rem; margin-top: 0.5rem; color: #888; font-weight: 700; text-transform: uppercase;">Scan to Verify</p>
                </div>
            </div>
            <div style="display: flex; flex-direction: column; justify-content: center;">
                <h5 style="margin: 0 0 0.5rem 0; color: #aaa; text-transform: uppercase; font-size: 0.7rem; letter-spacing: 1px; font-weight: 800;">SHA256 Verification Code</h5>
                <p style="font-family: monospace; font-size: 0.75rem; word-break: break-all; color: #666; margin: 0; padding: 1rem; background: #f0f0f0; border-radius: 5px;"><?= $verificationHash ?></p>
            </div>
        </div>

        <div class="mt-3 text-center" style="border-top: 2px dashed #eee; padding-top: 2.5rem; color: #aaa; font-size: 0.85rem; font-weight: 600; position: relative; z-index: 1; letter-spacing: 0.5px;">
            <p style="margin-bottom: 0.5rem;">This official document is computer-generated and verified by AfgCars Enterprise Systems.</p>
            <p style="color: #ccc;">ESCROW STATUS: <?= strtoupper($data['escrow_status'] ?: 'held_in_escrow') ?> • PAYMENT METHOD: <?= strtoupper($data['payment_method'] ?: 'bank_transfer') ?></p>
        </div>
        
        <!-- Status Badge -->
        <div style="position: absolute; bottom: 120px; right: 60px; border: 6px double #2ed573; color: #2ed573; padding: 15px 30px; font-size: 2.5rem; font-weight: 900; transform: rotate(-15deg); border-radius: 12px; opacity: 0.6; pointer-events: none; text-transform: uppercase;"><?= $data['status'] ?></div>
    </div>

    <div class="mt-3 flex justify-center gap-1">
        <button onclick="window.print()" class="btn btn-primary btn-lg">Print Documentation</button>
        <a href="dashboard.php" class="btn btn-outline btn-lg">Return to Dashboard</a>
    </div>
</div>

<style>
@media print {
    nav, footer, .btn, .nav-actions { display: none !important; }
    body { background: #fff !important; color: #000 !important; }
    .container { max-width: 100% !important; padding: 0 !important; margin: 0 !important; }
    .glass { border: none !important; box-shadow: none !important; background: #fff !important; border-radius: 0 !important; }
}
</style>

<?php require_once __DIR__ . '/includes/footer.php'; ?>