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

$agency_id = $_SESSION['agency_id'];

// 1. Check Usage Limit
$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>Monthly Limit Reached</h2><p>Contact Admin to upgrade.</p></div>");
}

$airlines_res = $conn->query("SELECT * FROM airlines ORDER BY name ASC");
$airline_list = [];
while($a = $airlines_res->fetch_assoc()){ $airline_list[] = $a; }

// 2. NEW PREMIUM GENERATION ENGINE
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;700;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 { 
        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 for Larger Logo */
    .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; } /* Increased Logo Size */
    .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; } /* Multi-line Contact */
    
    .update-badge {
        background: #e0e7ff;
        color: #4338ca;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 700;
        display: inline-block;
        margin-top: 8px;
    }

    .urdu-wrap { text-align: center; padding: 15px 40px 25px; }
    .urdu-text { font-family: 'Gulzar', serif; font-size: 42px; color: #eb2727; margin: 0; }

    .ticket-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);
    }
    
    .ticket-header { 
        background: #f8fafc; 
        padding: 15px 25px; 
        display: flex; 
        justify-content: space-between; 
        align-items: center; 
        border-bottom: 1px solid #f1f5f9;
        border-radius: 20px 20px 0 0;
    }
    .route-info { display: flex; align-items: center; gap: 12px; font-size: 22px; 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; }

    /* Column Grid: Now Split into 5 distinct columns for clarity */
    .fare-row { 
        display: grid; 
        grid-template-columns: 0.8fr 1fr 1fr 0.8fr 1.2fr; 
        align-items: center; 
        padding: 15px 25px; 
        border-bottom: 1px solid #f8fafc;
    }
    .fare-row:nth-child(even) { background: #fafcfe; }
    .fare-row:last-child { border-bottom: none; border-radius: 0 0 20px 20px; }
    
    .col-label { font-size: 10px; font-weight: 700; color: var(--text-light); text-transform: uppercase; margin-bottom: 3px; letter-spacing: 0.5px; }
    .col-val { font-size: 15px; font-weight: 600; color: #334155; }
    
    .price-col { text-align: right; }
    .price-box { 
        background: #ecfdf5; 
        border: 1px solid #a7f3d0;
        padding: 8px 18px; 
        border-radius: 12px; 
        display: inline-block;
    }
    .price-box small { display: block; font-size: 9px; color: #065f46; font-weight: 800; margin-bottom: 2px; }
    .price-box b { font-size: 20px; color: #047857; }

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

<div class="poster" id="poster-content">
    <div class="top-branding">
        <span>OFFICIAL GROUP FARES</span>
        <span><?php echo strtoupper(AGENCY_NAME_LIVE); ?> TRAVEL NETWORK</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">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="ticket-card">
        <div class="ticket-header">
            <div class="route-info">
                <?php echo strtoupper($block['from']); ?> 
                <span style="color:var(--accent); font-size: 16px;">✈</span> 
                <?php echo strtoupper($block['to']); ?>
            </div>
            <div class="airline-info">
                <img src="<?php echo $al_logo; ?>">
                <?php echo strtoupper($al_name); ?>
            </div>
        </div>
        
        <div class="fares-body">
            <?php foreach($block['fares'] as $fare): ?>
            <div class="fare-row">
                <div class="col">
                    <div class="col-label">Flight</div>
                    <div class="col-val"><?php echo strtoupper($fare['flight_code']); ?></div>
                </div>
                <div class="col">
                    <div class="col-label">Travel Date</div>
                    <div class="col-val"><?php echo $fare['date']; ?></div>
                </div>
                <div class="col">
                    <div class="col-label">Time</div>
                    <div class="col-val"><?php echo $fare['timing']; ?></div>
                </div>
                <div class="col">
                    <div class="col-label">Baggage</div>
                    <div class="col-val" style="color:var(--accent)"><?php echo $fare['baggage']; ?></div>
                </div>
                <div class="price-col">
                    <div class="price-box">
                        <small>TOTAL PRICE</small>
                        <b>Rs. <?php echo $fare['price']; ?></b>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>
    
    <div class="footer">
        *Prices are inclusive of taxes. Seats are subject to availability at time of booking.
    </div>
</div>
    </body></html>
    <?php
    $final_html = ob_get_clean();
    file_put_contents('generated_posters/poster_'.$agency_id.'.html', $final_html);
    $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>Poster Studio | One-Way</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; --bg: #f8f9fc; }
        body { font-family: 'Poppins', sans-serif; background: var(--bg); padding: 40px; }
        .container { max-width: 950px; margin: auto; }
        .card { background: white; padding: 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
        .block-box { border: 2px solid #e2e8f0; padding: 25px; border-radius: 15px; margin-bottom: 25px; background: #fcfdfd; }
        input, select { padding: 12px; border: 1px solid #ddd; border-radius: 10px; width: 100%; margin-bottom: 15px; font-size: 14px; 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; }
        .btn-add { background: var(--primary); }
        .btn-dup { background: #6c757d; font-size: 11px; }
        .btn-del { background: #ff7675; }
        .btn-gen { background: #1cc88a; width: 100%; padding: 18px; font-size: 18px; margin-top: 20px; }
        .fare-row { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr 1fr 40px 30px; gap: 10px; align-items: end; margin-top: 10px; border-top: 1px dashed #eee; padding-top: 10px; }
    </style>
</head>
<body>
    <div class="container">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:30px;">
            <h1>Poster Designer</h1>
            <a href="manage_airlines.php" class="btn" style="background:#1e293b;"><i class="fas fa-plus"></i> Add Airlines</a>
        </div>

        <div class="card">
            <form method="POST">
                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px;">
                    <div><label>Date Label</label><input type="text" name="applicable_date" placeholder="e.g. 15 Jan" required></div>
                    <div><label>Urdu Message</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"></i> Add Airline Block</button>
                <button type="submit" class="btn btn-gen">Create Premium Poster View</button>
            </form>
        </div>
    </div>

    <!-- JS TEMPLATES -->
    <template id="block-tpl">
        <div class="block-box">
            <div style="display:flex; justify-content:space-between; margin-bottom:15px;">
                <b>SECTOR CONFIG</b>
                <div style="display:flex; gap:10px;">
                    <button type="button" class="btn btn-dup" onclick="duplicateBlock(this)">Duplicate</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;">
                <select name="blocks[__B__][airline_id]"><?php foreach($airline_list as $al) echo "<option value='{$al['id']}'>{$al['name']}</option>"; ?></select>
                <input type="text" name="blocks[__B__][from]" placeholder="From">
                <input type="text" name="blocks[__B__][to]" placeholder="To">
            </div>
            <div class="fares-area"></div>
            <button type="button" class="btn btn-add" style="background:#64748b; font-size:11px; margin-top:10px;" onclick="addFare(this)">+ Add Fare</button>
        </div>
    </template>

    <template id="fare-tpl">
        <div class="fare-row">
            <input type="text" name="blocks[__B__][fares][__F__][flight_code]" placeholder="PA-470">
            <input type="text" name="blocks[__B__][fares][__F__][date]" placeholder="12 Jan">
            <input type="text" name="blocks[__B__][fares][__F__][timing]" placeholder="14:00">
            <input type="text" name="blocks[__B__][fares][__F__][baggage]" placeholder="30KG">
            <input type="text" name="blocks[__B__][fares][__F__][price]" placeholder="Price">
            <button type="button" class="btn btn-dup" onclick="duplicateFare(this)"><i class="fas fa-copy"></i></button>
            <button type="button" class="btn btn-del" onclick="this.parentElement.remove()">X</button>
        </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 block = container.lastElementChild;
            if(data) {
                block.querySelector('[name*="[airline_id]"]').value = data.airline_id;
                block.querySelector('[name*="[from]"]').value = data.from;
                block.querySelector('[name*="[to]"]').value = data.to;
                data.fares.forEach(f => addFare(block.querySelector('button'), f));
            } else { addFare(block.querySelector('button[onclick="addFare(this)"]')); }
            bIdx++;
        }
        function addFare(btn, data = null) {
            const block = btn.closest('.block-box');
            const bIdx = 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, bIdx).replace(/__F__/g, fIdx);
            const div = document.createElement('div'); div.innerHTML = html;
            area.appendChild(div.firstElementChild);
            if(data) {
                const row = area.lastElementChild;
                row.querySelector('[name*="[flight_code]"]').value = data.flight_code;
                row.querySelector('[name*="[date]"]').value = data.date;
                row.querySelector('[name*="[timing]"]').value = data.timing;
                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-row').forEach(row => {
                data.fares.push({ flight_code: row.querySelector('[name*="[flight_code]"]').value, date: row.querySelector('[name*="[date]"]').value, timing: row.querySelector('[name*="[timing]"]').value, baggage: row.querySelector('[name*="[baggage]"]').value, price: row.querySelector('[name*="[price]"]').value });
            });
            addBlock(data);
        }
        function duplicateFare(btn) {
            const row = btn.closest('.fare-row');
            const data = { flight_code: row.querySelector('[name*="[flight_code]"]').value, date: row.querySelector('[name*="[date]"]').value, timing: row.querySelector('[name*="[timing]"]').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>