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

$agency_id = $_SESSION['agency_id'];
$clients_res = $conn->query("SELECT id, name, phone_number FROM clients WHERE agency_id = $agency_id ORDER BY name ASC");
$client_list = [];
while($row = $clients_res->fetch_assoc()){ $client_list[] = $row; }
$aid = $_SESSION['agency_id'];
$usage = $conn->query("SELECT umrah_used, max_umrah FROM agencies WHERE id = $aid")->fetch_assoc();
if($usage['umrah_used'] >= $usage['max_umrah']) { 
    die("Monthly Limit Reached! Vouchers available next month."); 
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Umrah Voucher</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: #28a745; --bg: #f8f9fc; --danger: #ef4444; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); padding: 40px; }
        .container { max-width: 1000px; margin: auto; }
        .card { background: #fff; padding: 30px; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); margin-bottom: 20px; }
        label { display: block; font-size: 11px; font-weight: 700; color: #64748b; margin-bottom: 5px; text-transform: uppercase; }
        input, select, textarea { width: 100%; padding: 12px; border: 1px solid #e2e8f0; border-radius: 10px; font-size: 14px; margin-bottom: 10px; }
        
        .umrah-option { background: #fcfdfd; border: 1px solid #e2e8f0; padding: 25px; border-radius: 12px; margin-bottom: 20px; position: relative; }
        .itinerary-leg { background: #fff; border: 1px dashed #cbd5e1; padding: 15px; border-radius: 8px; margin-top: 10px; position: relative; }
        
        .btn { padding: 10px 20px; border-radius: 8px; border: none; cursor: pointer; font-weight: 600; transition: 0.3s; display: inline-flex; align-items: center; gap: 8px; }
        .btn-primary { background: #4e73df; color: #fff; }
        .btn-success { background: var(--primary); color: #fff; }
        .btn-danger { background: var(--danger); color: #fff; padding: 5px 10px; font-size: 11px; }

        .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); }
        .result-item { padding: 12px 15px; cursor: pointer; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        .row-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; }
    </style>
</head>
<body>

<div class="container">
    <form method="POST" action="handle_umrah_voucher.php">
        <!-- Section 1: Client Name (Manual or Search) -->
        <div class="card">
            <h3>1. Client Information</h3>
            <div style="display: grid; grid-template-columns: 1.5fr 1fr; gap: 20px; margin-top:15px;">
                <div class="search-wrapper">
                    <label>Client Name (Type anything or Search)</label>
                    <input type="text" name="manual_client_name" id="client_search" placeholder="Type Client Name..." 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)</label>
                    <input type="text" name="contact_person" placeholder="Agent Name">
                </div>
            </div>
        </div>

        <!-- Section 2: Package Options -->
        <div class="card">
            <div style="display:flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3>2. Package Details</h3>
                <button type="button" onclick="addUmrahOption()" class="btn btn-success"><i class="fas fa-plus"></i> Add Package Option</button>
            </div>
            <div id="umrah-options-container"></div>
        </div>
        
        <button type="submit" class="btn btn-primary" style="width: 100%; padding: 18px; font-size: 18px; justify-content: center; box-shadow: 0 10px 20px rgba(78, 115, 223, 0.2);">Generate Professional Voucher</button>
    </form>
</div>

<!-- TEMPLATE FOR OPTION -->
<template id="umrah-option-template">
    <div class="umrah-option">
        <div style="display:flex; justify-content:space-between; align-items:center;">
            <h4>Package Option #<span class="option-number"></span></h4>
            <button type="button" class="btn btn-danger" onclick="this.closest('.umrah-option').remove()"><i class="fas fa-trash"></i> Remove Option</button>
        </div>
        <hr style="margin: 15px 0; opacity: 0.1;">
        
        <label>Package Title</label>
        <input type="text" name="options[__OPTION_INDEX__][package_name]" placeholder="e.g. 15 Days Gold Package" required>
        
        <div class="row-4">
            <div><label>Airline</label><input type="text" name="options[__OPTION_INDEX__][airline_details][name]"></div>
            <div><label>Sector</label><input type="text" name="options[__OPTION_INDEX__][airline_details][sector]"></div>
            <div><label>Travel Dates</label><input type="text" name="options[__OPTION_INDEX__][airline_details][dates]"></div>
            <div><label>Baggage</label><input type="text" name="options[__OPTION_INDEX__][airline_details][baggage]" placeholder="e.g. 30KG"></div>
        </div>

        <div class="itinerary-container"></div>
        <button type="button" onclick="addItineraryLeg(this)" class="btn btn-primary" style="background:#64748b; margin-top:10px; font-size:12px;">+ Add Stay / Leg</button>

        <label style="margin-top:20px;">Package Inclusions</label>
        <textarea name="options[__OPTION_INDEX__][inclusions]" rows="3" placeholder="Visa, Transport, Ziarat etc..."></textarea>
        
        <!-- 4 PRICING BOXES -->
        <div class="row-4">
            <div><label>Double Price</label><input type="text" name="options[__OPTION_INDEX__][price_double]"></div>
            <div><label>Triple Price</label><input type="text" name="options[__OPTION_INDEX__][price_triple]"></div>
            <div><label>Quad Price</label><input type="text" name="options[__OPTION_INDEX__][price_quad]"></div>
            <div><label>Quint Price</label><input type="text" name="options[__OPTION_INDEX__][price_quint]"></div>
        </div>
    </div>
</template>

<!-- TEMPLATE FOR STAY -->
<template id="itinerary-leg-template">
    <div class="itinerary-leg">
        <button type="button" class="btn btn-danger" style="position:absolute; top:10px; right:10px;" onclick="this.closest('.itinerary-leg').remove()"><i class="fas fa-times"></i></button>
        <div style="display:grid; grid-template-columns: 1fr 2fr 1fr 1.5fr; gap:10px;">
            <div><label>City</label><select name="options[__OPTION_INDEX__][itinerary][__LEG_INDEX__][city]"><option>Makkah</option><option>Madinah</option></select></div>
            <div><label>Hotel Name</label><input type="text" name="options[__OPTION_INDEX__][itinerary][__LEG_INDEX__][hotel_name]" required></div>
            <div><label>Nights</label><input type="number" name="options[__OPTION_INDEX__][itinerary][__LEG_INDEX__][nights]" required></div>
            <div><label>Distance</label><input type="text" name="options[__OPTION_INDEX__][itinerary][__LEG_INDEX__][distance]" placeholder="e.g. 500m"></div>
        </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 = '';
        if(val.length < 1) { resultsBox.style.display = 'none'; return; }
        const filtered = clients.filter(c => c.name.toLowerCase().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 addUmrahOption() {
        const container = document.getElementById('umrah-options-container');
        const template = document.getElementById('umrah-option-template').content.cloneNode(true);
        const div = template.querySelector('.umrah-option');
        div.innerHTML = div.innerHTML.replace(/__OPTION_INDEX__/g, optionIndex);
        container.appendChild(div);
        addItineraryLeg(container.lastElementChild.querySelector('button[onclick="addItineraryLeg(this)"]'));
        optionIndex++;
    }
    function addItineraryLeg(btn) {
        const optDiv = btn.closest('.umrah-option');
        const optIdx = optDiv.querySelector('[name*="options["]').name.match(/\[(\d+)\]/)[1];
        const container = optDiv.querySelector('.itinerary-container');
        const template = document.getElementById('itinerary-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;
        container.appendChild(temp.firstElementChild);
    }
    addUmrahOption();
</script>
</body>
</html>