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

$agency_id = $_SESSION['agency_id'];

// Fetch All Clients for Autocomplete Search
$client_list = [];
$clients_res = $conn->query("SELECT id, name, phone_number FROM clients WHERE agency_id = $agency_id ORDER BY name ASC");
while($row = $clients_res->fetch_assoc()){ $client_list[] = $row; }
$aid = $_SESSION['agency_id'];
$usage = $conn->query("SELECT tickets_used, max_tickets FROM agencies WHERE id = $aid")->fetch_assoc();
if($usage['tickets_used'] >= $usage['max_tickets']) { 
    die("Monthly Limit Reached! Vouchers available next month."); 
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Ticket Voucher | Travel SaaS</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #4e73df; --secondary: #1e293b; --success: #1cc88a; --danger: #e74a3b; --bg-color: #f8f9fc; --sidebar-width: 260px; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg-color); display: flex; }
        .sidebar { width: var(--sidebar-width); background: var(--secondary); height: 100vh; position: fixed; color: #fff; padding: 20px 0; }
        .nav-link { display: flex; align-items: center; padding: 12px 15px; color: rgba(255,255,255,0.7); text-decoration: none; border-radius: 8px; margin: 5px 20px; }
        .active { background: rgba(255,255,255,0.1); color: #fff; }
        .main-content { margin-left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); padding: 40px; }
        .card { background: #fff; padding: 30px; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); margin-bottom: 25px; }
        label { display: block; font-size: 11px; font-weight: 700; color: #64748b; margin-bottom: 5px; text-transform: uppercase; }
        input, select { width: 100%; padding: 12px; border: 1px solid #e2e8f0; border-radius: 10px; font-size: 14px; outline: none; }
        .search-wrapper { position: relative; }
        .results-box { position: absolute; background: white; width: 100%; z-index: 1000; border: 1px solid #ddd; border-radius: 10px; max-height: 200px; overflow-y: auto; display: none; box-shadow: 0 10px 25px rgba(0,0,0,0.1); margin-top: 5px; }
        .result-item { padding: 12px 15px; cursor: pointer; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        .result-item:hover { background: #f8f9fc; }
        .ticket-option { background: #fcfdfd; border: 1px solid #e2e8f0; padding: 25px; border-radius: 15px; margin-bottom: 20px; position: relative; }
        .flight-leg { background: #fff; border: 1px dashed #cbd5e1; padding: 15px; border-radius: 10px; margin-top: 15px; }
        .btn { padding: 10px 20px; border-radius: 8px; border: none; cursor: pointer; font-weight: 600; font-size: 13px; display: inline-flex; align-items: center; gap: 8px; transition: 0.3s; }
        .btn-primary { background: var(--primary); color: #fff; }
        .btn-success { background: var(--success); color: #fff; }
        .btn-danger { background: var(--danger); color: #fff; }
    </style>
</head>
<body>

    <div class="sidebar">
        <div style="padding: 20px; font-weight: 600;"><?php echo AGENCY_NAME_LIVE; ?></div>
        <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <a href="ticket_vouchers.php" class="nav-link active"><i class="fas fa-ticket-alt"></i> Ticket Vouchers</a>
        <a href="logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <div class="main-content">
        <div style="display: flex; justify-content: space-between; margin-bottom: 25px; align-items:center;">
            <h2 style="font-weight: 700;">Flight Quotation Builder</h2>
            <a href="ticket_vouchers.php" class="btn btn-primary" style="background:#64748b;"><i class="fas fa-list"></i> View All Quotes</a>
        </div>

        <form method="POST" action="handle_ticket_voucher.php">
            <!-- Section 1: Client Selection (Hybrid) -->
            <div class="card">
                <div style="border-bottom: 1px solid #f1f5f9; padding-bottom: 10px; margin-bottom: 20px;"><h3>1. Client Information</h3></div>
                <div style="display: grid; grid-template-columns: 1.5fr 1fr; gap: 20px;">
                    <div class="search-wrapper">
                        <label>Client Name (Search or Type New)</label>
                        <input type="text" name="manual_client_name" id="client_search" placeholder="Type name or search..." autocomplete="off" required>
                        <input type="hidden" name="client_id" id="client_id_hidden">
                        <div id="results_box" class="results-box"></div>
                    </div>
                    <div>
                        <label>Contact Person (Agent Name)</label>
                        <input type="text" name="contact_person" placeholder="e.g. Ahmad Daud">
                    </div>
                </div>
            </div>

            <!-- Section 2: Flight Options -->
            <div class="card">
                <div style="display:flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3>2. Flight Options & Quotes</h3>
                    <button type="button" onclick="addTicketOption()" class="btn btn-success"><i class="fas fa-plus"></i> Add Option</button>
                </div>
                <div id="ticket-options-container"></div>
            </div>

            <button type="submit" class="btn btn-primary" style="width: 100%; padding: 18px; font-size: 16px; justify-content: center;">
                <i class="fas fa-file-invoice"></i> Generate Professional Ticket Voucher
            </button>
        </form>
    </div>

<!-- TEMPLATES -->
<template id="ticket-option-template">
    <div class="ticket-option">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px;">
            <h4>Option #<span class="option-number"></span></h4>
            <button type="button" class="btn btn-danger" onclick="this.closest('.ticket-option').remove()"><i class="fas fa-trash"></i></button>
        </div>
        <div class="legs-container"></div>
        <button type="button" onclick="addFlightLeg(this)" class="btn btn-primary" style="background:#6c757d; margin: 15px 0;"><i class="fas fa-plus"></i> Add Flight Leg</button>
        <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px;">
            <div><label>Total Price (PKR)</label><input type="number" name="options[__OPTION_INDEX__][price]" required></div>
            <div><label>Terms / Notes</label><input type="text" name="options[__OPTION_INDEX__][rules]" placeholder="e.g. Non-refundable"></div>
        </div>
    </div>
</template>

<template id="flight-leg-template">
    <div class="flight-leg">
        <div style="display:flex; justify-content:space-between; margin-bottom:10px;">
            <span style="font-size:10px; font-weight:700; color:var(--primary);">Segment #<span class="leg-number"></span></span>
            <span class="btn-danger" style="cursor:pointer; font-size:10px; padding:2px 8px; border-radius:5px;" onclick="this.closest('.flight-leg').remove()">Remove</span>
        </div>
        <div style="display:grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 10px; margin-bottom: 10px;">
            <input type="text" name="options[__OPTION_INDEX__][segments][__LEG_INDEX__][from]" placeholder="From (LHE)" required>
            <input type="text" name="options[__OPTION_INDEX__][segments][__LEG_INDEX__][to]" placeholder="To (JED)" required>
            <input type="text" name="options[__OPTION_INDEX__][segments][__LEG_INDEX__][airline]" placeholder="Airline">
            <input type="date" name="options[__OPTION_INDEX__][segments][__LEG_INDEX__][departure_date]">
        </div>
        <div style="display:grid; grid-template-columns: 1.5fr 1fr 1.5fr; gap: 10px;">
            <input type="text" name="options[__OPTION_INDEX__][segments][__LEG_INDEX__][baggage]" placeholder="Baggage (e.g. 30KG)">
            <input type="text" name="options[__OPTION_INDEX__][segments][__LEG_INDEX__][stops]" placeholder="Stops">
            <select name="options[__OPTION_INDEX__][segments][__LEG_INDEX__][refundable]">
                <option value="Non-refundable">Non-refundable</option>
                <option value="Refundable">Refundable</option>
            </select>
        </div>
    </div>
</template>

<script>
    const clients = <?php echo json_encode($client_list); ?>;
    const searchInput = document.getElementById('client_search');
    const resultsBox = document.getElementById('results_box');
    const hiddenId = document.getElementById('client_id_hidden');

    searchInput.addEventListener('input', function() {
        const val = this.value.toLowerCase();
        resultsBox.innerHTML = '';
        hiddenId.value = ''; // Reset ID if user types fresh
        if(val.length < 1) { resultsBox.style.display = 'none'; return; }
        const filtered = clients.filter(c => c.name.toLowerCase().includes(val) || c.phone_number.includes(val));
        if(filtered.length > 0) {
            resultsBox.style.display = 'block';
            filtered.forEach(c => {
                const div = document.createElement('div');
                div.className = 'result-item';
                div.innerHTML = `<b>${c.name}</b> - ${c.phone_number}`;
                div.onclick = function() {
                    searchInput.value = c.name;
                    hiddenId.value = c.id;
                    resultsBox.style.display = 'none';
                };
                resultsBox.appendChild(div);
            });
        }
    });

    let optionIndex = 0;
    function addTicketOption() {
        const container = document.getElementById('ticket-options-container');
        const template = document.getElementById('ticket-option-template').content.cloneNode(true);
        const div = template.querySelector('.ticket-option');
        div.innerHTML = div.innerHTML.replace(/__OPTION_INDEX__/g, optionIndex);
        div.querySelector('.option-number').textContent = optionIndex + 1;
        container.appendChild(div);
        addFlightLeg(container.lastElementChild.querySelector('button[onclick="addFlightLeg(this)"]'));
        optionIndex++;
    }

    function addFlightLeg(btn) {
        const optDiv = btn.closest('.ticket-option');
        const optIdx = optDiv.querySelector('[name*="options["]').name.match(/\[(\d+)\]/)[1];
        const container = optDiv.querySelector('.legs-container');
        const template = document.getElementById('flight-leg-template').content.cloneNode(true);
        let html = template.firstElementChild.outerHTML;
        html = html.replace(/__OPTION_INDEX__/g, optIdx).replace(/__LEG_INDEX__/g, container.children.length);
        const temp = document.createElement('div'); temp.innerHTML = html;
        temp.firstElementChild.querySelector('.leg-number').textContent = container.children.length + 1;
        container.appendChild(temp.firstElementChild);
    }
    addTicketOption();
</script>
</body>
</html>