<?php
// --- REDIRECT IF ALREADY INSTALLED ---
$basePath = dirname(__DIR__);
if (file_exists($basePath . '/.env') && file_exists(__DIR__ . '/install.lock')) {
    header('Location: /');
    exit;
}
require_once 'api.php'; 
?>
<!DOCTYPE html>
<html lang="en" class="antialiased">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Application Installer</title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'media',
            theme: {
                extend: {
                    colors: {
                        border: "hsl(var(--border))", input: "hsl(var(--input))", ring: "hsl(var(--ring))",
                        background: "hsl(var(--background))", foreground: "hsl(var(--foreground))",
                        primary: { DEFAULT: "hsl(var(--primary))", foreground: "hsl(var(--primary-foreground))" },
                        secondary: { DEFAULT: "hsl(var(--secondary))", foreground: "hsl(var(--secondary-foreground))" },
                        destructive: { DEFAULT: "hsl(var(--destructive))", foreground: "hsl(var(--destructive-foreground))" },
                        muted: { DEFAULT: "hsl(var(--muted))", foreground: "hsl(var(--muted-foreground))" },
                        accent: { DEFAULT: "hsl(var(--accent))", foreground: "hsl(var(--accent-foreground))" },
                        popover: { DEFAULT: "hsl(var(--popover))", foreground: "hsl(var(--popover-foreground))" },
                        card: { DEFAULT: "hsl(var(--card))", foreground: "hsl(var(--card-foreground))" },
                    },
                }
            }
        }
    </script>
    
    <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="https://unpkg.com/lucide@latest"></script>

    <style>
        @layer base {
            :root { --background: 0 0% 100%; --foreground: 224 71.4% 4.1%; --card: 0 0% 100%; --card-foreground: 224 71.4% 4.1%; --popover: 0 0% 100%; --popover-foreground: 224 71.4% 4.1%; --primary: 220.9 39.3% 11%; --primary-foreground: 210 20% 98%; --secondary: 220 14.3% 95.9%; --secondary-foreground: 220.9 39.3% 11%; --muted: 220 14.3% 95.9%; --muted-foreground: 220 8.9% 46.1%; --accent: 220 14.3% 95.9%; --accent-foreground: 220.9 39.3% 11%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 210 20% 98%; --border: 220 13% 91%; --input: 220 13% 91%; --ring: 224 71.4% 4.1%; }
            .dark { --background: 224 71.4% 4.1%; --foreground: 210 20% 98%; --card: 224 71.4% 4.1%; --card-foreground: 210 20% 98%; --popover: 224 71.4% 4.1%; --popover-foreground: 210 20% 98%; --primary: 210 20% 98%; --primary-foreground: 220.9 39.3% 11%; --secondary: 215 27.9% 16.9%; --secondary-foreground: 210 20% 98%; --muted: 215 27.9% 16.9%; --muted-foreground: 217.9 10.6% 64.9%; --accent: 215 27.9% 16.9%; --accent-foreground: 210 20% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 210 20% 98%; --border: 215 27.9% 16.9%; --input: 215 27.9% 16.9%; --ring: 216 12.2% 83.9%; }
        }
        body { font-family: Figtree, system-ui, sans-serif; }
        .custom-scrollbar::-webkit-scrollbar { width: 6px; } .custom-scrollbar::-webkit-scrollbar-track { background: transparent; } .custom-scrollbar::-webkit-scrollbar-thumb { background-color: rgba(156, 163, 175, 0.5); border-radius: 10px; }
        .step-active { font-weight: 700; color: hsl(var(--primary)); }
        .step-completed { color: #16a34a; } .step-pending { color: hsl(var(--muted-foreground)); }
    </style>
</head>
<body class="bg-background text-foreground selection:bg-primary selection:text-primary-foreground">
    <div id="installer-root"></div>
    <script type="text/babel">
        const { useState, useEffect } = React;
        const STEPS = ["Welcome", "Requirements", "Permissions", "Database", "Install", "Finish"];

        function App() {
            const [step, setStep] = useState(0);
            const [loading, setLoading] = useState(false);
            const [error, setError] = useState(null);
            const [warnings, setWarnings] = useState([]);
            
            const [requirements, setRequirements] = useState({ data: {}, passed: false });
            const [permissions, setPermissions] = useState({ data: {}, passed: false });
            
            const [dbForm, setDbForm] = useState({ db_host: '127.0.0.1', db_port: '3306', db_name: '', db_user: 'root', db_pass: '' });
            const [runSeeders, setRunSeeders] = useState(true);
            const [adminForm, setAdminForm] = useState({ admin_name: '', admin_username: '', admin_email: '', admin_password: '' });

            const nextStep = () => { setError(null); setStep(s => s + 1); };
            const prevStep = () => { setError(null); setStep(s => s - 1); };

            const fetchData = async (action, setDataCallback, errorMsg, autoContinue = false) => {
                setLoading(true); setError(null);
                try {
                    const res = await fetch(`?installer_api=${action}`).then(r => r.json());
                    if (!res.success) throw new Error(res.message);
                    setDataCallback(res);
                    if (res.passed && autoContinue) nextStep();
                    else if (!res.passed) setError(errorMsg);
                } catch (e) { setError(e.message); }
                finally { setLoading(false); }
            };

            const submitDatabase = async (e) => {
                e.preventDefault(); 
                if (!runSeeders && (!adminForm.admin_name || !adminForm.admin_username || !adminForm.admin_email || !adminForm.admin_password)) {
                    setError("Please fill out all Administrator details."); return;
                }
                setLoading(true); setError(null);
                try {
                    const res = await fetch('?installer_api=database', { method: 'POST', body: JSON.stringify(dbForm) }).then(r => r.json());
                    if (!res.success) throw new Error(res.message);
                    nextStep();
                } catch (e) { setError(e.message); }
                finally { setLoading(false); }
            };

            const runInstallation = async () => {
                setLoading(true); setError(null);
                try {
                    const payload = { ...dbForm, run_seeders: runSeeders, ...adminForm };
                    const res = await fetch('?installer_api=install', { method: 'POST', body: JSON.stringify(payload) }).then(r => r.json());
                    if (!res.success) throw new Error(res.message);
                    if (res.warnings && res.warnings.length > 0) {
                        setWarnings(res.warnings);
                    }
                    nextStep();
                } catch (e) { setError("Installation failed: " + e.message); }
                finally { setLoading(false); }
            };

            useEffect(() => {
                if (step === 1 && Object.keys(requirements.data).length === 0) fetchData('requirements', setRequirements, 'Please resolve server requirements.');
                else if (step === 2 && Object.keys(permissions.data).length === 0) fetchData('permissions', setPermissions, 'Please set correct folder permissions.');
                else if (step === 4) runInstallation();
            }, [step]);
            
            return (
                <div className="min-h-screen flex items-center justify-center p-4">
                    <div className="bg-card text-card-foreground rounded-xl shadow-2xl flex flex-col md:flex-row max-w-4xl w-full overflow-hidden min-h-[550px] border">
                        <div className="w-full md:w-64 bg-muted/30 border-b md:border-b-0 md:border-r p-6 shrink-0">
                            <h2 className="text-xl font-bold mb-8 flex items-center gap-2">Installer</h2>
                            <ul className="hidden md:flex flex-col space-y-4">
                                {STEPS.map((s, i) => (
                                    <li key={i} className={`flex items-center gap-3 text-sm ${step === i ? 'step-active' : step > i ? 'step-completed' : 'step-pending'}`}>
                                        <div className={`w-6 h-6 shrink-0 rounded-full flex items-center justify-center border-2 transition-colors ${step === i ? 'border-primary text-primary' : step > i ? 'border-green-600 bg-green-600 text-white' : 'border-border'}`}>{step > i ? '✓' : i + 1}</div>{s}
                                    </li>
                                ))}
                            </ul>
                        </div>
                        <div className="flex-1 p-6 md:p-8 flex flex-col relative overflow-hidden">
                            {error && <div className="bg-destructive/10 text-destructive border border-destructive/20 p-4 rounded-lg text-sm mb-6 flex items-start gap-3">{error}</div>}

                            {step === 0 && <div className="m-auto text-center w-full"><h1 className="text-3xl font-bold mb-3">Welcome to Installer</h1><p className="text-muted-foreground mb-8 max-w-md mx-auto">This wizard will configure your application in just a few clicks.</p><button onClick={nextStep} className="bg-primary text-primary-foreground px-8 py-3 rounded-lg font-semibold shadow-sm hover:opacity-90">Start Installation</button></div>}
                            {step === 1 && <div className="flex flex-col h-full"><h2 className="text-2xl font-bold mb-4">Server Requirements</h2><div className="flex-1 overflow-y-auto border rounded-lg"><table className="w-full text-left text-sm"><tbody className="divide-y">{Object.entries(requirements.data).map(([key, passed]) => <tr key={key}><td className="p-4 font-medium">{key}</td><td className="p-4 text-right">{passed ? <span className="bg-green-500/10 text-green-600 px-2 py-1 rounded text-xs font-bold border border-green-500/20">Passed</span> : <span className="bg-red-500/10 text-red-600 px-2 py-1 rounded text-xs font-bold border border-red-500/20">Failed</span>}</td></tr>)}</tbody></table></div><div className="mt-6 flex justify-between"><button onClick={prevStep} className="bg-secondary text-secondary-foreground px-6 py-2 rounded-lg font-medium">Back</button><button onClick={() => fetchData('requirements', setRequirements, 'Please resolve server requirements.', true)} disabled={loading} className="bg-primary text-primary-foreground px-6 py-2 rounded-lg font-medium disabled:opacity-50">{loading ? 'Checking...' : 'Check Again'}</button></div></div>}
                            {step === 2 && <div className="flex flex-col h-full"><h2 className="text-2xl font-bold mb-4">Folder Permissions</h2><div className="flex-1 overflow-y-auto border rounded-lg"><table className="w-full text-left text-sm"><tbody className="divide-y">{Object.entries(permissions.data).map(([key, passed]) => <tr key={key}><td className="p-4 font-mono text-xs">{key}</td><td className="p-4 text-right">{passed ? <span className="bg-green-500/10 text-green-600 px-2 py-1 rounded text-xs font-bold border border-green-500/20">Writable</span> : <span className="bg-red-500/10 text-red-600 px-2 py-1 rounded text-xs font-bold border border-red-500/20">Unwritable</span>}</td></tr>)}</tbody></table></div><div className="mt-6 flex justify-between"><button onClick={prevStep} className="bg-secondary text-secondary-foreground px-6 py-2 rounded-lg font-medium">Back</button><button onClick={() => fetchData('permissions', setPermissions, 'Please set correct folder permissions.', true)} disabled={loading} className="bg-primary text-primary-foreground px-6 py-2 rounded-lg font-medium disabled:opacity-50">{loading ? 'Checking...' : 'Check Again'}</button></div></div>}
                            {step === 3 && <form onSubmit={submitDatabase} className="flex flex-col h-full"><h2 className="text-2xl font-bold mb-6">Database & Admin Setup</h2><div className="flex-1 overflow-y-auto pr-2 custom-scrollbar"><div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm"><div className="space-y-1"><label>Host</label><input required value={dbForm.db_host} onChange={e => setDbForm({...dbForm, db_host: e.target.value})} className="w-full border-input bg-transparent border rounded-md p-2 outline-none focus:ring-2 focus:ring-primary" /></div><div className="space-y-1"><label>Port</label><input required value={dbForm.db_port} onChange={e => setDbForm({...dbForm, db_port: e.target.value})} className="w-full border-input bg-transparent border rounded-md p-2 outline-none focus:ring-2 focus:ring-primary" /></div><div className="sm:col-span-2 space-y-1"><label>Database Name</label><input required value={dbForm.db_name} onChange={e => setDbForm({...dbForm, db_name: e.target.value})} className="w-full border-input bg-transparent border rounded-md p-2 outline-none focus:ring-2 focus:ring-primary" /></div><div className="space-y-1"><label>Username</label><input required value={dbForm.db_user} onChange={e => setDbForm({...dbForm, db_user: e.target.value})} className="w-full border-input bg-transparent border rounded-md p-2 outline-none focus:ring-2 focus:ring-primary" /></div><div className="space-y-1"><label>Password</label><input type="password" value={dbForm.db_pass} onChange={e => setDbForm({...dbForm, db_pass: e.target.value})} className="w-full border-input bg-transparent border rounded-md p-2 outline-none focus:ring-2 focus:ring-primary" /></div></div><div className="mt-8 pt-6 border-t border-border"><h3 className="text-lg font-bold mb-3">Options</h3><label className="flex items-start gap-3 cursor-pointer p-4 border border-border rounded-lg hover:bg-muted/50 transition-colors"><input type="checkbox" checked={runSeeders} onChange={e => setRunSeeders(e.target.checked)} className="w-5 h-5 mt-0.5 accent-primary rounded" /><div><p className="font-medium text-sm">Run Demo Seeders</p><p className="text-xs text-muted-foreground mt-1">Installs default categories, sample posts, and a default Admin account.</p></div></label>{!runSeeders && (<div className="mt-4 p-4 border border-border bg-muted/20 rounded-lg space-y-4 animate-in fade-in duration-300"><h4 className="font-bold text-sm text-primary">Setup Primary Admin Account</h4><div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm"><div className="space-y-1"><label>Full Name</label><input required value={adminForm.admin_name} onChange={e => setAdminForm({...adminForm, admin_name: e.target.value})} className="w-full border-input bg-background border rounded-md p-2" placeholder="John Doe" /></div><div className="space-y-1"><label>Username</label><input required value={adminForm.admin_username} onChange={e => setAdminForm({...adminForm, admin_username: e.target.value})} className="w-full border-input bg-background border rounded-md p-2" placeholder="admin" /></div><div className="space-y-1"><label>Email</label><input required type="email" value={adminForm.admin_email} onChange={e => setAdminForm({...adminForm, admin_email: e.target.value})} className="w-full border-input bg-background border rounded-md p-2" placeholder="admin@domain.com" /></div><div className="space-y-1"><label>Password</label><input required type="password" value={adminForm.admin_password} onChange={e => setAdminForm({...adminForm, admin_password: e.target.value})} className="w-full border-input bg-background border rounded-md p-2" placeholder="••••••••" /></div></div></div>)}</div></div><div className="mt-6 flex justify-between pt-2"><button type="button" onClick={prevStep} className="bg-secondary text-secondary-foreground px-6 py-2.5 rounded-lg font-medium">Back</button><button type="submit" disabled={loading} className="bg-primary text-primary-foreground px-6 py-2.5 rounded-lg font-medium shadow-sm hover:opacity-90">{loading ? 'Connecting...' : 'Test & Continue'}</button></div></form>}
                            {step === 4 && <div className="m-auto text-center w-full"><div className="inline-block animate-spin rounded-full h-16 w-16 border-t-4 border-primary mb-6"></div><h2 className="text-2xl font-bold mb-2">Installing...</h2><p className="text-muted-foreground text-sm">Setting up database and storage links.<br/><span className="font-semibold text-amber-500 mt-2 block">Please do not close this window.</span></p></div>}
                            
                            {step === 5 && (
                                <div className="m-auto text-center w-full">
                                    <div className="w-20 h-20 bg-green-500/10 text-green-500 rounded-full flex items-center justify-center mx-auto mb-6">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 6 9 17l-5-5"/></svg>
                                    </div>
                                    <h2 className="text-3xl font-bold mb-2">Installation Complete!</h2>
                                    <p className="text-muted-foreground mb-6">Your application is ready to use.</p>
                                    
                                    {/* <-- NEW: Warning Box for Symlink Failure --> */}
                                    {warnings.length > 0 && (
                                        <div className="bg-amber-500/10 text-amber-600 border border-amber-500/20 p-4 rounded-lg text-sm mb-6 text-left max-w-lg mx-auto">
                                            <h4 className="font-bold mb-2">Manual Action Required</h4>
                                            {warnings.map((warn, i) => <p key={i} className="text-amber-700 dark:text-amber-400">{warn}</p>)}
                                        </div>
                                    )}

                                    <div className="bg-muted/50 border rounded-lg p-4 mb-8 text-left text-sm max-w-sm mx-auto">
                                        <h4 className="font-bold mb-3 border-b border-border pb-2 text-center text-primary">Your Admin Credentials</h4>
                                        <div className="space-y-2">
                                            <div className="flex justify-between"><span className="text-muted-foreground">Email:</span> <strong className="select-all">{runSeeders ? 'admin@example.com' : adminForm.admin_email}</strong></div>
                                            <div className="flex justify-between"><span className="text-muted-foreground">Password:</span> <strong className="select-all">{runSeeders ? '12345678' : adminForm.admin_password}</strong></div>
                                        </div>
                                        <p className="text-xs text-amber-600 mt-4 text-center italic bg-amber-500/10 p-2 rounded">Please log in and change your settings immediately.</p>
                                    </div>

                                    <a href="/" className="inline-block bg-primary text-primary-foreground px-8 py-3 rounded-lg font-bold shadow-md hover:opacity-90">Go to Website</a>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            );
        }
        ReactDOM.createRoot(document.getElementById('installer-root')).render(<App />);
    </script>
</body>
</html>