<?php
$pageTitle = 'Funnel: ' . $funnel['name'];
$currentPage = 'funnels';
$breadcrumb = [['label'=>'Funnels','url'=>url('/funnels')],['label'=>e($funnel['name'])],['label'=>'Manage Pages']];
$headerActions = '
    <a href="'.url('/funnel/'.$funnel['slug']).'" target="_blank" class="btn-secondary btn-sm"><i class="fas fa-external-link-alt"></i> Preview</a>
    <button onclick="copyToClipboard(\''.url('/funnel/'.$funnel['slug']).'\')" class="btn-secondary btn-sm"><i class="fas fa-link"></i> Copy Link</button>
';
require_once APP_PATH . '/views/layouts/header.php';
?>

<div style="display:grid;grid-template-columns:340px 1fr;gap:1.25rem">

<!-- Left: Settings + Add Page -->
<div style="display:flex;flex-direction:column;gap:1.25rem">

    <!-- Funnel Settings -->
    <div class="card" style="padding:1.25rem">
        <h3 style="font-weight:700;font-size:.85rem;color:#111827;margin:0 0 1rem">Funnel Settings</h3>
        <div style="display:flex;flex-direction:column;gap:.875rem">
            <div>
                <label class="form-label">Name</label>
                <input type="text" id="funnelName" class="form-input" value="<?= e($funnel['name']) ?>" style="font-size:.8rem">
            </div>
            <div>
                <label class="form-label">Description</label>
                <textarea id="funnelDesc" class="form-input" rows="2" style="font-size:.8rem"><?= e($funnel['description']) ?></textarea>
            </div>
            <button onclick="saveFunnelSettings()" class="btn-primary btn-sm"><i class="fas fa-save"></i> Save Settings</button>
        </div>
    </div>

    <!-- Add Page -->
    <div class="card" style="padding:1.25rem">
        <h3 style="font-weight:700;font-size:.85rem;color:#111827;margin:0 0 1rem">Add New Page</h3>
        <div style="display:flex;flex-direction:column;gap:.875rem">
            <div>
                <label class="form-label">Page Title *</label>
                <input type="text" id="newPageTitle" class="form-input" placeholder="e.g. Welcome Page" style="font-size:.8rem">
            </div>
            <div>
                <label class="form-label">Page Type</label>
                <select id="newPageType" class="form-input" style="font-size:.8rem" onchange="toggleFormSelect()">
                    <option value="landing">Landing Page</option>
                    <option value="form">Form Page</option>
                    <option value="thankyou">Thank You Page</option>
                </select>
            </div>
            <div id="formSelectWrap" style="display:none">
                <label class="form-label">Embed Form</label>
                <select id="newPageForm" class="form-input" style="font-size:.8rem">
                    <option value="">— Select a form —</option>
                    <?php foreach ($forms as $f): ?>
                    <option value="<?= $f['id'] ?>"><?= e($f['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button onclick="addPage()" class="btn-primary btn-sm"><i class="fas fa-plus"></i> Add Page</button>
        </div>
    </div>

    <!-- Public URL Info -->
    <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:.875rem;padding:1rem;font-size:.75rem;color:#166534">
        <p style="font-weight:700;margin:0 0 .375rem"><i class="fas fa-link" style="margin-right:.375rem"></i>Public Funnel URL</p>
        <p style="margin:0 0 .5rem;word-break:break-all;font-family:'JetBrains Mono',monospace"><?= url('/funnel/'.$funnel['slug']) ?></p>
        <button onclick="copyToClipboard('<?= url('/funnel/'.$funnel['slug']) ?>')" style="background:#16a34a;color:#fff;border:none;padding:.375rem .75rem;border-radius:.5rem;font-size:.7rem;font-weight:600;cursor:pointer"><i class="fas fa-copy"></i> Copy</button>
    </div>
</div>

<!-- Right: Pages List -->
<div class="card" style="padding:1.5rem;display:flex;flex-direction:column">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.25rem">
        <div>
            <h3 style="font-weight:700;font-size:.9rem;color:#111827;margin:0">Funnel Pages</h3>
            <p style="font-size:.7rem;color:#9ca3af;margin:.125rem 0 0">Drag to reorder steps &bull; Click to edit</p>
        </div>
        <span class="badge badge-orange" id="pageCountBadge"><?= count($pages) ?> pages</span>
    </div>

    <?php if (empty($pages)): ?>
    <div id="emptyPages" style="text-align:center;padding:3rem;color:#9ca3af;border:2px dashed #e5e7eb;border-radius:1rem">
        <i class="fas fa-layer-group" style="font-size:2rem;margin-bottom:.75rem;display:block;color:#d1d5db"></i>
        <p style="font-weight:600;font-size:.875rem;margin:0 0 .25rem">No Pages Yet</p>
        <p style="font-size:.75rem;margin:0">Add pages on the left to build your funnel flow.</p>
    </div>
    <?php endif; ?>

    <div id="pageList" style="display:flex;flex-direction:column;gap:.75rem">
        <?php foreach ($pages as $idx => $page): ?>
        <div data-page-id="<?= $page['id'] ?>" style="border:1px solid #e5e7eb;border-radius:.875rem;overflow:hidden;background:#fff" id="page-item-<?= $page['id'] ?>">
            <?php include __DIR__ . '/partials/page_card.php'; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>

</div>

<!-- Edit Page Modal -->
<div id="editPageModal" class="modal-overlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1000;align-items:center;justify-content:center">
    <div style="background:#fff;border-radius:1.25rem;padding:1.75rem;width:100%;max-width:500px;margin:1rem;position:relative">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.25rem">
            <h3 style="font-weight:800;font-size:1rem;color:#111827;margin:0">Edit Page</h3>
            <button onclick="closePageModal()" style="background:#f3f4f6;border:none;cursor:pointer;color:#374151;font-size:.875rem;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;flex-shrink:0" title="Close">&times;</button>
        </div>
        <input type="hidden" id="editPageId">
        <div style="display:flex;flex-direction:column;gap:1rem">
            <div>
                <label class="form-label">Page Title *</label>
                <input type="text" id="editPageTitle" class="form-input">
            </div>
            <div>
                <label class="form-label">Page Type</label>
                <select id="editPageType" class="form-input" onchange="toggleEditFormSelect()">
                    <option value="landing">Landing Page</option>
                    <option value="form">Form Page</option>
                    <option value="thankyou">Thank You Page</option>
                </select>
            </div>
            <div id="editFormSelectWrap">
                <label class="form-label">Embed Form</label>
                <select id="editPageForm" class="form-input">
                    <option value="">— No form —</option>
                    <?php foreach ($forms as $f): ?>
                    <option value="<?= $f['id'] ?>"><?= e($f['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="display:flex;gap:.75rem;padding-top:.5rem;border-top:1px solid #f3f4f6">
                <button onclick="savePageEdit()" class="btn-primary" style="flex:1;justify-content:center"><i class="fas fa-save"></i> Save</button>
                <button onclick="openLandingBuilder()" class="btn-secondary"><i class="fas fa-paint-brush"></i> Visual Builder</button>
                <button onclick="deletePageById()" class="btn-danger"><i class="fas fa-trash"></i></button>
            </div>
        </div>
    </div>
</div>

<script>
var FUNNEL_ID = <?= $funnel['id'] ?>;

// Sortable pages
Sortable.create(document.getElementById('pageList'), {
    animation:150,
    handle:'.page-drag-handle',
    ghostClass:'sortable-ghost',
    onEnd: function() {
        var order = Array.from(document.querySelectorAll('[data-page-id]')).map(function(el){ return parseInt(el.dataset.pageId); });
        apiPost('/funnel-pages/reorder', {funnel_id: FUNNEL_ID, order: order}).then(function(res){
            if (res.success) { showToast('Order saved', 'success'); refreshStepNumbers(); }
        });
    }
});

function refreshStepNumbers() {
    document.querySelectorAll('[data-page-id]').forEach(function(el, i) {
        var num = el.querySelector('.step-number');
        if (num) num.textContent = 'Step ' + (i+1);
    });
}

function toggleFormSelect() {
    var type = document.getElementById('newPageType').value;
    document.getElementById('formSelectWrap').style.display = type === 'form' ? '' : 'none';
}

function toggleEditFormSelect() {
    var type = document.getElementById('editPageType').value;
    document.getElementById('editFormSelectWrap').style.display = type === 'form' ? '' : 'none';
}

async function addPage() {
    var title = document.getElementById('newPageTitle').value.trim();
    var type  = document.getElementById('newPageType').value;
    var formId = document.getElementById('newPageForm').value;
    if (!title) { showToast('Page title is required', 'error'); return; }

    var res = await apiPost('/funnel-pages/store', {
        funnel_id: FUNNEL_ID,
        title: title,
        page_type: type,
        form_id: formId || null
    });

    if (res.success) {
        document.getElementById('newPageTitle').value = '';
        document.getElementById('emptyPages') && (document.getElementById('emptyPages').style.display = 'none');
        appendPageCard(res.page);
        updatePageCount(1);
        showToast(res.message, 'success');
    } else {
        showToast(res.message, 'error');
    }
}

var pageCount = <?= count($pages) ?>;
function updatePageCount(delta) {
    pageCount += delta;
    document.getElementById('pageCountBadge').textContent = pageCount + ' pages';
}

function appendPageCard(p) {
    var stepNum = pageCount;
    var typeColors = { landing:'background:#e0e7ff;color:#4338ca', form:'background:#d1fae5;color:#065f46', thankyou:'background:#fef3c7;color:#92400e' };
    var typeIcons  = { landing:'fa-image', form:'fa-wpforms', thankyou:'fa-check-circle' };
    var el = document.createElement('div');
    el.setAttribute('data-page-id', p.id);
    el.id = 'page-item-' + p.id;
    el.style.cssText = 'border:1px solid #e5e7eb;border-radius:.875rem;overflow:hidden;background:#fff';
    el.innerHTML = buildPageCardHTML(p, stepNum);
    document.getElementById('pageList').appendChild(el);
}

function buildPageCardHTML(p, stepNum) {
    var typeColors = { landing:'#e0e7ff;color:#4338ca', form:'#d1fae5;color:#065f46', thankyou:'#fef3c7;color:#92400e' };
    var typeIcons  = { landing:'fa-image', form:'fa-wpforms', thankyou:'fa-check-circle' };
    var color = typeColors[p.page_type] || typeColors.landing;
    var icon  = typeIcons[p.page_type]  || 'fa-file';
    return `
    <div style="display:flex;align-items:center;gap:.875rem;padding:1rem 1.125rem">
        <div class="page-drag-handle" style="color:#d1d5db;cursor:grab;font-size:1rem"><i class="fas fa-grip-vertical"></i></div>
        <div style="width:36px;height:36px;background:${color.split(';')[0]};border-radius:.625rem;display:flex;align-items:center;justify-content:center;flex-shrink:0">
            <i class="fas ${icon}" style="color:${color.split('color:')[1]||'#4f46e5'};font-size:.85rem"></i>
        </div>
        <div style="flex:1;min-width:0">
            <div style="font-weight:700;font-size:.875rem;color:#111827;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${p.title}</div>
            <div style="font-size:.7rem;color:#9ca3af;margin-top:.125rem">
                <span class="step-number" style="font-weight:600;color:#6366f1">Step ${stepNum}</span>
                &bull; <span style="text-transform:capitalize">${p.page_type}</span>
                ${p.form_id ? ' &bull; Form embedded' : ''}
            </div>
        </div>
        <div style="display:flex;gap:.375rem;flex-shrink:0">
            <a href="${APP_URL}/funnels/${FUNNEL_ID}/pages/${p.id}/builder" class="btn-secondary btn-sm" title="Visual Builder"><i class="fas fa-paint-brush"></i></a>
            <button onclick="openEditPage(${p.id},'${escapeHtml(p.title)}','${p.page_type}',${p.form_id||'null'})" class="btn-secondary btn-sm" title="Edit"><i class="fas fa-edit"></i></button>
        </div>
    </div>`;
}

function escapeHtml(str) { return (str||'').replace(/'/g, "\\'"); }

function openEditPage(id, title, type, formId) {
    document.getElementById('editPageId').value = id;
    document.getElementById('editPageTitle').value = title;
    document.getElementById('editPageType').value = type;
    document.getElementById('editPageForm').value = formId || '';
    toggleEditFormSelect();
    document.getElementById('editPageModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function closePageModal() {
    document.getElementById('editPageModal').style.display = 'none';
    document.body.style.overflow = '';
}

function openLandingBuilder() {
    var id = document.getElementById('editPageId').value;
    window.location.href = APP_URL + '/funnels/' + FUNNEL_ID + '/pages/' + id + '/builder';
}

async function savePageEdit() {
    var id    = document.getElementById('editPageId').value;
    var title = document.getElementById('editPageTitle').value.trim();
    var type  = document.getElementById('editPageType').value;
    var formId = document.getElementById('editPageForm').value;
    if (!title) { showToast('Title required', 'error'); return; }

    var res = await apiPost('/funnel-pages/' + id + '/update', {
        title: title,
        page_type: type,
        form_id: formId || null
    });

    if (res.success) {
        var el = document.getElementById('page-item-' + id);
        if (el) {
            var stepEl = el.querySelector('.step-number');
            var stepNum = stepEl ? stepEl.textContent.replace('Step ','') : '?';
            el.innerHTML = buildPageCardHTML(res.page, stepNum);
        }
        closePageModal();
        showToast(res.message, 'success');
    } else {
        showToast(res.message, 'error');
    }
}

async function deletePageById() {
    var id = document.getElementById('editPageId').value;
    confirmDelete('Delete this page?', async function() {
        var res = await apiPost('/funnel-pages/' + id + '/delete', {});
        if (res.success) {
            document.getElementById('page-item-' + id).remove();
            closePageModal();
            updatePageCount(-1);
            refreshStepNumbers();
            showToast(res.message, 'success');
            if (pageCount === 0) document.getElementById('emptyPages') && (document.getElementById('emptyPages').style.display = '');
        } else {
            showToast(res.message, 'error');
        }
    });
}

// Close on backdrop click
document.getElementById('editPageModal').addEventListener('click', function(e) {
    if (e.target === this) closePageModal();
});

// ESC to close
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closePageModal();
});

async function saveFunnelSettings() {
    var name = document.getElementById('funnelName').value.trim();
    var desc = document.getElementById('funnelDesc').value;
    if (!name) { showToast('Name required', 'error'); return; }

    var formData = new FormData();
    formData.append('name', name);
    formData.append('description', desc);

    var res = await fetch(APP_URL + '/funnels/<?= $funnel['id'] ?>/update', {
        method: 'POST',
        headers: {'X-Requested-With':'XMLHttpRequest'},
        body: formData
    }).then(r => r.json());

    if (res.success) showToast(res.message, 'success');
    else showToast(res.message, 'error');
}
</script>

<?php require_once APP_PATH . '/views/layouts/footer.php'; ?>
