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

$voucher_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$agency_id = $_SESSION['agency_id'];

// FIXED QUERY: Use LEFT JOIN so manual names (with NULL client_id) still show up
$stmt = $conn->prepare("SELECT v.*, u.name as creator_name, c.name as client_db_name, c.phone_number as client_db_phone 
                        FROM ticket_vouchers v 
                        JOIN users u ON v.agency_id = u.agency_id 
                        LEFT JOIN clients c ON v.client_id = c.id
                        WHERE v.id = ? AND v.agency_id = ?");
$stmt->bind_param("ii", $voucher_id, $agency_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("Voucher not found or access denied.");
}

$voucher = $result->fetch_assoc();
$data = json_decode($voucher['voucher_data'], true);

// Logic to determine which name/phone to show (Manual vs Database)
$display_name = $data['client_display_name'] ?? $voucher['client_db_name'] ?? 'Guest';
$display_phone = $voucher['client_db_phone'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flight Quote #TK-<?php echo str_pad($voucher_id, 4, '0', STR_PAD_LEFT); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
:root {
    --primary: #0f172a;      /* Deep corporate navy */
    --accent: #2563eb;       /* Airline blue */
    --muted: #64748b;
    --border: #e5e7eb;
    --bg-light: #f8fafc;
}

/* BASE */
body {
    background: #e6ebf2;
    font-family: 'Inter', 'Poppins', sans-serif;
    margin: 0;
    padding: 40px 0;
    color: #0f172a;
}

/* ACTION BAR */
.action-bar {
    max-width: 900px;
    margin: 0 auto 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.btn {
    padding: 10px 18px;
    border-radius: 6px;
    border: 1px solid var(--border);
    background: #fff;
    color: var(--primary);
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    gap: 8px;
}

.btn-print {
    background: var(--accent);
    color: #fff;
    border-color: var(--accent);
}

/* CONTAINER */
.voucher-container {
    background: #fff;
    max-width: 900px;
    margin: auto;
    padding: 45px;
    border-radius: 2px;
    box-shadow: 0 15px 40px rgba(15,23,42,0.08);
    border-top: 6px solid var(--accent);
}

/* HEADER */
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 25px;
    border-bottom: 1px solid var(--border);
    margin-bottom: 30px;
}

.agency-info h2 {
    margin: 0;
    font-size: 24px;
    font-weight: 700;
    letter-spacing: -0.3px;
}

.agency-info p {
    margin: 6px 0 0;
    font-size: 13px;
    color: var(--muted);
    line-height: 1.6;
}

.agency-logo img {
    max-height: 70px;
    object-fit: contain;
}

/* META INFO */
.meta-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 25px;
    margin-bottom: 40px;
}

.meta-box h4 {
    margin: 0 0 6px;
    font-size: 11px;
    text-transform: uppercase;
    color: var(--muted);
    letter-spacing: 0.08em;
}

.meta-box p {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
}

/* OPTION CARD */
.option-card {
    border: 1px solid var(--border);
    margin-bottom: 35px;
}

.option-header {
    background: var(--bg-light);
    padding: 16px 22px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--border);
}

.option-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.option-header .price {
    font-size: 18px;
    font-weight: 700;
    color: var(--accent);
}

/* TABLE */
.segments-table {
    width: 100%;
    border-collapse: collapse;
}

.segments-table th {
    background: #fbfdff;
    text-align: left;
    padding: 12px 22px;
    font-size: 11px;
    color: var(--muted);
    text-transform: uppercase;
    border-bottom: 1px solid var(--border);
}

.segments-table td {
    padding: 14px 22px;
    font-size: 14px;
    border-bottom: 1px solid var(--border);
}

/* STATUS */
.route-text {
    font-weight: 700;
    color: var(--accent);
}

.status-refundable {
    color: #166534;
    font-weight: 600;
}

.status-non-refundable {
    color: #991b1b;
    font-weight: 600;
}

/* NOTES */
.notes-box {
    background: #f9fafb;
    padding: 14px 22px;
    font-size: 12.5px;
    color: var(--muted);
    border-top: 1px dashed var(--border);
}

/* FOOTER */
.footer {
    margin-top: 45px;
    text-align: center;
    border-top: 1px solid var(--border);
    padding-top: 25px;
}

.footer p {
    font-size: 12px;
    color: var(--muted);
    margin: 4px 0;
}

/* PRINT */
@media print {
    body {
        background: #fff;
        padding: 0;
    }
    .action-bar {
        display: none;
    }
    .voucher-container {
        box-shadow: none;
        border: 1px solid #ddd;
        max-width: 100%;
    }
}
</style>

</head>
<body>

    <div class="action-bar">
        <a href="ticket_vouchers.php" class="btn btn-back"><i class="fas fa-arrow-left"></i> Back to List</a>
        <div>
            <button class="btn btn-print" onclick="window.print()"><i class="fas fa-print"></i> Print / PDF</button>
            <button class="btn btn-img" onclick="downloadVoucher()"><i class="fas fa-image"></i> Save Image</button>
        </div>
    </div>

    <div class="voucher-container" id="voucher-to-download">
        <header class="header">
            <div class="agency-info">
                <h2><?php echo AGENCY_NAME_LIVE; ?></h2>
                <p><?php echo AGENCY_ADDRESS_LIVE; ?></p>
                <p><i class="fas fa-phone-alt"></i> <?php echo AGENCY_PHONE_LIVE; ?></p>
            </div>
            <div class="agency-logo">
                <img src="<?php echo AGENCY_LOGO_LIVE; ?>" alt="Logo">
            </div>
        </header>

        <section class="meta-grid">
            <div class="meta-box">
                <h4>Prepared For</h4>
                <p><?php echo htmlspecialchars($display_name); ?> <?php echo ($display_phone ? "($display_phone)" : ""); ?></p>
                <?php if(!empty($data['contact_person'])): ?>
                    <small style="color:#64748b; font-weight:500;">Attention: <?php echo htmlspecialchars($data['contact_person']); ?></small>
                <?php endif; ?>
            </div>
            <div class="meta-box" style="text-align: right;">
                <h4>Voucher Details</h4>
                <p>#TK-<?php echo str_pad($voucher_id, 4, '0', STR_PAD_LEFT); ?></p>
                <small style="color:#64748b;">Issued on <?php echo date("d M Y", strtotime($voucher['created_at'])); ?></small>
            </div>
        </section>

        <?php if(!empty($data['flight_options'])): foreach($data['flight_options'] as $index => $option): ?>
            <div class="option-card">
                <div class="option-header">
                    <h3>FLIGHT OPTION #<?php echo $index + 1; ?></h3>
                    <div class="price">PKR <?php echo number_format($option['price']); ?></div>
                </div>
                <table class="segments-table">
                    <thead>
                        <tr>
                            <th>Route</th>
                            <th>Airline</th>
                            <th>Date</th>
                            <th>Baggage</th>
                            <th>Category</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if(!empty($option['segments'])): foreach($option['segments'] as $segment): 
                        $refundable = $segment['refundable'] ?? 'Non-refundable';
                        $refund_class = (strpos(strtolower($refundable), 'non') !== false) ? 'status-non-refundable' : 'status-refundable';
                    ?>
                        <tr>
                            <td><span class="route-text"><?php echo htmlspecialchars($segment['from']); ?> → <?php echo htmlspecialchars($segment['to']); ?></span></td>
                            <td><b><?php echo htmlspecialchars($segment['airline']); ?></b></td>
                            <td><?php echo date("d M Y", strtotime($segment['departure_date'])); ?></td>
                            <td><?php echo htmlspecialchars($segment['baggage']); ?></td>
                            <td class="<?php echo $refund_class; ?>"><?php echo htmlspecialchars($refundable); ?></td>
                        </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
                <?php if (!empty($option['rules'])): ?>
                    <div class="notes-box">
                        <strong>Important Notes:</strong> <?php echo nl2br(htmlspecialchars($option['rules'])); ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; endif; ?>

        <footer class="footer">
            <p>This is a quotation and is subject to seat availability.</p>
            <p>Generated by <b><?php echo htmlspecialchars($voucher['creator_name']); ?></b> | <?php echo AGENCY_NAME_LIVE; ?></p>
        </footer>
    </div>

    <script>
        function downloadVoucher() {
            const el = document.getElementById('voucher-to-download');
            html2canvas(el, { scale: 2, useCORS: true, backgroundColor: "#ffffff" }).then(canvas => {
                const link = document.createElement('a');
                link.download = `Flight_Quote_<?php echo $voucher_id; ?>.png`;
                link.href = canvas.toDataURL();
                link.click();
            });
        }
    </script>

</body>
</html>