<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e($form['name']) ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        * { font-family: 'Plus Jakarta Sans', sans-serif; }
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
        .form-card { background: #fff; border-radius: 20px; box-shadow: 0 30px 80px rgba(0,0,0,.2); overflow: hidden; }
        .form-header { background: linear-gradient(135deg, #3b6ff1, #6047ea); padding: 2.5rem 2rem; color: white; }
        .field-group { margin-bottom: 1.25rem; }
        .field-label { display: block; font-size: .8rem; font-weight: 700; color: #374151; margin-bottom: .4rem; text-transform: uppercase; letter-spacing: .04em; }
        .field-input { width: 100%; border: 1.5px solid #e5e7eb; border-radius: 10px; padding: .65rem 1rem; font-size: .9rem; color: #1f2937; transition: border .2s, box-shadow .2s; outline: none; background: #fafafa; }
        .field-input:focus { border-color: #3b6ff1; box-shadow: 0 0 0 3px rgba(59,111,241,.12); background: #fff; }
        .field-input.error { border-color: #ef4444; }
        .error-msg { color: #ef4444; font-size: .78rem; margin-top: .3rem; display: flex; align-items: center; gap: .3rem; }
        .submit-btn { width: 100%; padding: 1rem; background: linear-gradient(135deg, #3b6ff1, #6047ea); color: white; border: none; border-radius: 12px; font-size: 1rem; font-weight: 700; cursor: pointer; transition: all .2s; box-shadow: 0 8px 20px rgba(59,111,241,.35); }
        .submit-btn:hover { transform: translateY(-2px); box-shadow: 0 12px 28px rgba(59,111,241,.45); }
        .submit-btn:disabled { opacity: .7; transform: none; cursor: not-allowed; }
        .required-star { color: #ef4444; margin-left: 3px; }
        .radio-opt, .check-opt { display: flex; align-items: center; gap: .6rem; padding: .5rem .75rem; border: 1.5px solid #e5e7eb; border-radius: 8px; cursor: pointer; transition: all .2s; margin-bottom: .4rem; }
        .radio-opt:hover, .check-opt:hover { border-color: #3b6ff1; background: rgba(59,111,241,.04); }
        .radio-opt input:checked + span, .check-opt input:checked + span { color: #3b6ff1; font-weight: 600; }
        .success-screen { text-align: center; padding: 3rem 2rem; }
        .upload-area { border: 2px dashed #d1d5db; border-radius: 10px; padding: 1.5rem; text-align: center; cursor: pointer; transition: all .2s; }
        .upload-area:hover { border-color: #3b6ff1; background: rgba(59,111,241,.03); }
        .upload-area.has-file { border-color: #10b981; background: rgba(16,185,129,.05); }
        .progress-bar { height: 4px; background: #e5e7eb; border-radius: 2px; overflow: hidden; }
        .progress-fill { height: 100%; background: linear-gradient(90deg,#3b6ff1,#6047ea); border-radius: 2px; transition: width .3s; }
    </style>
</head>
<body class="py-8 px-4">

<div class="max-w-lg mx-auto">
    <div class="form-card" id="formCard">
        <!-- Header -->
        <div class="form-header">
            <h1 class="text-2xl font-extrabold mb-1"><?= e($form['name']) ?></h1>
            <?php if (!empty($form['description'])): ?>
            <p class="opacity-85 text-sm leading-relaxed"><?= e($form['description']) ?></p>
            <?php endif; ?>
        </div>

        <!-- Progress Bar -->
        <?php if (count($fields) > 0): ?>
        <div class="progress-bar">
            <div class="progress-fill" id="progressBar" style="width:0%"></div>
        </div>
        <?php endif; ?>

        <!-- Form Body -->
        <div class="p-8" id="formBody">
            <form id="publicForm" enctype="multipart/form-data" onsubmit="submitForm(event)">
                <?php foreach ($fields as $field): ?>
                <div class="field-group" id="fg-<?= $field['id'] ?>">
                    <label class="field-label">
                        <?= e($field['label']) ?>
                        <?php if ($field['required']): ?><span class="required-star">*</span><?php endif; ?>
                    </label>

                    <?php
                    $inputName = 'field_' . $field['id'];
                    $placeholder = $field['placeholder'] ?: '';
                    $required = $field['required'] ? 'required' : '';
                    $opts = array_filter(array_map('trim', explode("\n", $field['options'] ?? '')));
                    ?>

                    <?php if ($field['field_type'] === 'text'): ?>
                        <input type="text" name="<?= $inputName ?>" class="field-input" placeholder="<?= e($placeholder) ?>" <?= $required ?>>

                    <?php elseif ($field['field_type'] === 'email'): ?>
                        <input type="email" name="<?= $inputName ?>" class="field-input" placeholder="<?= e($placeholder) ?>" <?= $required ?>>

                    <?php elseif ($field['field_type'] === 'phone'): ?>
                        <input type="tel" name="<?= $inputName ?>" class="field-input" placeholder="<?= e($placeholder ?: '60123456789') ?>" <?= $required ?>>

                    <?php elseif ($field['field_type'] === 'number'): ?>
                        <input type="number" name="<?= $inputName ?>" class="field-input" placeholder="<?= e($placeholder) ?>" <?= $required ?>>

                    <?php elseif ($field['field_type'] === 'textarea'): ?>
                        <textarea name="<?= $inputName ?>" rows="4" class="field-input" placeholder="<?= e($placeholder) ?>" <?= $required ?>></textarea>

                    <?php elseif ($field['field_type'] === 'select'): ?>
                        <select name="<?= $inputName ?>" class="field-input" <?= $required ?>>
                            <option value="">Pilih satu pilihan...</option>
                            <?php foreach ($opts as $opt):
                                $parts = explode('|', $opt, 2);
                                $optLabel = trim($parts[0]);
                            ?>
                            <option value="<?= e($optLabel) ?>"><?= e($optLabel) ?></option>
                            <?php endforeach; ?>
                        </select>

                    <?php elseif ($field['field_type'] === 'radio'): ?>
                        <?php
                        $hasAnyImg = false;
                        foreach ($opts as $opt) { if (strpos($opt, '|') !== false) { $hasAnyImg = true; break; } }
                        ?>
                        <div style="display:grid;grid-template-columns:<?= $hasAnyImg ? 'repeat(auto-fill,minmax(140px,1fr))' : '1fr' ?>;gap:.625rem">
                        <?php foreach ($opts as $opt):
                            $parts    = explode('|', $opt, 2);
                            $optLabel = trim($parts[0]);
                            $optImg   = isset($parts[1]) ? trim($parts[1]) : '';
                        ?>
                        <label style="display:flex;<?= $optImg ? 'flex-direction:column' : 'flex-direction:row;align-items:center' ?>;gap:.5rem;padding:<?= $optImg ? '.75rem' : '.5rem .75rem' ?>;border:1.5px solid #e5e7eb;border-radius:10px;cursor:pointer;transition:all .2s;background:#fff" onmouseover="this.style.borderColor='#6366f1';this.style.background='#f5f3ff'" onmouseout="this.style.borderColor='#e5e7eb';this.style.background='#fff'">
                            <?php if ($optImg): ?>
                            <img src="<?= e(uploadUrl($optImg)) ?>" alt="<?= e($optLabel) ?>"
                                 style="width:100%;height:110px;object-fit:cover;border-radius:7px;display:block"
                                 onerror="this.style.display='none';this.nextSibling.textContent='[Gambar tidak dijumpai]'">
                            <?php endif; ?>
                            <div style="display:flex;align-items:center;gap:.5rem">
                                <input type="radio" name="<?= $inputName ?>" value="<?= e($optLabel) ?>" <?= $required ?> style="accent-color:#6366f1;flex-shrink:0">
                                <span style="font-size:.875rem;color:#374151;font-weight:500"><?= e($optLabel) ?></span>
                            </div>
                        </label>
                        <?php endforeach; ?>
                        </div>

                    <?php elseif ($field['field_type'] === 'checkbox'): ?>
                        <?php
                        $hasAnyImg = false;
                        foreach ($opts as $opt) { if (strpos($opt, '|') !== false) { $hasAnyImg = true; break; } }
                        ?>
                        <div style="display:grid;grid-template-columns:<?= $hasAnyImg ? 'repeat(auto-fill,minmax(140px,1fr))' : '1fr' ?>;gap:.625rem">
                        <?php foreach ($opts as $opt):
                            $parts    = explode('|', $opt, 2);
                            $optLabel = trim($parts[0]);
                            $optImg   = isset($parts[1]) ? trim($parts[1]) : '';
                        ?>
                        <label style="display:flex;<?= $optImg ? 'flex-direction:column' : 'flex-direction:row;align-items:center' ?>;gap:.5rem;padding:<?= $optImg ? '.75rem' : '.5rem .75rem' ?>;border:1.5px solid #e5e7eb;border-radius:10px;cursor:pointer;transition:all .2s;background:#fff" onmouseover="this.style.borderColor='#6366f1';this.style.background='#f5f3ff'" onmouseout="this.style.borderColor='#e5e7eb';this.style.background='#fff'">
                            <?php if ($optImg): ?>
                            <img src="<?= e(uploadUrl($optImg)) ?>" alt="<?= e($optLabel) ?>"
                                 style="width:100%;height:110px;object-fit:cover;border-radius:7px;display:block"
                                 onerror="this.style.display='none'">
                            <?php endif; ?>
                            <div style="display:flex;align-items:center;gap:.5rem">
                                <input type="checkbox" name="<?= $inputName ?>[]" value="<?= e($optLabel) ?>" style="accent-color:#6366f1;flex-shrink:0">
                                <span style="font-size:.875rem;color:#374151;font-weight:500"><?= e($optLabel) ?></span>
                            </div>
                        </label>
                        <?php endforeach; ?>
                        </div>

                    <?php elseif ($field['field_type'] === 'date'): ?>
                        <input type="date" name="<?= $inputName ?>" class="field-input" <?= $required ?>>

                    <?php elseif ($field['field_type'] === 'image'): ?>
                        <div class="upload-area" id="upload-area-<?= $field['id'] ?>" onclick="document.getElementById('<?= $inputName ?>').click()">
                            <i class="fas fa-image text-3xl text-gray-300 mb-2 block"></i>
                            <p class="text-gray-500 text-sm font-medium" id="upload-label-<?= $field['id'] ?>">Click to upload image</p>
                            <p class="text-gray-400 text-xs mt-1">JPG, PNG, JPEG — Max 5MB</p>
                            <img id="upload-preview-<?= $field['id'] ?>" class="hidden mx-auto mt-3 rounded-lg max-h-32 object-cover">
                        </div>
                        <input type="file" id="<?= $inputName ?>" name="<?= $inputName ?>" class="hidden" accept=".jpg,.jpeg,.png" <?= $required ?>
                               onchange="handleImagePreview(this, <?= $field['id'] ?>)">

                    <?php elseif ($field['field_type'] === 'file'): ?>
                        <div class="upload-area" onclick="document.getElementById('<?= $inputName ?>').click()">
                            <i class="fas fa-file text-3xl text-gray-300 mb-2 block"></i>
                            <p class="text-gray-500 text-sm font-medium" id="file-label-<?= $field['id'] ?>">Click to upload file</p>
                        </div>
                        <input type="file" id="<?= $inputName ?>" name="<?= $inputName ?>" class="hidden" <?= $required ?>
                               onchange="document.getElementById('file-label-<?= $field['id'] ?>').textContent=this.files[0]?.name||'Click to upload file'">
                    <?php endif; ?>

                    <div class="error-msg hidden" id="err-<?= $field['id'] ?>">
                        <i class="fas fa-exclamation-circle"></i><span></span>
                    </div>
                </div>
                <?php endforeach; ?>

                <div class="mt-6">
                    <button type="submit" class="submit-btn" id="submitBtn">
                        <i class="fas fa-paper-plane mr-2"></i>Submit Form
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Branding -->
    <div class="text-center mt-6 text-white/60 text-xs">
        Powered by <strong>SmartForm Builder</strong>
    </div>
</div>

<script>
const FORM_SLUG = '<?= e($form['slug']) ?>';
const APP_URL   = '<?= APP_URL ?>';
const TOTAL_FIELDS = <?= count($fields) ?>;

function handleImagePreview(input, fieldId) {
    const file = input.files[0];
    if (!file) return;
    const area = document.getElementById('upload-area-' + fieldId);
    const label = document.getElementById('upload-label-' + fieldId);
    const preview = document.getElementById('upload-preview-' + fieldId);
    area.classList.add('has-file');
    label.textContent = file.name;
    const reader = new FileReader();
    reader.onload = e => { preview.src = e.target.result; preview.classList.remove('hidden'); };
    reader.readAsDataURL(file);
}

function updateProgress() {
    const inputs = document.querySelectorAll('#publicForm input, #publicForm textarea, #publicForm select');
    let filled = 0;
    inputs.forEach(inp => { if (inp.value) filled++; });
    const pct = TOTAL_FIELDS > 0 ? Math.min(100, Math.round((filled / TOTAL_FIELDS) * 100)) : 0;
    const bar = document.getElementById('progressBar');
    if (bar) bar.style.width = pct + '%';
}

document.querySelectorAll('#publicForm input, #publicForm textarea, #publicForm select').forEach(el => {
    el.addEventListener('input', updateProgress);
    el.addEventListener('change', updateProgress);
});

async function submitForm(e) {
    e.preventDefault();
    const btn = document.getElementById('submitBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Submitting...';

    // Clear errors
    document.querySelectorAll('.error-msg').forEach(el => el.classList.add('hidden'));
    document.querySelectorAll('.field-input').forEach(el => el.classList.remove('error'));

    const formData = new FormData(document.getElementById('publicForm'));

    const resp = await fetch(APP_URL + '/form/' + FORM_SLUG + '/submit', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: formData
    });

    const data = await resp.json();

    if (data.success) {
        // Show success
        document.getElementById('formBody').innerHTML = `
            <div class="success-screen">
                <div class="w-20 h-20 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-5">
                    <i class="fas fa-check-circle text-4xl text-green-500"></i>
                </div>
                <h2 class="text-2xl font-extrabold text-gray-800 mb-3">Thank You!</h2>
                <p class="text-gray-500 mb-6">${data.message}</p>
                ${data.whatsapp_url ? `<a href="${data.whatsapp_url}" target="_blank"
                    class="inline-flex items-center gap-2 px-6 py-3 rounded-xl text-white font-bold text-sm mb-3"
                    style="background:linear-gradient(135deg,#25d366,#128c7e);box-shadow:0 8px 20px rgba(37,211,102,.35)">
                    <i class="fab fa-whatsapp text-lg"></i>Send via WhatsApp
                </a>` : ''}
                ${data.redirect_url ? `<script>setTimeout(()=>{window.location='${data.redirect_url}'},2500);<\/script><p class="text-xs text-gray-400 mt-2">Redirecting in 3 seconds...</p>` : ''}
            </div>`;

        // Auto open WhatsApp after 1 second
        if (data.whatsapp_url) {
            setTimeout(() => window.open(data.whatsapp_url, '_blank'), 1000);
        }
    } else {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-paper-plane mr-2"></i>Submit Form';

        if (data.errors) {
            Object.entries(data.errors).forEach(([fieldId, msg]) => {
                const errEl = document.getElementById('err-' + fieldId);
                if (errEl) {
                    errEl.classList.remove('hidden');
                    errEl.querySelector('span').textContent = msg;
                }
                const input = document.querySelector(`[name="field_${fieldId}"]`);
                if (input) input.classList.add('error');
            });
            document.querySelector('.error-msg:not(.hidden)')?.scrollIntoView({ behavior:'smooth', block:'center' });
        }
    }
}
</script>
</body>
</html>
