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

$agency_id = $_SESSION['agency_id'];

// 1. Check Usage Limit for the month
$usage = $conn->query("SELECT posters_generated, max_posters FROM agencies WHERE id = $agency_id")->fetch_assoc();
if($usage['posters_generated'] >= $usage['max_posters']) {
    die("<div style='text-align:center; padding:50px; font-family:sans-serif;'>
            <h2 style='color:#e74a3b;'>Monthly Limit Reached</h2>
            <p>You have used your limit of {$usage['max_posters']} posters this month.</p>
            <a href='posters.php' style='color:#4e73df; font-weight:bold;'>Go Back</a>
         </div>");
}

// 2. Fetch Airlines for the dropdowns
$airlines_res = $conn->query("SELECT * FROM airlines ORDER BY name ASC");
$airline_list = [];
while($a = $airlines_res->fetch_assoc()){ $airline_list[] = $a; }

// 3. GENERATION ENGINE (When Generate button is clicked)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['blocks'])) {
    ob_start();
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&family=Gulzar&display=swap" rel="stylesheet">
        <style>
    :root { 
        --primary: #0f172a; 
        --accent: #2563eb; 
        --success: #059669;
        --text-dark: #1e293b; 
        --text-light: #64748b; 
    }
    
    body { font-family: 'Inter', sans-serif; margin: 0; padding: 0; background: #f1f5f9; color: var(--text-dark); }
    .poster { width: 1080px; margin: auto; background: #fff; position: relative; overflow: hidden;}

    /* Top Branding Bar */
    .top-branding { 
        background: var(--primary); 
        padding: 8px 40px; 
        display: flex; 
        justify-content: space-between; 
        color: rgba(255,255,255,0.9);
        font-size: 11px;
        letter-spacing: 1.5px;
        font-weight: 600;
    }

    /* Enhanced Header - Larger Logo & Split Contact */
    .header { 
        display: flex; 
        justify-content: space-between; 
        align-items: center; 
        padding: 30px 40px;
        background: linear-gradient(to bottom, #ffffff, #f8fafc);
        border-bottom: 1px solid #f1f5f9;
    }
    .header img { height: 85px; width: auto; }
    .agency-contact { text-align: right; }
    .agency-contact h2 { margin: 0 0 5px 0; font-size: 26px; color: var(--primary); font-weight: 800; }
    .agency-contact p { margin: 2px 0; font-size: 14px; color: var(--text-light); line-height: 1.4; font-weight: 500; }
    
    .update-badge {
        background: #e0e7ff;
        color: #4338ca;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 700;
        display: inline-block;
        margin-top: 8px;
    }

    /* Requested Urdu Styling: 42px and Red */
    .urdu-wrap { text-align: center; padding: 15px 40px 20px; }
    .urdu-text { font-family: 'Gulzar', serif; font-size: 42px; color: #ef4444; margin: 0; }

    /* Compact Return Sector Card */
    .sector-card { 
        margin: 0 30px 25px; 
        border-radius: 20px; 
        background: #fff; 
        border: 1px solid #e2e8f0;
        box-shadow: 0 10px 25px rgba(0,0,0,0.03);
        overflow: hidden;
    }
    
    .sector-header { 
        background: #f8fafc; 
        padding: 15px 25px; 
        display: flex; 
        justify-content: space-between; 
        align-items: center; 
        border-bottom: 1px solid #f1f5f9;
    }
    .route-info { display: flex; align-items: center; gap: 12px; font-size: 20px; font-weight: 800; color: var(--primary); }
    .airline-info { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 14px; color: var(--text-light); }
    .airline-info img { height: 24px; }

    /* Fares Table */
    .fares-table { width: 100%; border-collapse: collapse; }
    .fares-table th { background: #f8fafc; padding: 12px 20px; text-align: left; font-size: 10px; text-transform: uppercase; color: var(--text-light); border-bottom: 1px solid #f1f5f9; }
    .fares-table td { padding: 15px 20px; border-bottom: 1px solid #f8fafc; vertical-align: middle; }
    .fares-table tr:last-child td { border-bottom: none; }
    
    .leg-box { line-height: 1.4; }
    .leg-label { display: block; font-size: 9px; font-weight: 800; color: var(--accent); text-transform: uppercase; margin-bottom: 2px; }
    .leg-val { font-size: 14px; font-weight: 600; color: #334155; }
    .leg-val span { color: #94a3b8; font-weight: 400; font-size: 12px; margin-left: 5px; }

    /* Price Highlight Box */
    .price-box { 
        background: #ecfdf5; 
        border: 1px solid #a7f3d0;
        padding: 8px 15px; 
        border-radius: 12px; 
        text-align: center;
        min-width: 140px;
    }
    .price-box small { display: block; font-size: 9px; color: #065f46; font-weight: 800; margin-bottom: 2px; }
    .price-box b { font-size: 18px; color: #047857; }

    .poster-footer { text-align: center; padding: 25px; font-size: 13px; color: #94a3b8; border-top: 1px solid #f1f5f9; background: #fafafa; }
</style>

<div class="poster" id="poster-content">
    <div class="top-branding">
        <span>EXCLUSIVE RETURN GROUP FARES</span>
        <span><?php echo strtoupper(AGENCY_NAME_LIVE); ?> </span>
    </div>

    <div class="header">
        <img src="<?php echo AGENCY_LOGO_LIVE; ?>">
        <div class="agency-contact">
            <h2><?php echo AGENCY_NAME_LIVE; ?></h2>
            <p><i class="fas fa-phone-alt"></i> <?php echo AGENCY_PHONE_LIVE; ?></p>
            <p><i class="fas fa-map-marker-alt"></i> <?php echo AGENCY_ADDRESS_LIVE; ?></p>
            <div class="update-badge">RETURN FARES UPDATED: <?php echo strtoupper($_POST['applicable_date']); ?></div>
        </div>
    </div>
    
    <div class="urdu-wrap">
        <h1 class="urdu-text"><?php echo $_POST['urdu_text']; ?></h1>
    </div>

    <?php foreach ($_POST['blocks'] as $block): 
        $al_logo = ''; $al_name = '';
        foreach($airline_list as $al) { if($al['id'] == $block['airline_id']) { $al_logo = $al['logo_path']; $al_name = $al['name']; } }
    ?>
    <div class="sector-card">
        <div class="sector-header">
            <div class="route-info">
                <?php echo strtoupper($block['from']); ?> 
                <span style="color:var(--accent); font-size: 16px;">✈</span>  
                <?php echo strtoupper($block['to']); ?>
                <span style="color:var(--accent); font-size: 16px;">✈</span>
                <?php echo strtoupper($block['from']); ?>  
            </div>
            <div class="airline-info">
                <img src="<?php echo $al_logo; ?>">
                <?php echo strtoupper($al_name); ?>
            </div>
        </div>
        
        <table class="fares-table">
            <thead>
                <tr>
                    <th>Departure (Going)</th>
                    <th>Return (Back)</th>
                    <th style="text-align:center">Baggage</th>
                    <th style="text-align:right">Total Return Fare</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($block['fares'] as $fare): ?>
                <tr>
                    <td>
                        <div class="leg-box">
                            <span class="leg-label">Outbound</span>
                            <div class="leg-val"><?php echo $fare['out_flt']; ?> <span>|<span style= "font-weight: 650; font-size: 14px; color: #30363f;"><?php echo $fare['out_date']; ?> </span> | <?php echo $fare['out_time']; ?></span></div>
                        </div>
                    </td>
                    <td>
                        <div class="leg-box">
                            <span class="leg-label" style="color:var(--success)">Inbound</span>
                            <div class="leg-val"><?php echo $fare['in_flt']; ?> <span>|<span style= "font-weight: 650; font-size: 14px; color: #30363f;"><?php echo $fare['in_date']; ?> </span> | <?php echo $fare['in_time']; ?></span></div>
                        </div>
                    </td>
                    <td style="text-align:center">
                        <div class="leg-val" style="color:var(--accent); font-size: 13px;"><?php echo $fare['baggage']; ?></div>
                    </td>
                    <td style="text-align:right">
                        <div class="price-box">
                            <small>NET PKR</small>
                            <b><?php echo $fare['price']; ?></b>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endforeach; ?>
    
    <div class="poster-footer">
        *Fares are subject to seat availability. Terms & Conditions apply. Book now with <?php echo AGENCY_NAME_LIVE; ?>.
    </div>
</div>
    </body></html>
    <?php
    $final_html = ob_get_clean();
    file_put_contents('generated_posters/poster_'.$agency_id.'.html', $final_html);
    
    // Auto-count usage
    $conn->query("UPDATE agencies SET posters_generated = posters_generated + 1 WHERE id = $agency_id");

    header("Location: poster_viewer.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Return Poster Studio | Travel SaaS</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #4e73df; --success: #1cc88a; --danger: #ef4444; --bg: #f8f9fc; }
        body { font-family: 'Poppins', sans-serif; background-color: var(--bg); padding: 40px; }
        .container { max-width: 1050px; margin: auto; }
        .card { background: white; padding: 30px; border-radius: 20px; box-shadow: 0 5px 25px rgba(0,0,0,0.05); }
        .block-box { border: 2px solid #e2e8f0; padding: 25px; border-radius: 15px; margin-bottom: 25px; background: #fcfdfd; }
        .fare-box { background: #fff; border: 1.5px solid #e2e8f0; padding: 20px; border-radius: 12px; margin-top: 15px; position: relative; }
        
        label { display: block; font-size: 10px; font-weight: 700; color: #64748b; margin-bottom: 4px; text-transform: uppercase; }
        input, select { padding: 12px; border: 1px solid #e2e8f0; border-radius: 10px; width: 100%; margin-bottom: 10px; font-size: 13px; outline: none; }
        
        .btn { padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; color: white; display: inline-flex; align-items: center; gap: 8px; transition: 0.3s; }
        .btn-add { background: var(--primary); }
        .btn-dup { background: #6c757d; font-size: 11px; padding: 6px 12px; }
        .btn-del { background: var(--danger); padding: 6px 12px; }
        .btn-gen { background: var(--success); width: 100%; padding: 18px; font-size: 18px; margin-top: 20px; box-shadow: 0 10px 20px rgba(28, 200, 138, 0.2); }
        
        .top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .compact-row { display: grid; grid-template-columns: 0.5fr 1fr 1fr 1fr; gap: 10px; align-items: center; margin-bottom: 10px; }
        .row-label { font-size: 12px; font-weight: 800; color: var(--primary); letter-spacing: 0.5px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="top-bar">
            <div>
                <a href="posters.php" style="text-decoration:none; color:#64748b; font-size:14px;"><i class="fas fa-arrow-left"></i> Back to Studio</a>
                <h1 style="margin-top:10px;"><i class="fas fa-exchange-alt"></i> Return Fare Studio</h1>
            </div>
            <a href="manage_airlines.php" class="btn" style="background:#1e293b;"><i class="fas fa-plus"></i> Manage Airlines</a>
        </div>

        <div class="card">
            <form method="POST">
                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px; margin-bottom: 25px;">
                    <div><label>Poster Fare Date</label><input type="text" name="applicable_date" placeholder="e.g. 15 Jan 2026" required></div>
                    <div><label>Urdu Heading</label><input type="text" name="urdu_text" placeholder="خوشخبری" style="direction:rtl; text-align:right;"></div>
                </div>

                <div id="blocks-container"></div>
                
                <button type="button" class="btn btn-add" onclick="addBlock()"><i class="fas fa-plus-circle"></i> Add New Sector Block</button>
                <button type="submit" class="btn btn-gen">Generate Premium Return Poster</button>
            </form>
        </div>
    </div>

    <!-- TEMPLATE: SECTOR BLOCK -->
    <template id="block-tpl">
        <div class="block-box">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:10px;">
                <b style="color:var(--primary);">SECTOR CONFIGURATION</b>
                <div style="display:flex; gap:10px;">
                    <button type="button" class="btn btn-dup" onclick="duplicateBlock(this)"><i class="fas fa-copy"></i> Duplicate Block</button>
                    <button type="button" class="btn btn-del" onclick="this.closest('.block-box').remove()">X</button>
                </div>
            </div>
            <div style="display:grid; grid-template-columns: 1.5fr 1fr 1fr; gap:15px;">
                <div><label>Airline</label><select name="blocks[__B__][airline_id]"><?php foreach($airline_list as $al) echo "<option value='{$al['id']}'>{$al['name']}</option>"; ?></select></div>
                <div><label>Departure From</label><input type="text" name="blocks[__B__][from]" placeholder="LHE"></div>
                <div><label>Arrival To</label><input type="text" name="blocks[__B__][to]" placeholder="JED"></div>
            </div>
            <div class="fares-area"></div>
            <button type="button" class="btn btn-add" style="background:#6c757d; font-size:11px; margin-top:15px;" onclick="addFare(this)">+ Add Fare Option</button>
        </div>
    </template>

    <!-- TEMPLATE: FARE ROW -->
    <template id="fare-tpl">
        <div class="fare-box">
            <div style="display:flex; justify-content:space-between; margin-bottom:15px;">
                <span style="font-size:11px; font-weight:700; color:#94a3b8;">FARE OPTION #<span class="f-num"></span></span>
                <div style="display:flex; gap:8px;">
                    <button type="button" class="btn btn-dup" onclick="duplicateFare(this)"><i class="fas fa-copy"></i> Duplicate Ticket</button>
                    <button type="button" class="btn btn-del" onclick="this.closest('.fare-box').remove()">X</button>
                </div>
            </div>
            
            <div class="compact-row">
                <span class="row-label">GOING:</span>
                <div><label>Flight#</label><input type="text" name="blocks[__B__][fares][__F__][out_flt]" placeholder="PA-470"></div>
                <div><label>Date</label><input type="text" name="blocks[__B__][fares][__F__][out_date]" placeholder="12 Jan"></div>
                <div><label>Time</label><input type="text" name="blocks[__B__][fares][__F__][out_time]" placeholder="14:00"></div>
            </div>

            <div class="compact-row">
                <span class="row-label" style="color:var(--success)">BACK:</span>
                <div><label>Flight#</label><input type="text" name="blocks[__B__][fares][__F__][in_flt]" placeholder="PA-471"></div>
                <div><label>Date</label><input type="text" name="blocks[__B__][fares][__F__][in_date]" placeholder="25 Jan"></div>
                <div><label>Time</label><input type="text" name="blocks[__B__][fares][__F__][in_time]" placeholder="18:30"></div>
            </div>

            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:15px; margin-top:15px; border-top:1px solid #f1f5f9; padding-top:10px;">
                <div><label>Baggage</label><input type="text" name="blocks[__B__][fares][__F__][baggage]" placeholder="30KG + 7KG"></div>
                <div><label>Total Price (PKR)</label><input type="text" name="blocks[__B__][fares][__F__][price]" placeholder="145,000"></div>
            </div>
        </div>
    </template>

    <script>
        let bIdx = 0;
        function addBlock(data = null) {
            const container = document.getElementById('blocks-container');
            const html = document.getElementById('block-tpl').innerHTML.replace(/__B__/g, bIdx);
            const div = document.createElement('div'); div.innerHTML = html;
            container.appendChild(div.firstElementChild);
            const currentBlock = container.lastElementChild;
            if(data) {
                currentBlock.querySelector('[name*="[airline_id]"]').value = data.airline_id;
                currentBlock.querySelector('[name*="[from]"]').value = data.from;
                currentBlock.querySelector('[name*="[to]"]').value = data.to;
                if(data.fares) data.fares.forEach(f => addFare(currentBlock.querySelector('button'), f));
            } else { addFare(currentBlock.querySelector('button[onclick="addFare(this)"]')); }
            bIdx++;
        }
        function addFare(btn, data = null) {
            const block = btn.closest('.block-box');
            const blockIdx = block.querySelector('[name*="blocks["]').name.match(/\[(\d+)\]/)[1];
            const area = block.querySelector('.fares-area');
            const fIdx = area.children.length;
            const html = document.getElementById('fare-tpl').innerHTML.replace(/__B__/g, blockIdx).replace(/__F__/g, fIdx);
            const div = document.createElement('div'); div.innerHTML = html;
            area.appendChild(div.firstElementChild);
            const row = area.lastElementChild;
            row.querySelector('.f-num').textContent = fIdx + 1;
            if(data) {
                row.querySelector('[name*="[out_flt]"]').value = data.out_flt; row.querySelector('[name*="[out_date]"]').value = data.out_date; row.querySelector('[name*="[out_time]"]').value = data.out_time;
                row.querySelector('[name*="[in_flt]"]').value = data.in_flt; row.querySelector('[name*="[in_date]"]').value = data.in_date; row.querySelector('[name*="[in_time]"]').value = data.in_time;
                row.querySelector('[name*="[baggage]"]').value = data.baggage; row.querySelector('[name*="[price]"]').value = data.price;
            }
        }
        function duplicateBlock(btn) {
            const block = btn.closest('.block-box');
            const data = { airline_id: block.querySelector('[name*="[airline_id]"]').value, from: block.querySelector('[name*="[from]"]').value, to: block.querySelector('[name*="[to]"]').value, fares: [] };
            block.querySelectorAll('.fare-box').forEach(row => {
                data.fares.push({
                    out_flt: row.querySelector('[name*="[out_flt]"]').value, out_date: row.querySelector('[name*="[out_date]"]').value, out_time: row.querySelector('[name*="[out_time]"]').value,
                    in_flt: row.querySelector('[name*="[in_flt]"]').value, in_date: row.querySelector('[name*="[in_date]"]').value, in_time: row.querySelector('[name*="[in_time]"]').value,
                    baggage: row.querySelector('[name*="[baggage]"]').value, price: row.querySelector('[name*="[price]"]').value
                });
            });
            addBlock(data);
        }
        function duplicateFare(btn) {
            const row = btn.closest('.fare-box');
            const data = { 
                out_flt: row.querySelector('[name*="[out_flt]"]').value, out_date: row.querySelector('[name*="[out_date]"]').value, out_time: row.querySelector('[name*="[out_time]"]').value,
                in_flt: row.querySelector('[name*="[in_flt]"]').value, in_date: row.querySelector('[name*="[in_date]"]').value, in_time: row.querySelector('[name*="[in_time]"]').value,
                baggage: row.querySelector('[name*="[baggage]"]').value, price: row.querySelector('[name*="[price]"]').value
            };
            addFare(btn, data);
        }
        window.onload = () => { if(bIdx == 0) addBlock(); };
    </script>
</body></html>