<?php
$errors = session()->getFlashdata('errors') ?? [];
$old = session()->getFlashdata('_ci_old_input') ?? [];
$oldPost = $old['post'] ?? [];

function statusVal($old, $key, $default = '') {
    return $old[$key] ?? $default;
}
?>

<div class="space-y-6 max-w-7xl">
    <div class="flex items-center gap-3">
        <div class="w-11 h-11 rounded-2xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-md">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-5.5 h-5.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                <path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
            </svg>
        </div>
        <div>
            <h3 class="text-xl font-bold text-slate-800">Lead Statuses</h3>
            <p class="text-sm text-slate-500">Manage lead pipeline status labels and colors</p>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-1">
            <div class="glass rounded-2xl p-6 shadow-sm border border-slate-200/60 sticky top-6">
                <div class="flex items-center gap-3 mb-5">
                    <div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
                        </svg>
                    </div>
                    <div>
                        <h4 class="text-sm font-bold text-slate-800">Add Status</h4>
                        <p class="text-xs text-slate-500">Create a new lead status</p>
                    </div>
                </div>

                <?php if (!empty($errors)): ?>
                    <div class="mb-5 rounded-xl border border-red-200/70 bg-red-50/50 p-4">
                        <ul class="list-disc list-inside text-xs text-red-700 space-y-0.5">
                            <?php foreach ($errors as $e): ?>
                                <li><?= esc($e) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?= form_open('/admin/lead-statuses', ['class' => 'space-y-4']) ?>
                <?= csrf_field() ?>

                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Status Name <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
                            </svg>
                        </span>
                        <input type="text" name="name" value="<?= esc(statusVal($oldPost, 'name')) ?>" class="w-full pl-11 pr-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-700 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" placeholder="e.g. New, Contacted, Closed">
                    </div>
                    <?php if (isset($errors['name'])): ?>
                        <p class="mt-1 text-xs text-red-600"><?= esc($errors['name']) ?></p>
                    <?php endif; ?>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Color</label>
                    <div class="flex items-center gap-3">
                        <div class="relative flex-1">
                            <input type="color" name="color" value="<?= esc(statusVal($oldPost, 'color', '#3b82f6')) ?>" class="w-full h-11 rounded-xl bg-white border border-slate-200 cursor-pointer p-1">
                        </div>
                        <div class="flex-1">
                            <div class="relative">
                                <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-mono text-xs">#</span>
                                <input type="text" name="color_text" value="<?= esc(statusVal($oldPost, 'color', '#3b82f6')) ?>" oninput="document.querySelector('input[name=color]').value = this.value" class="w-full pl-8 pr-3 py-2.5 rounded-xl bg-white border border-slate-200 text-sm font-mono text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" placeholder="3b82f6">
                            </div>
                        </div>
                    </div>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Sort Order</label>
                    <div class="relative">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12" />
                            </svg>
                        </span>
                        <input type="number" name="sort_order" value="<?= esc(statusVal($oldPost, 'sort_order', '0')) ?>" class="w-full pl-11 pr-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-700 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" placeholder="0">
                    </div>
                </div>

                <button type="submit" class="w-full inline-flex items-center justify-center gap-2 px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold rounded-xl shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
                    </svg>
                    Add Status
                </button>

                </form>
            </div>
        </div>

        <div class="lg:col-span-2">
            <div class="glass rounded-2xl shadow-sm border border-slate-200/60 overflow-hidden">
                <div class="px-6 py-4 bg-slate-50/50 border-b border-slate-200/60 flex items-center justify-between">
                    <div>
                        <h4 class="text-sm font-bold text-slate-800">Status List</h4>
                        <p class="text-xs text-slate-500"><?= count($statuses) ?> status<?= count($statuses) !== 1 ? 'es' : '' ?> defined</p>
                    </div>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-white/30 border-b border-slate-100">
                                <th class="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Color</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-24">Order</th>
                                <th class="px-6 py-3 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider w-32">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <?php if (empty($statuses)): ?>
                                <tr>
                                    <td colspan="4" class="px-6 py-16 text-center">
                                        <div class="flex flex-col items-center gap-3">
                                            <div class="w-14 h-14 rounded-2xl bg-slate-100 flex items-center justify-center">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                                                </svg>
                                            </div>
                                            <p class="text-sm font-medium text-slate-600">No statuses defined yet</p>
                                            <p class="text-xs text-slate-400">Create your first status using the form</p>
                                        </div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($statuses as $s): ?>
                                    <tr class="hover:bg-slate-50/40 transition">
                                        <td class="px-6 py-4">
                                            <div class="flex items-center gap-3">
                                                <span class="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full text-xs font-semibold" style="background: <?= esc($s['color'] ?? '#3b82f6') ?>18; color: <?= esc($s['color'] ?? '#3b82f6') ?>;">
                                                    <span class="w-2 h-2 rounded-full" style="background: <?= esc($s['color'] ?? '#3b82f6') ?>;"></span>
                                                    <?= esc($s['name']) ?>
                                                </span>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="flex items-center gap-3">
                                                <div class="w-9 h-9 rounded-xl shadow-inner border border-slate-200/60" style="background: <?= esc($s['color'] ?? '#3b82f6') ?>;"></div>
                                                <span class="font-mono text-xs text-slate-600"><?= esc($s['color'] ?? '#3b82f6') ?></span>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="inline-flex items-center justify-center min-w-[2rem] h-8 px-2 rounded-lg bg-slate-100 text-xs font-semibold text-slate-700">
                                                <?= esc($s['sort_order'] ?? 0) ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="flex items-center justify-end gap-1">
                                                <button type="button" class="edit-status-btn p-2 rounded-lg text-blue-600 hover:bg-blue-50 transition"
                                                    data-id="<?= (int) $s['id'] ?>"
                                                    data-name="<?= esc($s['name']) ?>"
                                                    data-color="<?= esc($s['color'] ?? '#3b82f6') ?>"
                                                    data-sort-order="<?= esc($s['sort_order'] ?? 0) ?>"
                                                    title="Edit">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                    </svg>
                                                </button>
                                                <form method="get" action="<?= site_url('/admin/lead-statuses/delete/' . (int) $s['id']) ?>" onsubmit="return confirm('Delete this status? Leads using this status will lose their status assignment.');" class="inline">
                                                    <button type="submit" class="p-2 rounded-lg text-red-500 hover:bg-red-50 transition" title="Delete">
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                        </svg>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="editStatusModal" class="fixed inset-0 z-50 hidden items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
    <div class="glass w-full max-w-md rounded-2xl shadow-2xl border border-slate-200/60 p-6 fade-in">
        <div class="flex items-center justify-between mb-5">
            <div class="flex items-center gap-3">
                <div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                </div>
                <div>
                    <h4 class="text-sm font-bold text-slate-800">Edit Status</h4>
                    <p class="text-xs text-slate-500">Update lead status details</p>
                </div>
            </div>
            <button type="button" id="closeEditModal" class="p-2 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-slate-600 transition">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
        </div>

        <?= form_open('', ['id' => 'editStatusForm', 'class' => 'space-y-4']) ?>
        <?= csrf_field() ?>

        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Status Name <span class="text-red-500">*</span></label>
            <div class="relative">
                <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
                    </svg>
                </span>
                <input type="text" id="edit_name" name="name" class="w-full pl-11 pr-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-700 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" placeholder="e.g. New, Contacted, Closed" required>
            </div>
        </div>

        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Color</label>
            <div class="flex items-center gap-3">
                <div class="relative flex-1">
                    <input type="color" id="edit_color" name="color" class="w-full h-11 rounded-xl bg-white border border-slate-200 cursor-pointer p-1">
                </div>
                <div class="flex-1">
                    <div class="relative">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-mono text-xs">#</span>
                        <input type="text" id="edit_color_text" class="w-full pl-8 pr-3 py-2.5 rounded-xl bg-white border border-slate-200 text-sm font-mono text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" placeholder="3b82f6">
                    </div>
                </div>
            </div>
        </div>

        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Sort Order</label>
            <div class="relative">
                <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12" />
                    </svg>
                </span>
                <input type="number" id="edit_sort_order" name="sort_order" class="w-full pl-11 pr-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-700 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" placeholder="0">
            </div>
        </div>

        <div class="flex items-center justify-end gap-3 pt-2">
            <button type="button" id="cancelEditBtn" class="px-4 py-2.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold transition">
                Cancel
            </button>
            <button type="submit" class="inline-flex items-center justify-center gap-2 px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold rounded-xl shadow-md hover:shadow-lg transition-all">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
                </svg>
                Save Changes
            </button>
        </div>

        </form>
    </div>
</div>

<script>
(function () {
    const modal = document.getElementById('editStatusModal');
    const form = document.getElementById('editStatusForm');
    const editName = document.getElementById('edit_name');
    const editColor = document.getElementById('edit_color');
    const editColorText = document.getElementById('edit_color_text');
    const editSortOrder = document.getElementById('edit_sort_order');
    const closeBtn = document.getElementById('closeEditModal');
    const cancelBtn = document.getElementById('cancelEditBtn');

    let currentEditId = null;

    function openModal(data) {
        currentEditId = data.id;
        editName.value = data.name;
        editColor.value = data.color;
        editColorText.value = data.color;
        editSortOrder.value = data.sortOrder;
        form.action = <?= json_encode(site_url('/admin/lead-statuses/update/')) ?> + data.id;
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        setTimeout(() => editName.focus(), 50);
    }

    function closeModal() {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        currentEditId = null;
    }

    document.querySelectorAll('.edit-status-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            openModal({
                id: btn.getAttribute('data-id'),
                name: btn.getAttribute('data-name'),
                color: btn.getAttribute('data-color'),
                sortOrder: btn.getAttribute('data-sort-order'),
            });
        });
    });

    closeBtn.addEventListener('click', closeModal);
    cancelBtn.addEventListener('click', closeModal);
    modal.addEventListener('click', function (e) {
        if (e.target === modal) closeModal();
    });

    editColorText.addEventListener('input', function () {
        let val = editColorText.value.trim();
        if (!val.startsWith('#')) val = '#' + val;
        editColor.value = val;
    });
    editColor.addEventListener('input', function () {
        editColorText.value = editColor.value;
    });

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && !modal.classList.contains('hidden')) closeModal();
    });
})();
</script>
