<?php
// install/index.php - UHD-Lite Installation Wizard
session_start();

// Check if already installed
if(file_exists('../config.php')) {
    header("Location: ../index.php");
    exit();
}

$step = $_GET['step'] ?? 1;
$error = '';
$success = '';

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if($step == 1) {
        // Test database connection
        $host = $_POST['db_host'];
        $name = $_POST['db_name'];
        $user = $_POST['db_user'];
        $pass = $_POST['db_pass'];
        
        try {
            $pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // Create database if not exists
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `$name`");
            $pdo->exec("USE `$name`");
            
            // Run SQL setup file
            $sql = file_get_contents(__DIR__ . '/setup.sql');
            $pdo->exec($sql);
            
            $_SESSION['db_config'] = [
                'host' => $host,
                'name' => $name,
                'user' => $user,
                'pass' => $pass
            ];
            
            header("Location: index.php?step=2");
            exit();
        } catch(PDOException $e) {
            $error = "Connection failed: " . $e->getMessage();
        }
    } elseif($step == 2) {
        // Create admin account
        $db = $_SESSION['db_config'];
        
        try {
            $pdo = new PDO(
                "mysql:host={$db['host']};dbname={$db['name']};charset=utf8mb4",
                $db['user'],
                $db['pass']
            );
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // Create admin user
            $admin_pass = password_hash($_POST['admin_pass'], PASSWORD_BCRYPT);
            $stmt = $pdo->prepare("
                INSERT INTO users (username, password, full_name, email, role, status) 
                VALUES (?, ?, ?, ?, 'admin', 'active')
            ");
            $stmt->execute([
                $_POST['admin_user'],
                $admin_pass,
                $_POST['admin_name'],
                $_POST['admin_email']
            ]);
            
            // Generate config.php from sample
            $sample = file_get_contents('../config.sample.php');
            $config = str_replace(
                ['DB_HOST_VALUE', 'DB_NAME_VALUE', 'DB_USER_VALUE', 'DB_PASS_VALUE'],
                [$db['host'], $db['name'], $db['user'], $db['pass']],
                $sample
            );
            file_put_contents('../config.php', $config);
            
            unset($_SESSION['db_config']);
            
            $success = "Installation completed successfully!";
            header("refresh:3; url=../index.php");
            
        } catch(PDOException $e) {
            $error = "Installation failed: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>UHD-Lite Installation</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white text-center">
                        <h3>UHD-Lite Installation</h3>
                        <p class="mb-0">Healthcare Management System</p>
                    </div>
                    <div class="card-body">
                        <?php if($error): ?>
                            <div class="alert alert-danger"><?= $error ?></div>
                        <?php endif; ?>
                        <?php if($success): ?>
                            <div class="alert alert-success"><?= $success ?> Redirecting...</div>
                        <?php endif; ?>
                        
                        <?php if($step == 1 && !$success): ?>
                            <h5>Step 1: Database Configuration</h5>
                            <form method="POST">
                                <div class="mb-3">
                                    <label>Database Host</label>
                                    <input type="text" name="db_host" class="form-control" value="localhost" required>
                                </div>
                                <div class="mb-3">
                                    <label>Database Name</label>
                                    <input type="text" name="db_name" class="form-control" required>
                                </div>
                                <div class="mb-3">
                                    <label>Database Username</label>
                                    <input type="text" name="db_user" class="form-control" required>
                                </div>
                                <div class="mb-3">
                                    <label>Database Password</label>
                                    <input type="password" name="db_pass" class="form-control">
                                </div>
                                <button type="submit" class="btn btn-primary w-100">Test Connection & Continue</button>
                            </form>
                        <?php elseif($step == 2 && !$success): ?>
                            <h5>Step 2: Admin Account</h5>
                            <form method="POST">
                                <div class="mb-3">
                                    <label>Admin Username</label>
                                    <input type="text" name="admin_user" class="form-control" value="admin" required>
                                </div>
                                <div class="mb-3">
                                    <label>Admin Password</label>
                                    <input type="password" name="admin_pass" class="form-control" required>
                                </div>
                                <div class="mb-3">
                                    <label>Full Name</label>
                                    <input type="text" name="admin_name" class="form-control" required>
                                </div>
                                <div class="mb-3">
                                    <label>Email Address</label>
                                    <input type="email" name="admin_email" class="form-control" required>
                                </div>
                                <button type="submit" class="btn btn-success w-100">Complete Installation</button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>