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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Asystent IT</title>
    <link rel="icon" type="image/png" href="favicons/favicon-96x96.png" sizes="96x96" />
    <link rel="icon" type="image/svg+xml" href="favicons/favicon.svg" />
    <link rel="shortcut icon" href="favicons/favicon.ico" />
    <link rel="apple-touch-icon" sizes="180x180" href="favicons/apple-touch-icon.png" />
    <link rel="manifest" href="favicons/site.webmanifest" />
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#e63223',
                        secondary: '#e63223',
                    }
                }
            }
        }
    </script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        .glass {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(10px);
        }

        .fade-in {
            animation: fadeIn 0.3s ease-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>

<body class="bg-slate-100 min-h-screen flex items-center justify-center p-4">

    <div id="wizard-container" class="glass w-full max-w-lg p-8 rounded-2xl shadow-2xl border border-slate-200 fade-in">
        <header class="mb-8 text-center relative">
            <div class="absolute top-0 right-0 flex gap-2">
                <?php if (!empty($_SESSION['is_admin'])): ?>
                    <a href="admin.php" class="text-slate-400 hover:text-primary transition-colors p-2"
                        title="Panel Administratora">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z">
                            </path>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        </svg>
                    </a>
                <?php endif; ?>
                <button onclick="renderMFASettings()" class="text-slate-400 hover:text-primary transition-colors p-2"
                    title="Zabezpieczenia">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z">
                        </path>
                    </svg>
                </button>
                <a href="logout.php" class="text-slate-400 hover:text-primary transition-colors p-2" title="Wyloguj">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1">
                        </path>
                    </svg>
                </a>
            </div>
            <img src="logo.png" alt="Logo" class="h-16 mx-auto mb-4 object-contain">
            <h1 class="text-3xl font-bold text-slate-800">Asystent IT</h1>
            <p class="text-slate-500 mt-2 font-medium">Zgłoś swój problem do działu IT</p>
            <div class="h-1 w-20 bg-primary mx-auto mt-4 rounded-full"></div>
        </header>

        <div id="wizard-content">
            <!-- Content dynamically loaded here -->
        </div>

        <div id="loader" class="hidden flex justify-center py-4">
            <svg class="animate-spin h-8 w-8 text-primary" xmlns="http://www.w3.org/2000/svg" fill="none"
                viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
                </path>
            </svg>
        </div>
    </div>

    <script>
        const userEmail = '<?php echo $_SESSION['user_email']; ?>';
        const emailPrefix = userEmail.split('@')[0];
        const extractedName = emailPrefix
            .replace(/\./g, ' ')
            .split(' ')
            .map(word => word.split('-').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join('-'))
            .join(' ');

        const state = {
            step: 0,
            isMfaSettings: false,
            name: extractedName,
            userEmail: userEmail,
            selectedSteps: [],
            currentSteps: [],
            description: '',
            senderDomain: '...' // Will be loaded from get_config.php
        };

        const contentEl = document.getElementById('wizard-content');
        const loaderEl = document.getElementById('loader');

        function render() {
            contentEl.innerHTML = '';

            if (state.isMfaSettings) {
                renderMFASettings();
                return;
            }

            if (state.step === 0) {
                renderUserForm();
            } else {
                const lastStep = state.selectedSteps[state.selectedSteps.length - 1];
                if (lastStep && lastStep.is_final == 1) {
                    renderFinalForm();
                } else {
                    renderSteps();
                }
            }
        }

        function renderUserForm() {
            contentEl.innerHTML = `
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider">Imię i Nazwisko</label>
                        <div class="mt-1 flex rounded-lg bg-slate-50 border border-slate-200 overflow-hidden">
                            <div class="p-3 text-slate-500 font-medium flex-1">${state.name}</div>
                            <div class="bg-slate-100 px-4 flex items-center border-l border-slate-200">
                                <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
                            </div>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider">Mój E-mail</label>
                        <div class="mt-1 flex rounded-lg bg-slate-50 border border-slate-200 overflow-hidden">
                            <div class="p-3 text-slate-500 font-medium flex-1">${state.userEmail}</div>
                            <div class="bg-slate-100 px-4 flex items-center border-l border-slate-200">
                                <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
                            </div>
                        </div>
                    </div>
                    <button onclick="handleInitialSubmit()" class="w-full bg-primary text-white rounded-lg py-4 font-bold hover:brightness-110 transition-all shadow-md mt-4 uppercase tracking-widest text-sm">Rozpocznij</button>
                </div>
            `;
        }

        async function renderSteps() {
            const parentId = state.selectedSteps.length > 0 ? state.selectedSteps[state.selectedSteps.length - 1].id : null;

            showLoader(true);
            try {
                const response = await fetch(`get_steps.php?parent_id=${parentId || 'null'}`);
                const steps = await response.json();

                if (steps.error) throw new Error(steps.error);

                contentEl.innerHTML = '<div class="grid grid-cols-1 sm:grid-cols-2 gap-4"></div>';
                const grid = contentEl.querySelector('div');

                if (steps.length === 0) {
                    grid.innerHTML = '<p class="text-center text-slate-500 col-span-full">Brak dostępnych opcji.</p>';
                } else {
                    steps.forEach(step => {
                        const btn = document.createElement('button');
                        btn.className = "text-left px-5 py-4 bg-white border-2 border-slate-100 rounded-xl hover:border-primary hover:bg-green-50/30 transition-all shadow-sm font-semibold text-slate-700 flex flex-col justify-between group h-full";
                        btn.innerHTML = `
                            <span class="mb-2 leading-tight">${step.label_pl}</span>
                            <svg class="w-5 h-5 text-slate-300 group-hover:text-primary transition-colors mt-auto self-end" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg>
                        `;
                        btn.onclick = () => handleStepSelect(step);
                        grid.appendChild(btn);
                    });
                }

                if (state.selectedSteps.length > 0) {
                    const backBtn = document.createElement('button');
                    backBtn.className = "mt-8 text-xs text-slate-400 hover:text-secondary font-bold uppercase tracking-widest w-full text-center transition-colors col-span-full";
                    backBtn.innerText = "← Wróć do poprzedniego kroku";
                    backBtn.onclick = handleBack;
                    contentEl.appendChild(backBtn);
                }

            } catch (err) {
                contentEl.innerHTML = `<p class="text-secondary text-center font-medium col-span-full">${err.message}</p>`;
            } finally {
                showLoader(false);
            }
        }

        function renderFinalForm() {
            contentEl.innerHTML = `
                <div class="space-y-4">
                    <div class="bg-green-50 border-l-4 border-primary p-4 rounded-r-lg">
                        <p class="text-xs font-bold text-primary uppercase tracking-wider mb-1">Ścieżka zgłoszenia:</p>
                        <p class="text-sm text-slate-700 font-medium">${state.selectedSteps.map(s => s.label_pl).join(' / ')}</p>
                    </div>
                    <div>
                        <div class="flex justify-between items-end mb-1">
                            <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider">Opisz problem</label>
                            <span class="text-[10px] font-bold text-primary uppercase tracking-tight">Prosimy o opis w j. angielskim</span>
                        </div>
                        <textarea id="description" rows="5" class="block w-full rounded-lg border-slate-300 shadow-sm focus:border-primary focus:ring-primary p-3 border transition-colors" placeholder="Please describe your problem in English..."></textarea>
                        
                        <div class="mt-3">
                            <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1">Załączniki (obrazki)</label>
                            <input type="file" id="attachment" accept="image/*" multiple class="block w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-primary file:text-white hover:file:brightness-110 cursor-pointer">
                        </div>

                        <div class="mt-4 flex items-center gap-3 text-[11px] text-slate-400 font-medium">
                            <span>Pomoce:</span>
                            <a href="https://www.deepl.com/translator" target="_blank" class="text-primary hover:underline flex items-center gap-1">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path></svg>
                                DeepL
                            </a>
                            <a href="https://translate.google.com/?sl=pl&tl=en" target="_blank" class="text-primary hover:underline flex items-center gap-1">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path></svg>
                                Google Translate
                            </a>
                        </div>
                    </div>
                    <button onclick="handleSubmitTicket()" class="w-full bg-primary text-white rounded-lg py-4 font-bold hover:brightness-110 transition-all shadow-lg uppercase tracking-widest text-sm">Wyślij Zgłoszenie</button>
                    <button onclick="handleBack()" class="w-full text-xs text-slate-400 hover:text-secondary font-bold uppercase tracking-widest transition-colors">← Popraw wybór</button>
                </div>
            `;
        }

        function handleInitialSubmit() {
            state.step = 1;
            render();
        }

        function handleStepSelect(step) {
            state.selectedSteps.push(step);
            render();
        }

        function handleBack() {
            if (state.selectedSteps.length > 0) {
                state.selectedSteps.pop();
            } else {
                state.step = 0;
            }
            render();
        }

        async function handleSubmitTicket() {
            const desc = document.getElementById('description').value.trim();
            const fileInput = document.getElementById('attachment');

            if (!desc) {
                alert('Proszę opisać problem.');
                return;
            }

            const formData = new FormData();
            formData.append('name', state.name);
            formData.append('full_email', state.userEmail);
            formData.append('steps', JSON.stringify(state.selectedSteps.map(s => s.id)));
            formData.append('description', desc);

            if (fileInput.files.length > 0) {
                for (let i = 0; i < fileInput.files.length; i++) {
                    formData.append('attachments[]', fileInput.files[i]);
                }
            }

            showLoader(true);
            try {
                const response = await fetch('send_ticket.php', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    contentEl.innerHTML = `
                        <div class="text-center py-8">
                            <div class="w-20 h-20 bg-green-50 text-primary rounded-full flex items-center justify-center mx-auto mb-6 shadow-sm border border-green-100">
                                <svg class="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path></svg>
                            </div>
                            <h2 class="text-2xl font-bold text-slate-800 tracking-tight">Dziękujemy!</h2>
                            <p class="text-slate-500 mt-3 font-medium">Twoje zgłoszenie zostało wysłane pomyślnie.</p>
                            <button onclick="location.reload()" class="mt-10 px-8 py-3 border-2 border-primary text-primary font-bold rounded-lg hover:bg-primary hover:text-white transition-all uppercase tracking-widest text-xs">Nowe zgłoszenie</button>
                        </div>
                    `;
                } else {
                    throw new Error(result.error || 'Wystąpił błąd podczas wysyłania.');
                }
            } catch (err) {
                alert(err.message);
            } finally {
                showLoader(false);
            }
        }

        function showLoader(show) {
            loaderEl.classList.toggle('hidden', !show);
            if (show) contentEl.style.opacity = '0.5';
            else contentEl.style.opacity = '1';
        }

        async function loadConfig() {
            try {
                const response = await fetch('get_config.php');
                const config = await response.json();
                state.senderDomain = config.sender_domain;
                render();
            } catch (err) {
                console.error('Błąd ładowania konfiguracji:', err);
                state.senderDomain = 'mojadomena.pl'; // fallback
                render();
            }
        }

        async function renderMFASettings() {
            state.isMfaSettings = true;
            showLoader(true);
            try {
                const res = await fetch('auth.php?action=get_mfa_status').then(r => r.json());
                contentEl.innerHTML = `
                    <div class="space-y-6">
                        <div class="flex items-center justify-between">
                            <h2 class="text-xl font-bold text-slate-800">Ustawienia MFA</h2>
                            <button onclick="state.isMfaSettings = false; render();" class="text-slate-400 hover:text-primary transition-colors">
                                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                            </button>
                        </div>
                        <div class="bg-slate-50 p-4 rounded-xl border border-slate-100">
                            <p class="text-sm text-slate-500 mb-2 uppercase font-bold tracking-wider">Aktualna metoda:</p>
                            <div class="flex items-center gap-3 font-semibold text-slate-700">
                                <span>${res.method === 'totp' ? '📱 Aplikacja Authenticator' : '📧 Kod na E-mail'}</span>
                            </div>
                        </div>
                        
                        <div id="mfa-setup-area" class="space-y-4">
                            <p class="text-sm text-slate-600">Możesz w każdej chwili skonfigurować aplikację Authenticator (np. Google Authenticator), aby zwiększyć bezpieczeństwo swojego konta.</p>
                            <button onclick="handleReconfigureTOTP()" class="w-full bg-primary text-white rounded-lg py-4 font-bold hover:brightness-110 transition-all shadow-md uppercase tracking-widest text-xs">
                                Skonfiguruj / Zmień na Authenticator
                            </button>
                        </div>

                        <button onclick="state.isMfaSettings = false; render();" class="w-full text-xs text-slate-400 hover:text-secondary font-bold uppercase tracking-widest transition-colors pt-4 text-center">
                            ← Wróć do Kreatora
                        </button>
                    </div>
                `;
            } catch (err) {
                contentEl.innerHTML = `<p class="text-red-500">Błąd: ${err.message}</p>`;
            } finally {
                showLoader(false);
            }
        }

        async function handleReconfigureTOTP() {
            const area = document.getElementById('mfa-setup-area');
            area.innerHTML = `
                <div class="flex flex-col items-center gap-4 py-4 fade-in">
                    <p class="text-xs text-slate-500 text-center">Zeskanuj poniższy kod w aplikacji Authenticator:</p>
                    <div class="bg-white p-2 border-2 border-slate-100 rounded-lg shadow-inner" id="qr-container">
                        <div class="animate-pulse w-48 h-48 bg-slate-100 rounded flex items-center justify-center text-xs text-slate-400">Generowanie QR...</div>
                    </div>
                    <code id="totp-secret-key" class="text-[10px] text-slate-400 bg-slate-50 px-2 py-1 rounded select-all font-mono"></code>
                    <p class="text-[10px] text-slate-400 text-center italic">Po zeskanowaniu Twoja kolejna próba logowania będzie wymagać kodu z aplikacji.</p>
                    <button onclick="state.isMfaSettings = false; render();" class="w-full bg-green-500 text-white rounded-lg py-4 font-bold hover:bg-green-600 transition-all shadow-md uppercase tracking-widest text-xs">
                        Gotowe!
                    </button>
                </div>
            `;

            try {
                const res = await fetch('auth.php?action=reconfigure_totp').then(r => r.json());
                const img = new Image();
                img.src = res.qr_url;
                img.className = "w-48 h-48";
                img.onload = () => {
                    const container = document.getElementById('qr-container');
                    container.innerHTML = '';
                    container.appendChild(img);
                    document.getElementById('totp-secret-key').innerText = res.secret;
                };
            } catch (err) {
                area.innerHTML = `<p class="text-red-500">Błąd setupu: ${err.message}</p>`;
            }
        }

        // Init
        loadConfig();
    </script>
</body>

</html>