<?php include 'header.php'; ?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Add Ad</title>

    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/remixicon/fonts/remixicon.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/tom-select/dist/css/tom-select.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/tom-select/dist/js/tom-select.complete.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>tailwind.config = { theme: { extend: {} } }</script>

    <style>
        /* ── Tom Select ── */
        .ts-wrapper{width:100%;position:relative;}
        .ts-control{min-height:56px !important;height:56px !important;border:1px solid #d1d5db !important;border-radius:16px !important;padding:0 16px !important;background:#fff !important;box-shadow:none !important;display:flex !important;align-items:center !important;overflow:hidden !important;}
        .ts-control input{font-size:14px !important;}
        .ts-wrapper.focus .ts-control{border-color:#2563eb !important;box-shadow:0 0 0 4px rgba(37,99,235,0.10) !important;}
        .ts-dropdown{margin-top:8px !important;border-radius:16px !important;border:1px solid #e5e7eb !important;overflow:hidden !important;background:#fff !important;box-shadow:0 10px 30px rgba(0,0,0,0.10) !important;z-index:9999 !important;}
        .ts-dropdown-content{max-height:220px !important;overflow-y:auto !important;overflow-x:hidden !important;}
        .ts-dropdown .option{padding:14px 16px !important;font-size:14px !important;cursor:pointer;}
        .ts-dropdown .active{background:#eff6ff !important;color:#1d4ed8 !important;}

        /* ── Floating Input ── */
        .fi{position:relative;}
        .fi input,.fi textarea{width:100%;height:56px;border:1px solid #d1d5db;border-radius:16px;padding:0 16px;outline:none;font-size:15px;background:#fff;transition:0.25s;}
        .fi textarea{height:100px;resize:none;padding-top:16px;}
        .fi input:focus,.fi textarea:focus{border-color:#2563eb;box-shadow:0 0 0 4px rgba(37,99,235,0.10);}
        .fi label{position:absolute;left:14px;top:50%;transform:translateY(-50%);background:#fff;padding:0 6px;font-size:14px;color:#6b7280;pointer-events:none;transition:0.2s;z-index:2;}
        .fi textarea+label{top:22px;transform:none;}
        .fi input:focus+label,.fi input:not(:placeholder-shown)+label{top:0;transform:translateY(-50%);font-size:11px;color:#2563eb;}
        .fi textarea:focus+label,.fi textarea:not(:placeholder-shown)+label{top:-8px;transform:none;font-size:11px;color:#2563eb;}

        /* ── Select Input ── */
        .si{position:relative;}
        .si select{width:100%;height:56px;border:1px solid #d1d5db;border-radius:16px;padding:0 42px 0 16px;outline:none;font-size:15px;background:#fff;appearance:none;transition:0.25s;}
        .si select:focus{border-color:#2563eb;box-shadow:0 0 0 4px rgba(37,99,235,0.10);}
        .si::after{content:'\ea4e';font-family:'remixicon';position:absolute;right:16px;top:50%;transform:translateY(-50%);color:#6b7280;pointer-events:none;}

        /* ── Steps ── */
        .form-step{display:none;}
        .form-step.active{display:block;}

        /* ── Budget Toggle ── */
        .switch-track{width:52px;height:28px;border-radius:999px;background:#d1d5db;position:relative;cursor:pointer;transition:background 0.25s;flex-shrink:0;}
        .switch-track.on{background:#2563eb;}
        .switch-thumb{width:22px;height:22px;border-radius:50%;background:#fff;position:absolute;top:3px;left:3px;transition:left 0.25s;box-shadow:0 1px 4px rgba(0,0,0,0.18);}
        .switch-track.on .switch-thumb{left:27px;}

        /* ── Platform Cards ── */
        .platform-card{border:2px solid #e5e7eb;border-radius:16px;padding:14px 16px;cursor:pointer;transition:all 0.2s;display:flex;align-items:center;gap:12px;background:#fff;}
        .platform-card:hover{border-color:#93c5fd;background:#eff6ff;}
        .platform-card.selected{border-color:#2563eb;background:#eff6ff;}
        .platform-card input[type="checkbox"]{width:18px;height:18px;accent-color:#2563eb;cursor:pointer;flex-shrink:0;}

        /* ── Creative Upload ── */
        .upload-zone{border:2px dashed #d1d5db;border-radius:16px;padding:32px 20px;text-align:center;cursor:pointer;transition:all 0.2s;background:#fafafa;}
        .upload-zone:hover{border-color:#2563eb;background:#eff6ff;}
        .upload-zone.has-file{border-color:#2563eb;border-style:solid;background:#eff6ff;}

        /* ── Review ── */
        .review-section{border-radius:14px;border:1px solid #e5e7eb;overflow:hidden;margin-bottom:12px;}
        .review-section-header{padding:10px 16px;background:#f8fafc;border-bottom:1px solid #e5e7eb;font-size:12px;font-weight:700;color:#2563eb;text-transform:uppercase;letter-spacing:0.05em;}

        /* SweetAlert custom */
        .swal-custom-popup{border-radius:24px !important;padding:2rem 2rem 1.5rem !important;}
        .swal-custom-confirm{border-radius:12px !important;padding:0.6rem 2rem !important;font-weight:600 !important;}
    </style>
</head>

<body class="bg-gray-100 min-h-screen">

    <!-- PAGE HEADER -->
    <div class="max-w-7xl mx-auto px-2 sm:px-4 lg:px-8 pt-6 sm:pt-8 pb-5 sm:pb-6">
        <div class="flex items-start justify-between">
            <h1 class="text-3xl font-bold text-gray-900">Create Ad</h1>
            <a href="ads_management.php"
               class="inline-flex items-center gap-2 h-11 px-5 rounded-xl border border-gray-200 bg-white hover:bg-gray-50 text-gray-700 text-sm font-semibold transition-all shadow-sm">
                <i class="ri-arrow-left-line"></i> Back
            </a>
        </div>
    </div>

    <!-- MAIN CARD -->
    <div class="max-w-7xl mx-auto px-2 sm:px-4 lg:px-8 pb-6 sm:pb-10">
        <div class="w-full bg-white rounded-2xl sm:rounded-3xl shadow-xl border border-gray-100 p-3 sm:p-6 md:p-8 lg:p-12 overflow-visible">
            <div class="flex flex-col lg:flex-row gap-6 lg:gap-14">

                <!-- ═══ SIDEBAR ═══ -->
                <div class="w-full lg:w-64 xl:w-72 flex-shrink-0">

                    <!-- Mobile Step Indicator -->
                    <div class="flex lg:hidden items-center justify-between mb-6">
                        <span id="mobileLabel" class="text-sm font-semibold text-gray-800">Step 1 of 5 — Campaign Basics</span>
                        <div class="flex gap-1.5">
                            <div id="mdot0" class="w-2.5 h-2.5 rounded-full bg-blue-600"></div>
                            <div id="mdot1" class="w-2.5 h-2.5 rounded-full bg-blue-200"></div>
                            <div id="mdot2" class="w-2.5 h-2.5 rounded-full bg-blue-200"></div>
                            <div id="mdot3" class="w-2.5 h-2.5 rounded-full bg-blue-200"></div>
                            <div id="mdot4" class="w-2.5 h-2.5 rounded-full bg-blue-200"></div>
                        </div>
                    </div>

                    <!-- Desktop Sidebar -->
                    <div class="hidden lg:flex flex-col gap-0">
                        <?php
                        $steps = [
                            ['01', 'Campaign Basics',   'Name, platform & objective'],
                            ['02', 'Audience',          'Targeting & demographics'],
                            ['03', 'Budget & Schedule', 'Spend, dates & bidding'],
                            ['04', 'Ad Creative',       'Media, copy & CTA'],
                            ['05', 'Review & Launch',   'Confirm all details'],
                        ];
                        foreach ($steps as $i => $s): ?>
                        <div class="flex gap-4 items-start">
                            <div class="flex flex-col items-center">
                                <div id="sd<?= $i ?>"
                                     class="w-7 h-7 rounded-full <?= $i==0 ? 'border-[3px] border-blue-600' : 'border-2 border-blue-200' ?> bg-white flex items-center justify-center transition-all duration-300"></div>
                                <?php if ($i != 4): ?><div class="w-0.5 h-10 bg-blue-200 mt-1"></div><?php endif; ?>
                            </div>
                            <div class="pt-0.5">
                                <div class="text-[11px] font-semibold text-gray-400"><?= $s[0] ?></div>
                                <div id="st<?= $i ?>" class="text-[15px] font-bold <?= $i==0 ? 'text-gray-900' : 'text-gray-400' ?>"><?= $s[1] ?></div>
                                <div class="text-xs text-gray-400"><?= $s[2] ?></div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- ═══ FORM ═══ -->
                <div class="flex-1 min-w-0 lg:border-l lg:border-gray-100 lg:pl-10 xl:pl-12">


                    <!-- ══ STEP 1 : Campaign Basics ══ -->
                    <div class="form-step active" id="fs0">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 1 of 5</p>
                            <h1 class="text-3xl font-bold text-gray-900">Campaign Basics</h1>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <div class="fi sm:col-span-2" id="fi_campaign_name">
                                <input type="text" id="campaign_name" placeholder=" ">
                                <label>Campaign Name *</label>
                            </div>

                            <div class="si">
                                <select id="platform">
                                    <option value="" disabled selected>Ad Platform *</option>
                                    <option>Facebook Ads</option>
                                    <option>Instagram Ads</option>
                                    <option>Google Ads</option>
                                    <option>YouTube Ads</option>
                                    <option>LinkedIn Ads</option>
                                    <option>Twitter / X Ads</option>
                                    <option>Snapchat Ads</option>
                                </select>
                            </div>

                            <div class="si">
                                <select id="campaign_objective">
                                    <option value="" disabled selected>Campaign Objective *</option>
                                    <option>Brand Awareness</option>
                                    <option>Lead Generation</option>
                                    <option>Website Traffic</option>
                                    <option>Conversions</option>
                                    <option>App Installs</option>
                                    <option>Engagement</option>
                                    <option>Video Views</option>
                                    <option>Catalog Sales</option>
                                </select>
                            </div>

                            <div class="si">
                                <select id="ad_type">
                                    <option value="" disabled selected>Ad Type *</option>
                                    <option>Image Ad</option>
                                    <option>Video Ad</option>
                                    <option>Carousel Ad</option>
                                    <option>Stories Ad</option>
                                    <option>Reel Ad</option>
                                    <option>Search Ad</option>
                                    <option>Display Ad</option>
                                    <option>Shopping Ad</option>
                                </select>
                            </div>

                            <div class="si">
                                <select id="campaign_status">
                                    <option value="" disabled selected>Campaign Status *</option>
                                    <option>Running</option>
                                    <option>Paused</option>
                                    <option>Draft</option>
                                    <option>Scheduled</option>
                                </select>
                            </div>

                            <div class="fi sm:col-span-2">
                                <textarea id="campaign_description" placeholder=" "></textarea>
                                <label>Campaign Description</label>
                            </div>

                        </div>
                    </div>


                    <!-- ══ STEP 2 : Audience ══ -->
                    <div class="form-step" id="fs1">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 2 of 5</p>
                            <h1 class="text-3xl font-bold text-gray-900">Audience Targeting</h1>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <div class="fi">
                                <input type="text" id="target_location" placeholder=" ">
                                <label>Target Location</label>
                            </div>

                            <div class="si">
                                <select id="target_language">
                                    <option value="" disabled selected>Target Language</option>
                                    <option>English</option>
                                    <option>Hindi</option>
                                    <option>Gujarati</option>
                                    <option>Marathi</option>
                                    <option>Tamil</option>
                                    <option>Telugu</option>
                                    <option>Bengali</option>
                                    <option>All Languages</option>
                                </select>
                            </div>

                            <div class="si">
                                <select id="gender_target">
                                    <option value="" disabled selected>Gender</option>
                                    <option>All</option>
                                    <option>Male</option>
                                    <option>Female</option>
                                </select>
                            </div>

                            <div class="si">
                                <select id="age_range">
                                    <option value="" disabled selected>Age Range</option>
                                    <option>13–17</option>
                                    <option>18–24</option>
                                    <option>25–34</option>
                                    <option>35–44</option>
                                    <option>45–54</option>
                                    <option>55–64</option>
                                    <option>65+</option>
                                    <option>All Ages</option>
                                </select>
                            </div>

                            <div class="fi">
                                <input type="text" id="interests" placeholder=" ">
                                <label>Interests / Keywords</label>
                            </div>

                            <div class="si">
                                <select id="device_target">
                                    <option value="" disabled selected>Device Type</option>
                                    <option>All Devices</option>
                                    <option>Mobile Only</option>
                                    <option>Desktop Only</option>
                                    <option>Tablet Only</option>
                                </select>
                            </div>

                            <div class="fi">
                                <input type="text" id="custom_audience" placeholder=" ">
                                <label>Custom Audience / Segment</label>
                            </div>

                            <div class="si">
                                <select id="audience_type">
                                    <option value="" disabled selected>Audience Type</option>
                                    <option>Cold Audience</option>
                                    <option>Warm Audience</option>
                                    <option>Retargeting</option>
                                    <option>Lookalike</option>
                                </select>
                            </div>

                        </div>
                    </div>


                    <!-- ══ STEP 3 : Budget & Schedule ══ -->
                    <div class="form-step" id="fs2">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 3 of 5</p>
                            <h1 class="text-3xl font-bold text-gray-900">Budget & Schedule</h1>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <!-- Daily Budget Toggle -->
                            <div class="sm:col-span-2 flex items-center justify-between h-14 px-4 border border-gray-200 rounded-2xl bg-gray-50">
                                <div>
                                    <p class="text-sm font-semibold text-gray-700">Daily Budget Cap</p>
                                    <p class="text-xs text-gray-400">Set a maximum spend per day</p>
                                </div>
                                <div class="switch-track" id="dailyCapSwitch" onclick="toggleDailyCap()">
                                    <div class="switch-thumb"></div>
                                </div>
                            </div>

                            <div class="fi sm:col-span-2" id="dailyCapWrapper" style="display:none;">
                                <input type="number" id="daily_budget_cap" placeholder=" " min="0">
                                <label>Daily Budget Cap (₹)</label>
                            </div>

                            <div class="fi">
                                <input type="number" id="total_budget" placeholder=" " min="0">
                                <label>Total Budget (₹) *</label>
                            </div>

                            <div class="si">
                                <select id="budget_type">
                                    <option value="" disabled selected>Budget Type</option>
                                    <option>Daily Budget</option>
                                    <option>Lifetime Budget</option>
                                </select>
                            </div>

                            <div class="fi">
                                <input type="date" id="start_date" placeholder=" ">
                                <label>Start Date *</label>
                            </div>

                            <div class="fi">
                                <input type="date" id="end_date" placeholder=" ">
                                <label>End Date</label>
                            </div>

                            <div class="si">
                                <select id="bid_strategy">
                                    <option value="" disabled selected>Bid Strategy</option>
                                    <option>Lowest Cost</option>
                                    <option>Cost Cap</option>
                                    <option>Bid Cap</option>
                                    <option>Target ROAS</option>
                                    <option>Manual CPC</option>
                                    <option>Manual CPM</option>
                                </select>
                            </div>

                            <div class="fi">
                                <input type="number" id="bid_amount" placeholder=" " min="0">
                                <label>Bid Amount (₹)</label>
                            </div>

                            <div class="si">
                                <select id="currency">
                                    <option value="" disabled selected>Currency</option>
                                    <option selected>INR</option>
                                    <option>USD</option>
                                    <option>EUR</option>
                                </select>
                            </div>

                            <div class="fi">
                                <input type="number" id="frequency_cap" placeholder=" " min="0">
                                <label>Frequency Cap (impressions/user)</label>
                            </div>

                        </div>
                    </div>


                    <!-- ══ STEP 4 : Ad Creative ══ -->
                    <div class="form-step" id="fs3">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 4 of 5</p>
                            <h1 class="text-3xl font-bold text-gray-900">Ad Creative</h1>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                            <div class="fi sm:col-span-2">
                                <input type="text" id="ad_headline" placeholder=" " maxlength="100">
                                <label>Ad Headline *</label>
                            </div>

                            <div class="fi sm:col-span-2">
                                <textarea id="ad_primary_text" placeholder=" " maxlength="500"></textarea>
                                <label>Primary Text / Ad Copy *</label>
                            </div>

                            <div class="fi">
                                <input type="text" id="ad_description" placeholder=" " maxlength="200">
                                <label>Ad Description</label>
                            </div>

                            <div class="si">
                                <select id="cta_button">
                                    <option value="" disabled selected>Call to Action Button</option>
                                    <option>Learn More</option>
                                    <option>Shop Now</option>
                                    <option>Sign Up</option>
                                    <option>Get Quote</option>
                                    <option>Contact Us</option>
                                    <option>Download</option>
                                    <option>Book Now</option>
                                    <option>Subscribe</option>
                                    <option>Watch More</option>
                                </select>
                            </div>

                            <div class="fi sm:col-span-2">
                                <input type="url" id="destination_url" placeholder=" ">
                                <label>Destination URL / Landing Page</label>
                            </div>

                            <div class="fi">
                                <input type="text" id="display_url" placeholder=" ">
                                <label>Display URL</label>
                            </div>

                            <div class="si">
                                <select id="ad_format">
                                    <option value="" disabled selected>Ad Format / Placement</option>
                                    <option>Feed</option>
                                    <option>Stories</option>
                                    <option>Reels</option>
                                    <option>In-Stream</option>
                                    <option>Search Results</option>
                                    <option>Display Network</option>
                                </select>
                            </div>

                        </div>

                        <!-- Creative Upload -->
                        <div class="mt-4">
                            <p class="text-sm font-semibold text-gray-700 mb-2">Ad Creative Media</p>
                            <div class="upload-zone" id="creativeDropzone" onclick="document.getElementById('creative_file').click()">
                                <input type="file" id="creative_file" class="hidden" accept="image/*,video/*"
                                       onchange="handleCreativeUpload(this)">
                                <div id="creativePreviewContent">
                                    <i class="ri-image-add-line text-3xl text-gray-400 block mb-2"></i>
                                    <p class="text-sm font-semibold text-gray-600">Click to upload image or video</p>
                                    <p class="text-xs text-gray-400 mt-1">PNG, JPG, GIF, MP4 — max 50MB</p>
                                </div>
                            </div>
                        </div>
                    </div>


                    <!-- ══ STEP 5 : Review & Launch ══ -->
                    <div class="form-step" id="fs4">
                        <div class="mb-8">
                            <p class="text-xs text-gray-400 mb-1">Step 5 of 5</p>
                            <h1 class="text-3xl font-bold text-gray-900">Review & Launch</h1>
                            <p class="text-sm text-gray-500 mt-1.5">Confirm all ad details before launching.</p>
                        </div>
                        <div id="reviewContent"
                             class="rounded-xl border border-gray-100 divide-y divide-gray-100 overflow-y-auto max-h-[55vh] sm:max-h-[500px] pr-1 bg-white">
                        </div>
                    </div>


                    <!-- ══ NAV BUTTONS ══ -->
                    <div id="btnRow"
                         class="flex flex-col-reverse sm:flex-row gap-3 sm:gap-0 items-stretch sm:items-center justify-between mt-8 sm:mt-10 pt-6 border-t border-gray-100">

                        <button id="prevBtn" onclick="goStep(-1)"
                                class="w-full sm:w-auto inline-flex justify-center items-center gap-2 h-12 px-7 rounded-xl border border-gray-200 bg-white text-black text-sm font-semibold opacity-40 cursor-not-allowed transition-all">
                            <i class="ri-arrow-left-line"></i> Previous
                        </button>

                        <button id="nextBtn" onclick="goStep(1)"
                                class="w-full sm:w-auto inline-flex justify-center items-center gap-2 h-12 px-9 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold transition-all shadow-lg shadow-blue-200">
                            Next <i class="ri-arrow-right-line"></i>
                        </button>

                    </div>

                </div><!-- /form -->
            </div>
        </div>
    </div>


    <script>
    /* ═══════════════════════════════════════════════════
       INIT
    ═══════════════════════════════════════════════════ */
    let cur = 0;
    const total = 5;

    const mobileLabels = [
        'Step 1 of 5 — Campaign Basics',
        'Step 2 of 5 — Audience',
        'Step 3 of 5 — Budget & Schedule',
        'Step 4 of 5 — Ad Creative',
        'Step 5 of 5 — Review & Launch',
    ];

    ['#platform','#campaign_objective','#ad_type','#campaign_status',
     '#target_language','#gender_target','#age_range','#device_target',
     '#audience_type','#budget_type','#bid_strategy','#currency',
     '#cta_button','#ad_format'].forEach(id => {
        if (document.querySelector(id)) {
            new TomSelect(id, {
                create: false, allowEmptyOption: true,
                placeholder: 'Search...', closeAfterSelect: true
            });
        }
    });

    /* ═══════════════════════════════════════════════════
       DAILY CAP TOGGLE
    ═══════════════════════════════════════════════════ */
    let dailyCapOn = false;

    function toggleDailyCap() {
        dailyCapOn = !dailyCapOn;
        const track = document.getElementById('dailyCapSwitch');
        const wrap  = document.getElementById('dailyCapWrapper');
        dailyCapOn ? track.classList.add('on') : track.classList.remove('on');
        wrap.style.display = dailyCapOn ? '' : 'none';
        if (!dailyCapOn) document.getElementById('daily_budget_cap').value = '';
    }

    /* ═══════════════════════════════════════════════════
       CREATIVE UPLOAD
    ═══════════════════════════════════════════════════ */
    function handleCreativeUpload(input) {
        const file = input.files[0];
        if (!file) return;
        const zone    = document.getElementById('creativeDropzone');
        const content = document.getElementById('creativePreviewContent');
        zone.classList.add('has-file');
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                content.innerHTML = `
                    <img src="${e.target.result}" class="max-h-48 mx-auto rounded-lg object-contain mb-2" alt="preview">
                    <p class="text-xs font-semibold text-blue-700">${file.name}</p>
                    <button type="button" onclick="clearCreative(event)" class="mt-2 text-xs text-red-500 hover:text-red-700 font-semibold">
                        <i class="ri-delete-bin-line"></i> Remove
                    </button>`;
            };
            reader.readAsDataURL(file);
        } else {
            content.innerHTML = `
                <i class="ri-video-line text-3xl text-blue-500 block mb-2"></i>
                <p class="text-sm font-semibold text-blue-700">${file.name}</p>
                <p class="text-xs text-gray-400 mt-1">${(file.size/1024/1024).toFixed(2)} MB</p>
                <button type="button" onclick="clearCreative(event)" class="mt-2 text-xs text-red-500 hover:text-red-700 font-semibold">
                    <i class="ri-delete-bin-line"></i> Remove
                </button>`;
        }
    }

    function clearCreative(e) {
        e.stopPropagation();
        document.getElementById('creative_file').value = '';
        const zone    = document.getElementById('creativeDropzone');
        const content = document.getElementById('creativePreviewContent');
        zone.classList.remove('has-file');
        content.innerHTML = `
            <i class="ri-image-add-line text-3xl text-gray-400 block mb-2"></i>
            <p class="text-sm font-semibold text-gray-600">Click to upload image or video</p>
            <p class="text-xs text-gray-400 mt-1">PNG, JPG, GIF, MP4 — max 50MB</p>`;
    }

    /* ═══════════════════════════════════════════════════
       REVIEW BUILD
    ═══════════════════════════════════════════════════ */
    function buildReview() {
        const sections = [
            {
                title: 'Campaign Basics',
                rows: [
                    ['Campaign Name',      document.getElementById('campaign_name').value           || '-'],
                    ['Platform',           document.getElementById('platform').value                || '-'],
                    ['Objective',          document.getElementById('campaign_objective').value       || '-'],
                    ['Ad Type',            document.getElementById('ad_type').value                 || '-'],
                    ['Status',             document.getElementById('campaign_status').value         || '-'],
                    ['Description',        document.getElementById('campaign_description').value    || '-'],
                ]
            },
            {
                title: 'Audience Targeting',
                rows: [
                    ['Target Location',    document.getElementById('target_location').value         || '-'],
                    ['Language',           document.getElementById('target_language').value         || '-'],
                    ['Gender',             document.getElementById('gender_target').value           || '-'],
                    ['Age Range',          document.getElementById('age_range').value               || '-'],
                    ['Interests',          document.getElementById('interests').value               || '-'],
                    ['Device',             document.getElementById('device_target').value           || '-'],
                    ['Custom Audience',    document.getElementById('custom_audience').value         || '-'],
                    ['Audience Type',      document.getElementById('audience_type').value           || '-'],
                ]
            },
            {
                title: 'Budget & Schedule',
                rows: [
                    ['Total Budget',       (document.getElementById('total_budget').value ? '₹' + document.getElementById('total_budget').value : '-')],
                    ['Daily Cap',          dailyCapOn ? '₹' + (document.getElementById('daily_budget_cap').value || '-') : 'Not set'],
                    ['Budget Type',        document.getElementById('budget_type').value             || '-'],
                    ['Start Date',         document.getElementById('start_date').value              || '-'],
                    ['End Date',           document.getElementById('end_date').value                || '-'],
                    ['Bid Strategy',       document.getElementById('bid_strategy').value            || '-'],
                    ['Bid Amount',         (document.getElementById('bid_amount').value ? '₹' + document.getElementById('bid_amount').value : '-')],
                    ['Currency',           document.getElementById('currency').value                || '-'],
                    ['Frequency Cap',      document.getElementById('frequency_cap').value           || '-'],
                ]
            },
            {
                title: 'Ad Creative',
                rows: [
                    ['Headline',           document.getElementById('ad_headline').value             || '-'],
                    ['Primary Text',       document.getElementById('ad_primary_text').value         || '-'],
                    ['Description',        document.getElementById('ad_description').value          || '-'],
                    ['CTA Button',         document.getElementById('cta_button').value              || '-'],
                    ['Destination URL',    document.getElementById('destination_url').value         || '-'],
                    ['Display URL',        document.getElementById('display_url').value             || '-'],
                    ['Ad Format',          document.getElementById('ad_format').value               || '-'],
                    ['Media File',         document.getElementById('creative_file').files[0] ? document.getElementById('creative_file').files[0].name : '-'],
                ]
            }
        ];

        document.getElementById('reviewContent').innerHTML = sections.map(section => `
            <div class="review-section">
                <div class="review-section-header">${section.title}</div>
                ${section.rows.map(([k, v]) => `
                <div class="flex flex-col sm:flex-row sm:items-baseline gap-1 sm:gap-4 px-4 sm:px-5 py-3 bg-white hover:bg-gray-50 transition-colors">
                    <span class="text-xs text-gray-500 sm:min-w-[160px] flex-shrink-0 font-semibold">${k}</span>
                    <span class="text-sm text-gray-800 break-all whitespace-pre-wrap flex-1 min-w-0">${v}</span>
                </div>`).join('')}
            </div>`).join('');
    }

    /* ═══════════════════════════════════════════════════
       VALIDATION
    ═══════════════════════════════════════════════════ */
    function validateStep(step) {
        if (step === 0) {
            const name = document.getElementById('campaign_name').value.trim();
            const plat = document.getElementById('platform').value;
            const obj  = document.getElementById('campaign_objective').value;
            const stat = document.getElementById('campaign_status').value;

            if (!name) {
                Swal.fire({ icon:'error', title:'Campaign Name Required',
                    confirmButtonColor:'#2563eb',
                    customClass:{popup:'swal-custom-popup',confirmButton:'swal-custom-confirm'}});
                return false;
            }
            if (!plat) {
                Swal.fire({ icon:'error', title:'Please select an Ad Platform',
                    confirmButtonColor:'#2563eb',
                    customClass:{popup:'swal-custom-popup',confirmButton:'swal-custom-confirm'}});
                return false;
            }
            if (!obj) {
                Swal.fire({ icon:'error', title:'Please select a Campaign Objective',
                    confirmButtonColor:'#2563eb',
                    customClass:{popup:'swal-custom-popup',confirmButton:'swal-custom-confirm'}});
                return false;
            }
            if (!stat) {
                Swal.fire({ icon:'error', title:'Please select a Campaign Status',
                    confirmButtonColor:'#2563eb',
                    customClass:{popup:'swal-custom-popup',confirmButton:'swal-custom-confirm'}});
                return false;
            }
        }

        if (step === 2) {
            const budget = document.getElementById('total_budget').value.trim();
            const start  = document.getElementById('start_date').value;
            if (!budget) {
                Swal.fire({ icon:'error', title:'Total Budget is Required',
                    confirmButtonColor:'#2563eb',
                    customClass:{popup:'swal-custom-popup',confirmButton:'swal-custom-confirm'}});
                return false;
            }
            if (!start) {
                Swal.fire({ icon:'error', title:'Please set a Start Date',
                    confirmButtonColor:'#2563eb',
                    customClass:{popup:'swal-custom-popup',confirmButton:'swal-custom-confirm'}});
                return false;
            }
        }

        if (step === 3) {
            const headline = document.getElementById('ad_headline').value.trim();
            const copy     = document.getElementById('ad_primary_text').value.trim();
            if (!headline) {
                Swal.fire({ icon:'error', title:'Ad Headline is Required',
                    confirmButtonColor:'#2563eb',
                    customClass:{popup:'swal-custom-popup',confirmButton:'swal-custom-confirm'}});
                return false;
            }
            if (!copy) {
                Swal.fire({ icon:'error', title:'Primary Text / Ad Copy is Required',
                    confirmButtonColor:'#2563eb',
                    customClass:{popup:'swal-custom-popup',confirmButton:'swal-custom-confirm'}});
                return false;
            }
        }

        return true;
    }

    /* ═══════════════════════════════════════════════════
       SIDEBAR UPDATE
    ═══════════════════════════════════════════════════ */
    function updateSidebar() {
        for (let i = 0; i < 5; i++) {
            const dot   = document.getElementById('sd' + i);
            const title = document.getElementById('st' + i);
            if (i < cur) {
                dot.className   = 'w-7 h-7 rounded-full bg-blue-600 border-2 border-blue-600 flex items-center justify-center transition-all duration-300';
                dot.innerHTML   = '<i class="ri-check-line text-white text-xs"></i>';
                title.className = 'text-[15px] font-bold text-gray-400';
            } else if (i === cur) {
                dot.className   = 'w-7 h-7 rounded-full border-[3px] border-blue-600 bg-white flex items-center justify-center transition-all duration-300';
                dot.innerHTML   = '';
                title.className = 'text-[15px] font-bold text-gray-900';
            } else {
                dot.className   = 'w-7 h-7 rounded-full border-2 border-blue-200 bg-white flex items-center justify-center transition-all duration-300';
                dot.innerHTML   = '';
                title.className = 'text-[15px] font-bold text-gray-400';
            }
        }

        document.getElementById('mobileLabel').textContent = mobileLabels[Math.min(cur, 4)];

        for (let i = 0; i < 5; i++) {
            document.getElementById('mdot' + i).className =
                i <= cur
                    ? 'w-2.5 h-2.5 rounded-full bg-blue-600'
                    : 'w-2.5 h-2.5 rounded-full bg-blue-200';
        }
    }

    /* ═══════════════════════════════════════════════════
       STEP NAVIGATION
    ═══════════════════════════════════════════════════ */
    function goStep(dir) {

        if (cur === 4 && dir === 1) {
            Swal.fire({
                icon: 'success',
                title: 'Ad Launched!',
                text: 'Your campaign has been saved successfully.',
                confirmButtonText: 'OK',
                confirmButtonColor: '#2563eb',
                customClass: { popup: 'swal-custom-popup', confirmButton: 'swal-custom-confirm' },
                timer: 3000,
                timerProgressBar: true,
                willClose: () => { window.location.href = 'ads_management.php'; }
            }).then(() => { window.location.href = 'ads_management.php'; });
            return;
        }

        if (dir === 1 && !validateStep(cur)) return;

        const nxt = cur + dir;
        if (nxt < 0 || nxt >= total) return;

        document.getElementById('fs' + cur).classList.remove('active');
        cur = nxt;
        if (cur === 4) buildReview();
        document.getElementById('fs' + cur).classList.add('active');
        updateSidebar();

        const pb = document.getElementById('prevBtn');
        const nb = document.getElementById('nextBtn');

        cur === 0
            ? pb.classList.add('opacity-40', 'cursor-not-allowed')
            : pb.classList.remove('opacity-40', 'cursor-not-allowed');

        if (cur === 4) {
            nb.innerHTML = '<i class="ri-rocket-line"></i> Launch Ad';
            nb.classList.remove('bg-blue-600', 'hover:bg-blue-700');
            nb.classList.add('bg-green-600', 'hover:bg-green-700');
        } else {
            nb.innerHTML = 'Next <i class="ri-arrow-right-line"></i>';
            nb.classList.remove('bg-green-600', 'hover:bg-green-700');
            nb.classList.add('bg-blue-600', 'hover:bg-blue-700');
        }

        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    </script>

</body>
</html>

<?php include 'footer.php'; ?>