<?php
require_once __DIR__ . '/../config/bootstrap.php';
$user = Auth::requireLogin();
$pageTitle = 'Add Campaign';
$activeNav = 'add-campaign';
$extraCss  = ['campaigns'];
$showSearch = false;
require __DIR__ . '/../includes/partials/dashboard-head.php';
?>

<div class="page-header">
    <div class="page-header-left">
        <h4>Add Campaign</h4>
        <p>Create a new beta testing campaign for your application</p>
    </div>
    <div class="page-header-actions">
        <button class="btn-dark-custom" id="publishBtn" style="padding:10px 24px">
            <i class="bi bi-rocket-takeoff-fill"></i> Publish Campaign
        </button>
    </div>
</div>

<div class="content-wrapper">
    <form id="addCampaignForm" enctype="multipart/form-data" novalidate>

        <!-- App Details -->
        <div class="campaign-list-card mb-3">
            <div class="card-header-title" style="margin-bottom:20px">Enter App Details</div>
            <div class="row g-3">

                <!-- Icon Upload -->
                <div class="col-md-3">
                    <div class="icon-upload-box" id="iconUploadBox">
                        <input type="file" id="appIconInput" name="app_icon" accept="image/jpeg,image/png,image/webp" style="display:none">
                        <div id="iconUploadPlaceholder">
                            <div class="icon-upload-placeholder"><i class="bi bi-android2"></i></div>
                            <div class="icon-upload-text">Tap to upload app icon<br><small>(PNG, JPG, WEBP up to 2MB)</small></div>
                            <button type="button" class="btn-primary-custom" id="selectIconBtn" style="padding:8px 20px;font-size:13px">Select Icon</button>
                        </div>
                        <img id="appIconPreview" class="icon-upload-preview" alt="App Icon" style="display:none">
                    </div>
                </div>

                <!-- Fields -->
                <div class="col-md-9">
                    <div class="input-group-custom mb-3">
                        <div class="input-icon" style="z-index:5"><i class="bi bi-app"></i></div>
                        <input type="text" id="appName" name="app_name" class="form-control-custom" placeholder="App Name" maxlength="100" required>
                    </div>
                    <div class="input-group-custom mb-3">
                        <div class="input-icon" style="z-index:5"><i class="bi bi-person-badge"></i></div>
                        <input type="text" id="appDeveloper" name="app_developer" class="form-control-custom" placeholder="Developer Name" maxlength="100" required>
                    </div>
                    <div class="input-group-custom mb-3">
                        <div class="input-icon" style="z-index:5"><i class="bi bi-link-45deg"></i></div>
                        <input type="url" id="appLink" name="app_link" class="form-control-custom"
                               placeholder="https://play.google.com/store/apps/details?id=…" required>
                    </div>
                    <div id="pkgPreview" style="font-size:12px;color:var(--text-secondary);display:none">
                        <i class="bi bi-info-circle"></i> Package: <code id="pkgPreviewVal"></code>
                    </div>
                </div>
            </div>
        </div>

        <!-- Description -->
        <div class="campaign-list-card mb-3">
            <div class="card-header-title" style="margin-bottom:12px">Application Description</div>
            <textarea id="appDes" name="app_des" class="form-control-custom"
                      placeholder="Describe your app — what it does, what testers should focus on, any test accounts, etc."
                      rows="5" maxlength="2000" required style="resize:vertical"></textarea>
            <div class="text-end mt-1" style="font-size:11px;color:var(--text-muted)">
                <span id="desCount">0</span>/2000
            </div>
        </div>

        <!-- Package Selection (live from API) -->
        <div class="campaign-list-card">
            <div class="card-header-title" style="margin-bottom:20px">Select Plan</div>
            <div class="row g-3" id="planRow">
                <div class="col-12 text-center text-muted py-4">
                    <div class="spinner-border spinner-border-sm me-2"></div> Loading plans…
                </div>
            </div>
            <input type="hidden" name="plan_name" id="selectedPlan">
        </div>
    </form>
</div>

<style>
.icon-upload-box {
    border: 2px dashed var(--card-border); border-radius: 16px;
    padding: 24px; text-align: center; cursor: pointer;
    transition: all 0.2s ease; background: white; min-height: 240px;
    display: flex; align-items: center; justify-content: center;
}
.icon-upload-box:hover, .icon-upload-box.drag-over { border-color: var(--primary); background: var(--bg-light-green); }
.icon-upload-placeholder {
    width: 64px; height: 64px; border-radius: 16px;
    background: var(--bg-cream); display: flex; align-items: center; justify-content: center;
    margin: 0 auto 12px; font-size: 28px; color: var(--primary);
}
.icon-upload-text { font-size: 13px; color: var(--text-secondary); margin-bottom: 12px; }
.icon-upload-preview { max-width: 100%; max-height: 200px; border-radius: 16px; }
.input-group-custom { position: relative; }
.input-icon {
    position: absolute; left: 16px; top: 50%; transform: translateY(-50%);
    color: var(--primary); font-size: 16px; z-index: 2;
}
.form-control-custom {
    width: 100%; padding: 14px 16px 14px 48px;
    border: 1.5px solid var(--card-border); border-radius: 12px;
    font-size: 14px; background: white;
}
textarea.form-control-custom { padding: 14px 16px; }
.form-control-custom:focus { outline: none; border-color: var(--primary); }

.package-card-select {
    background: white; border: 2px solid var(--card-border);
    border-radius: 18px; padding: 22px; cursor: pointer;
    position: relative; transition: all 0.2s ease; height: 100%;
}
.package-card-select:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,0.08); }
.package-card-select.selected { border-color: var(--primary); box-shadow: 0 4px 16px rgba(27,122,67,0.15); }
.package-card-select.colored { color: white; }
.package-card-name { font-weight: 700; font-size: 16px; margin-bottom: 6px; display: flex; align-items: center; gap: 6px; }
.package-card-price { font-size: 28px; font-weight: 800; margin-bottom: 14px; }
.package-card-feature { display: flex; align-items: center; gap: 8px; font-size: 13px; padding: 4px 0; }
.package-card-feature .feat-check {
    width: 18px; height: 18px; border-radius: 50%;
    background: rgba(27,122,67,0.15); color: var(--primary);
    display: inline-flex; align-items: center; justify-content: center; font-size: 11px;
    flex-shrink: 0;
}
.package-card-select.colored .feat-check { background: rgba(255,255,255,0.25); color: white; }
.package-select-cb {
    position: absolute; top: 16px; right: 16px;
    width: 28px; height: 28px; border-radius: 50%;
    background: white; border: 2px solid var(--card-border);
    display: flex; align-items: center; justify-content: center;
    color: white; opacity: 0; transition: opacity 0.2s;
}
.package-card-select.selected .package-select-cb { opacity: 1; background: var(--primary); border-color: var(--primary); }
</style>

<script>
(function () {
    let plans = [];
    let selectedPlanKey = null;

    function escapeHtml(s) {
        return String(s ?? '').replace(/[&<>"']/g, c =>
            ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
    }

    // ───── Icon upload ─────
    const iconInput = document.getElementById('appIconInput');
    const iconBox = document.getElementById('iconUploadBox');
    const iconPreview = document.getElementById('appIconPreview');
    const iconPlaceholder = document.getElementById('iconUploadPlaceholder');
    const selectBtn = document.getElementById('selectIconBtn');

    function showPreview(file) {
        if (!file || !file.type.startsWith('image/')) return;
        if (file.size > 2 * 1024 * 1024) {
            window.Toast.fire({ icon: 'error', title: 'Image must be under 2MB' });
            return;
        }
        const reader = new FileReader();
        reader.onload = e => {
            iconPreview.src = e.target.result;
            iconPreview.style.display = 'block';
            iconPlaceholder.style.display = 'none';
        };
        reader.readAsDataURL(file);
    }

    iconInput.addEventListener('change', () => showPreview(iconInput.files[0]));
    iconBox.addEventListener('click', e => { if (e.target !== iconInput) iconInput.click(); });
    if (selectBtn) selectBtn.addEventListener('click', e => { e.stopPropagation(); iconInput.click(); });

    ['dragover', 'dragenter'].forEach(ev =>
        iconBox.addEventListener(ev, e => { e.preventDefault(); iconBox.classList.add('drag-over'); }));
    ['dragleave', 'drop'].forEach(ev =>
        iconBox.addEventListener(ev, e => {
            e.preventDefault(); iconBox.classList.remove('drag-over');
            if (ev === 'drop' && e.dataTransfer.files[0]) {
                iconInput.files = e.dataTransfer.files;
                showPreview(iconInput.files[0]);
            }
        }));

    // ───── Live package extraction from URL ─────
    const appLink = document.getElementById('appLink');
    const pkgPrev = document.getElementById('pkgPreview');
    const pkgPrevVal = document.getElementById('pkgPreviewVal');
    appLink.addEventListener('input', () => {
        const m = appLink.value.match(/[?&]id=([a-zA-Z0-9._]+)/);
        if (m) {
            pkgPrevVal.textContent = m[1];
            pkgPrev.style.display = 'block';
        } else {
            pkgPrev.style.display = 'none';
        }
    });

    // ───── Description char counter ─────
    const desEl = document.getElementById('appDes');
    const desCount = document.getElementById('desCount');
    desEl.addEventListener('input', () => { desCount.textContent = desEl.value.length; });

    // ───── Load plans ─────
    function planCard(p) {
        const colored = p.plan_key !== 'silver';
        const features = p.features.map(f =>
            `<div class="package-card-feature">
                <div class="feat-check"><i class="bi bi-check"></i></div> ${escapeHtml(f)}
            </div>`
        ).join('');
        return `
            <div class="col-md-4">
                <div class="package-card-select ${colored ? 'colored' : ''}"
                     data-plan="${escapeHtml(p.plan_name)}"
                     style="${colored ? 'background:' + p.bg_gradient : ''}">
                    <div class="package-card-name">
                        <i class="bi bi-star-fill" style="color:${p.accent_color}"></i>
                        ${escapeHtml(p.plan_name)}
                    </div>
                    <div class="package-card-price">₹${p.price_inr.toFixed(2)}</div>
                    ${features}
                    <div class="package-select-cb"><i class="bi bi-check"></i></div>
                </div>
            </div>`;
    }

    (async function loadPlans() {
        try {
            const resp = await window.api('/api/campaign/plans');
            if (resp.status !== 'success') throw new Error(resp.message);
            plans = resp.data.plans;
            const row = document.getElementById('planRow');
            row.innerHTML = plans.map(planCard).join('');

            // Bind selection
            row.querySelectorAll('.package-card-select').forEach(card => {
                card.addEventListener('click', function () {
                    row.querySelectorAll('.package-card-select').forEach(c => c.classList.remove('selected'));
                    this.classList.add('selected');
                    selectedPlanKey = this.dataset.plan;
                    document.getElementById('selectedPlan').value = selectedPlanKey;
                });
            });

            // Auto-select first (cheapest)
            const first = row.querySelector('.package-card-select');
            if (first) first.click();
        } catch (err) {
            document.getElementById('planRow').innerHTML =
                '<div class="col-12 text-center text-muted">Could not load plans. Please refresh.</div>';
        }
    })();

    // ───── Submit ─────
    function setBtnLoading(btn, loading) {
        if (loading) {
            btn.dataset.orig = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Publishing…';
        } else {
            btn.disabled = false;
            btn.innerHTML = btn.dataset.orig || btn.innerHTML;
        }
    }

    document.getElementById('publishBtn').addEventListener('click', async function () {
        const form = document.getElementById('addCampaignForm');

        // Front-end checks
        if (!iconInput.files[0]) { window.Toast.fire({ icon: 'warning', title: 'Please upload an app icon.' }); return; }
        if (!document.getElementById('appName').value.trim())      { window.Toast.fire({ icon: 'warning', title: 'App name required.' }); return; }
        if (!document.getElementById('appDeveloper').value.trim()) { window.Toast.fire({ icon: 'warning', title: 'Developer name required.' }); return; }
        if (!document.getElementById('appLink').value.trim())      { window.Toast.fire({ icon: 'warning', title: 'Play Store URL required.' }); return; }
        if (desEl.value.trim().length < 20)                         { window.Toast.fire({ icon: 'warning', title: 'Description must be at least 20 characters.' }); return; }
        if (!selectedPlanKey)                                       { window.Toast.fire({ icon: 'warning', title: 'Please select a plan.' }); return; }

        setBtnLoading(this, true);
        try {
            const fd = new FormData(form);
            const res = await window.api('/api/campaign/create', { method: 'POST', body: fd });
            if (res.status === 'success') {
                window.Toast.fire({ icon: 'success', title: 'Campaign created. Redirecting to checkout…' });
                setTimeout(() => { window.location.href = (res.data && res.data.redirect) || '/dashboard'; }, 800);
            } else {
                window.Toast.fire({ icon: 'error', title: res.message });
                setBtnLoading(this, false);
            }
        } catch (err) {
            window.Toast.fire({ icon: 'error', title: 'Network error. Please try again.' });
            setBtnLoading(this, false);
        }
    });
})();
</script>

<?php require __DIR__ . '/../includes/partials/dashboard-foot.php'; ?>
