<?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 umrah_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
$display_name = $data['client_display_name'] ?? $voucher['client_db_name'] ?? 'Guest';
$display_phone = $voucher['client_db_phone'] ?? '';

// Handle the options key
$umrah_options = $data['options'] ?? $data['umrah_options'] ?? [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Umrah Voucher #UM-<?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: #1f7a4f;
    --dark: #0f172a;
    --muted: #64748b;
    --border: #e2e8f0;
    --bg: #f8fafc;
}

body {
    background: #e5ebf3;
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 40px 0;
    color: var(--dark);
}

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

.btn {
    padding: 10px 18px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    display: inline-flex;
    gap: 8px;
    align-items: center;
}

.btn-back { background: #fff; border: 1px solid var(--border); }
.btn-print { background: #2563eb; color: #fff; }
.btn-img { background: #16a34a; color: #fff; }

/* MAIN VOUCHER */
.voucher-container {
    background: #fff;
    max-width: 820px;
    margin: auto;
    padding: 45px 50px;
    border-radius: 2px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.08);
    border-top: 10px solid var(--primary);
}

/* HEADER */
.header {
    display: flex;
    justify-content: space-between;
    border-bottom: 2px solid var(--border);
    padding-bottom: 20px;
    margin-bottom: 25px;
}

.agency-info h2 {
    margin: 0;
    font-size: 26px;
    color: var(--primary);
}

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

.agency-logo img {
    max-height: 75px;
}

/* META */
.meta-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--border);
    margin-bottom: 25px;
}

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

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

/* PACKAGE */
.package-card {
    border: 1px solid var(--border);
    border-radius: 10px;
    overflow: hidden;
    margin-bottom: 30px;
}

.package-header {
    background: linear-gradient(90deg, var(--primary), #2ea36a);
    color: #fff;
    padding: 14px 22px;
    display: flex;
    justify-content: space-between;
}

.package-header h3 {
    margin: 0;
    font-size: 17px;
}

.pricing-grid {
    display: flex;
    gap: 8px;
}

.price-item {
    background: rgba(255,255,255,0.2);
    padding: 6px 10px;
    border-radius: 6px;
    text-align: center;
    min-width: 70px;
}

.price-item span {
    display: block;
    font-size: 9px;
    letter-spacing: .5px;
}

.price-item b {
    font-size: 12px;
}

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

.details-table th {
    width: 150px;
    background: var(--bg);
    padding: 14px 20px;
    text-align: left;
    font-size: 11px;
    color: var(--muted);
    text-transform: uppercase;
}

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

/* ITINERARY */
.itinerary-row {
    display: flex;
    gap: 12px;
    margin-bottom: 10px;
}

.city-icon {
    width: 34px;
    height: 34px;
    border-radius: 6px;
    background: var(--bg);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--primary);
}

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

.footer p {
    font-size: 11px;
    color: var(--muted);
}

/* PRINT MODE */
@media print {

    @page {
        size: A4;
        margin: 12mm;
    }

    body {
        background: #fff;
        padding: 0;
    }

    .action-bar {
        display: none !important;
    }

    .voucher-container {
        box-shadow: none;
        border: none;
        padding: 0;
        max-width: 100%;
    }

    .package-card,
    table,
    tr {
        page-break-inside: avoid;
    }

    * {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
}

    </style>
</head>
<body>

    <div class="action-bar">
        <a href="umrah_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; ?>"></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;">Contact: <?php echo htmlspecialchars($data['contact_person']); ?></small>
                <?php endif; ?>
            </div>
            <div class="meta-box" style="text-align: right;">
                <h4>Voucher Details</h4>
                <p>#UM-<?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($umrah_options)): foreach($umrah_options as $option): ?>
            <div class="package-card">
                <div class="package-header">
                    <h3><?php echo htmlspecialchars($option['package_name'] ?? 'Umrah Package'); ?></h3>
                    <div class="pricing-grid">
                        <?php if(!empty($option['price_double'])): ?><div class="price-item"><span>Double</span><b><?php echo number_format($option['price_double']); ?></b></div><?php endif; ?>
                        <?php if(!empty($option['price_triple'])): ?><div class="price-item"><span>Triple</span><b><?php echo number_format($option['price_triple']); ?></b></div><?php endif; ?>
                        <?php if(!empty($option['price_quad'])): ?><div class="price-item"><span>Quad</span><b><?php echo number_format($option['price_quad']); ?></b></div><?php endif; ?>
                        <?php if(!empty($option['price_quint'])): ?><div class="price-item"><span>Quint</span><b><?php echo number_format($option['price_quint']); ?></b></div><?php endif; ?>
                    </div>
                </div>

                <table class="details-table">
                    <tr>
                        <th>Airline</th>
                        <td>
                            <b><?php echo htmlspecialchars($option['airline_details']['name'] ?? 'N/A'); ?></b> (<?php echo htmlspecialchars($option['airline_details']['sector'] ?? ''); ?>)<br>
                            <small>Dates: <?php echo htmlspecialchars($option['airline_details']['dates'] ?? ''); ?> | Baggage: <?php echo htmlspecialchars($option['airline_details']['baggage'] ?? ''); ?></small>
                        </td>
                    </tr>
                    <tr>
                        <th>Accommodation</th>
                        <td>
                            <?php if (!empty($option['itinerary'])): foreach ($option['itinerary'] as $leg): ?>
                                <div class="itinerary-row">
                                    <div class="city-icon"><i class="fas <?php echo (strtolower($leg['city']) == 'makkah' ? 'fa-kaaba' : 'fa-mosque'); ?>"></i></div>
                                    <div>
                                        <strong><?php echo $leg['nights']; ?> Nights in <?php echo $leg['city']; ?></strong><br>
                                        <small><?php echo htmlspecialchars($leg['hotel_name']); ?> - <?php echo $leg['distance']; ?></small>
                                    </div>
                                </div>
                            <?php endforeach; endif; ?>
                        </td>
                    </tr>
                    <?php if(!empty($option['inclusions'])): ?>
                    <tr>
                        <th>Inclusions</th>
                        <td><small><?php echo nl2br(htmlspecialchars($option['inclusions'])); ?></small></td>
                    </tr>
                    <?php endif; ?>
                </table>
            </div>
        <?php endforeach; endif; ?>

        <footer class="footer">
            <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 }).then(canvas => {
                const link = document.createElement('a');
                link.download = `Umrah_Voucher_<?php echo $voucher_id; ?>.png`;
                link.href = canvas.toDataURL();
                link.click();
            });
        }
    </script>
</body>
</html>