<?php
// setup.php - Initial setup and user creation
require_once __DIR__ . '/src/Database.php';
require_once __DIR__ . '/src/Auth.php';

$db = new Database();
$conn = $db->getConnection();
$setupSuccess = false;
$setupMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $fullName = trim($_POST['full_name'] ?? '');

    if (!$username || !$email || !$password || !$confirmPassword) {
        $setupMessage = 'All fields are required';
    } elseif ($password !== $confirmPassword) {
        $setupMessage = 'Passwords do not match';
    } elseif (strlen($password) < 6) {
        $setupMessage = 'Password must be at least 6 characters';
    } else {
        try {
            $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("INSERT INTO users (username, email, password, full_name, role, status) VALUES (?, ?, ?, ?, 'admin', 'active')");
            $stmt->execute([$username, $email, $hashedPassword, $fullName]);
            $setupSuccess = true;
            $setupMessage = 'Admin user created successfully! Redirecting to login...';
            // Redirect after 2 seconds
            echo '<script>setTimeout(() => { window.location.href = "/login.php"; }, 2000);</script>';
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                $setupMessage = 'Username or email already exists';
            } else {
                $setupMessage = 'Error creating user: ' . $e->getMessage();
            }
        }
    }
}

// Check if admin user already exists
$stmt = $conn->query("SELECT COUNT(*) as count FROM users WHERE role = 'admin'");
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$adminExists = $result['count'] > 0;

if ($adminExists && !$_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Location: /login.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Initial Setup - USSD System</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gradient-to-br from-blue-600 to-purple-700 min-h-screen flex items-center justify-center">
    <div class="w-full max-w-md">
        <div class="bg-white rounded-lg shadow-2xl p-8">
            <div class="text-center mb-8">
                <h1 class="text-3xl font-bold text-gray-800">USSD System</h1>
                <p class="text-gray-500 mt-2">Initial Setup</p>
            </div>

            <?php if ($setupSuccess): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                <?php echo htmlspecialchars($setupMessage); ?>
            </div>
            <script>
                setTimeout(() => {
                    window.location.href = '/ussd/login.php';
                }, 2000);
            </script>
            <?php elseif ($setupMessage): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                <?php echo htmlspecialchars($setupMessage); ?>
            </div>
            <?php endif; ?>

            <?php if ($adminExists): ?>
            <div class="bg-blue-100 border border-blue-400 text-blue-700 px-4 py-3 rounded mb-4">
                Admin user already exists. <a href="/ussd/login.php" class="font-semibold underline">Go to login</a>
            </div>
            <?php else: ?>
            <form method="POST" class="space-y-4">
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">Full Name</label>
                    <input type="text" name="full_name" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Enter your full name">
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">Email</label>
                    <input type="email" name="email" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Enter your email">
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">Username</label>
                    <input type="text" name="username" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Choose a username">
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">Password</label>
                    <input type="password" name="password" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Enter a password (min 6 characters)">
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">Confirm Password</label>
                    <input type="password" name="confirm_password" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Confirm your password">
                </div>

                <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 rounded-lg transition duration-200">
                    Create Admin Account
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
