<?php
session_start();
if (!isset($_SESSION['user_email']) || empty($_SESSION['is_admin'])) {
    header('Location: index.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="pl">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Zarządzanie Krokami</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: { extend: { colors: { primary: '#e63223', secondary: '#333' } } }
        }
    </script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        .glass {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(10px);
        }
    </style>
</head>

<body class="bg-slate-100 min-h-screen p-4 md:p-8">
    <div class="max-w-6xl mx-auto">
        <header
            class="flex justify-between items-center mb-8 bg-white p-6 rounded-2xl shadow-sm border border-slate-200">
            <div>
                <h1 class="text-2xl font-bold text-slate-800">Panel Administratora</h1>
                <p class="text-slate-500 text-sm">Zarządzanie ścieżkami IT Wizard</p>
            </div>
            <div class="flex gap-4">
                <a href="index.php"
                    class="px-4 py-2 text-slate-500 hover:text-primary font-bold transition-all text-sm flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6">
                        </path>
                    </svg>
                    Wróć do Wizarda
                </a>
                <button onclick="openModal()"
                    class="bg-primary text-white px-6 py-2 rounded-xl font-bold hover:brightness-110 shadow-lg transition-all text-sm flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                    Dodaj Nowy Krok
                </button>
            </div>
        </header>

        <div class="bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-slate-50 border-b border-slate-200">
                        <th class="p-4 text-xs font-bold text-slate-500 uppercase tracking-widest">ID</th>
                        <th class="p-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Parent</th>
                        <th class="p-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Etykieta (PL/EN)</th>
                        <th class="p-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Typ/Final</th>
                        <th class="p-4 text-xs font-bold text-slate-500 uppercase tracking-widest text-right">Akcje</th>
                    </tr>
                </thead>
                <tbody id="steps-table-body">
                    <!-- Loaded via JS -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- Modal -->
    <div id="step-modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center p-4 z-50">
        <div class="glass w-full max-w-lg p-8 rounded-2xl shadow-2xl space-y-6">
            <h2 id="modal-title" class="text-2xl font-bold text-slate-800">Dodaj Krok</h2>
            <form id="step-form" class="space-y-4">
                <input type="hidden" id="step-id">
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Krok nadrzędny (Rodzic)</label>
                    <select id="parent-id" class="w-full p-3 border rounded-xl focus:ring-2 focus:ring-primary outline-none">
                        <option value="">(Brak - Krok Główny)</option>
                    </select>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Etykieta PL</label>
                        <input type="text" id="label-pl" required
                            class="w-full p-3 border rounded-xl focus:ring-2 focus:ring-primary outline-none">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Etykieta EN</label>
                        <input type="text" id="label-en" required
                            class="w-full p-3 border rounded-xl focus:ring-2 focus:ring-primary outline-none">
                    </div>
                </div>
                <div class="flex items-center gap-4 py-2 border-t border-b border-slate-100">
                    <label class="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" id="is-final" class="w-5 h-5 accent-primary">
                        <span class="text-sm font-bold text-slate-700">Krok końcowy?</span>
                    </label>
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Typ zgłoszenia
                        (REQ/INC)</label>
                    <select id="ticket-type"
                        class="w-full p-3 border rounded-xl focus:ring-2 focus:ring-primary outline-none">
                        <option value="">(Brak)</option>
                        <option value="REQ">REQ</option>
                        <option value="INC">INC</option>
                    </select>
                </div>
                <div class="flex gap-3 pt-4">
                    <button type="button" onclick="closeModal()"
                        class="flex-1 px-4 py-3 bg-slate-100 text-slate-600 font-bold rounded-xl hover:bg-slate-200 transition-all uppercase tracking-widest text-xs">Anuluj</button>
                    <button type="submit"
                        class="flex-1 px-4 py-3 bg-primary text-white font-bold rounded-xl hover:brightness-110 transition-all shadow-lg uppercase tracking-widest text-xs">Zapisz</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let allSteps = [];

        async function loadSteps() {
            const res = await fetch('auth.php?action=get_all_steps').then(r => r.json());
            if (res.success) {
                allSteps = res.steps;
                renderTable();
            }
        }

        function renderTable() {
            const tbody = document.getElementById('steps-table-body');
            tbody.innerHTML = allSteps.map(step => {
                const parent = allSteps.find(s => s.id == step.parent_id);
                return `
                    <tr class="border-b border-slate-100 hover:bg-slate-50 transition-colors">
                        <td class="p-4 text-xs font-mono text-slate-400">${step.id}</td>
                        <td class="p-4">
                            ${parent 
                                ? `<div class="text-xs font-bold text-slate-600">${parent.label_pl}</div><div class="text-[10px] text-slate-400">ID: ${parent.id}</div>` 
                                : '<span class="text-slate-300 text-[10px] italic">Główny</span>'}
                        </td>
                        <td class="p-4">
                            <div class="font-bold text-slate-800">${step.label_pl}</div>
                            <div class="text-xs text-slate-400">${step.label_en}</div>
                        </td>
                        <td class="p-4">
                            ${step.is_final == 1 ? '<span class="bg-green-100 text-green-700 px-2 py-0.5 rounded text-[10px] font-bold">FINAL</span>' : ''}
                            ${step.ticket_type ? `<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-[10px] font-bold ml-1">${step.ticket_type}</span>` : ''}
                        </td>
                        <td class="p-4 text-right">
                            <button onclick="editStep(${step.id})" class="text-slate-400 hover:text-primary p-2"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg></button>
                            <button onclick="deleteStep(${step.id})" class="text-slate-400 hover:text-red-500 p-2"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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"></path></svg></button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        function openModal(step = null) {
            const modal = document.getElementById('step-modal');
            const parentSelect = document.getElementById('parent-id');
            
            modal.classList.remove('hidden');
            modal.classList.add('flex');

            // Populate Parent dropdown
            parentSelect.innerHTML = '<option value="">(Brak - Krok Główny)</option>';
            allSteps.forEach(s => {
                // Prevent selecting itself OR selecting final items as parents
                if ((!step || s.id != step.id) && s.is_final != 1) {
                    parentSelect.innerHTML += `<option value="${s.id}">${s.label_pl} (${s.label_en})</option>`;
                }
            });

            if (step) {
                document.getElementById('modal-title').innerText = 'Edytuj Krok';
                document.getElementById('step-id').value = step.id;
                parentSelect.value = step.parent_id || '';
                document.getElementById('label-pl').value = step.label_pl;
                document.getElementById('label-en').value = step.label_en;
                document.getElementById('is-final').checked = step.is_final == 1;
                document.getElementById('ticket-type').value = step.ticket_type || '';
            } else {
                document.getElementById('modal-title').innerText = 'Dodaj Krok';
                document.getElementById('step-form').reset();
                document.getElementById('step-id').value = '';
                parentSelect.value = '';
            }
        }

        function closeModal() {
            document.getElementById('step-modal').classList.add('hidden');
            document.getElementById('step-modal').classList.remove('flex');
        }

        function editStep(id) {
            const step = allSteps.find(s => s.id == id);
            if (step) openModal(step);
        }

        async function deleteStep(id) {
            if (!confirm('Czy na pewno chcesz usunąć ten krok?')) return;
            const res = await fetch('auth.php?action=delete_step', {
                method: 'POST',
                body: JSON.stringify({ id })
            }).then(r => r.json());
            if (res.success) loadSteps();
            else alert(res.message);
        }

        document.getElementById('step-form').onsubmit = async (e) => {
            e.preventDefault();
            const data = {
                id: document.getElementById('step-id').value,
                parent_id: document.getElementById('parent-id').value,
                label_pl: document.getElementById('label-pl').value,
                label_en: document.getElementById('label-en').value,
                is_final: document.getElementById('is-final').checked ? 1 : 0,
                ticket_type: document.getElementById('ticket-type').value
            };

            const res = await fetch('auth.php?action=save_step', {
                method: 'POST',
                body: JSON.stringify(data)
            }).then(r => r.json());

            if (res.success) {
                closeModal();
                loadSteps();
            } else {
                alert(res.message);
            }
        };

        loadSteps();
    </script>
</body>

</html>