<?php
// create_admin.php - DELETE AFTER USE!
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'includes/db.php'; // Adjust path if needed

// Security: Only allow local access
$allowed_ips = ['127.0.0.1', '::1', 'localhost'];
if (!in_array($_SERVER['REMOTE_ADDR'], $allowed_ips) && php_sapi_name() !== 'cli') {
    die('Access denied. This script can only be run locally.');
}

$message = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $occupation = trim($_POST['occupation'] ?? 'Admin');
    $age = (int) ($_POST['age'] ?? 30);
    $birth_year = date('Y') - $age;

    // Validation
    $errors = [];

    if (empty($full_name)) {
        $errors[] = "Full name is required";
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Valid email is required";
    }

    if (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters";
    }

    if ($password !== $confirm_password) {
        $errors[] = "Passwords do not match";
    }

    if (empty($phone)) {
        $errors[] = "Phone number is required";
    }

    if (empty($address)) {
        $errors[] = "Address is required";
    }

    // Check if email already exists
    if (empty($errors)) {
        $check_stmt = $pdo->prepare("SELECT user_id FROM users WHERE email = ?");
        $check_stmt->execute([$email]);
        if ($check_stmt->fetch()) {
            $errors[] = "Email already exists in the system";
        }
    }

    // If no errors, create admin user
    if (empty($errors)) {
        try {
            $password_hash = password_hash($password, PASSWORD_DEFAULT);

            $sql = "INSERT INTO users (
                full_name, age, birth_year, email, address, 
                occupation, phone, password_hash, is_admin, 
                status, is_active, created_at
            ) VALUES (
                :full_name, :age, :birth_year, :email, :address,
                :occupation, :phone, :password_hash, 1,
                'approved', 1, NOW()
            )";

            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':full_name' => $full_name,
                ':age' => $age,
                ':birth_year' => $birth_year,
                ':email' => $email,
                ':address' => $address,
                ':occupation' => $occupation,
                ':phone' => $phone,
                ':password_hash' => $password_hash
            ]);

            $user_id = $pdo->lastInsertId();

            $message = "✅ Admin user created successfully!";
            $message .= "<br>User ID: " . $user_id;
            $message .= "<br>Email: " . htmlspecialchars($email);
            $message .= "<br>Name: " . htmlspecialchars($full_name);
            $success = true;

        } catch (PDOException $e) {
            $message = "❌ Database error: " . $e->getMessage();
        }
    } else {
        $message = "❌ Please fix the following errors:<br>" . implode("<br>", $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Admin - Oakshire Finance</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            padding: 40px;
            max-width: 600px;
            width: 100%;
        }

        h2 {
            color: #1e3c72;
            margin-bottom: 10px;
            text-align: center;
            font-size: 28px;
        }

        .subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .db-info {
            background: #f0f7ff;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 25px;
            font-size: 14px;
            border-left: 4px solid #1e3c72;
        }

        .db-info strong {
            color: #1e3c72;
        }

        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group.full-width {
            grid-column: span 2;
        }

        label {
            display: block;
            margin-bottom: 5px;
            color: #4a5568;
            font-weight: 500;
            font-size: 14px;
        }

        label .required {
            color: #e53e3e;
        }

        input,
        textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 15px;
            transition: all 0.3s;
            font-family: inherit;
        }

        input:focus,
        textarea:focus {
            outline: none;
            border-color: #1e3c72;
            box-shadow: 0 0 0 3px rgba(30, 60, 114, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 80px;
        }

        button {
            width: 100%;
            padding: 16px;
            background: #1e3c72;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
            margin-top: 10px;
        }

        button:hover {
            background: #2a5298;
        }

        .message {
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 25px;
            text-align: center;
            font-weight: 500;
        }

        .message.success {
            background: #c6f6d5;
            color: #22543d;
            border: 1px solid #9ae6b4;
        }

        .message.error {
            background: #fed7d7;
            color: #742a2a;
            border: 1px solid #fc8181;
        }

        .warning {
            background: #fefcbf;
            color: #744210;
            padding: 15px;
            border-radius: 8px;
            font-size: 13px;
            margin-top: 25px;
            text-align: center;
            border: 1px solid #faf089;
        }

        .login-info {
            background: #e6fffa;
            border: 1px solid #4fd1c5;
            border-radius: 10px;
            padding: 15px;
            margin-top: 20px;
            color: #234e52;
        }

        .note {
            font-size: 13px;
            color: #718096;
            margin-top: 5px;
        }
    </style>
    <link rel="stylesheet" href="assets/css/nexus-theme.css" />
</head>

<body>
    <div class="container">
        <h2>🏦 Create Admin Account</h2>
        <div class="subtitle">Oakshire Finance Platform Administration</div>

        <div class="db-info">
            <strong>Database:</strong> <?php echo htmlspecialchars($dbname); ?><br>
            <strong>Table:</strong> users (is_admin field detected)<br>
            <strong>Status:</strong> <span style="color:green">✓ Ready to create admin</span>
        </div>

        <?php if ($message): ?>
            <div class="message <?php echo $success ? 'success' : 'error'; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <?php if (!$success): ?>
            <form method="POST">
                <div class="form-group full-width">
                    <label>Full Name <span class="required">*</span></label>
                    <input type="text" name="full_name" required placeholder="John Doe"
                        value="<?php echo htmlspecialchars($_POST['full_name'] ?? 'Admin User'); ?>">
                </div>

                <div class="form-group full-width">
                    <label>Email Address <span class="required">*</span></label>
                    <input type="email" name="email" required placeholder="admin@oakshirefinance.com"
                        value="<?php echo htmlspecialchars($_POST['email'] ?? 'admin@oakshirefinance.com'); ?>">
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Phone Number <span class="required">*</span></label>
                        <input type="tel" name="phone" required placeholder="+1234567890"
                            value="<?php echo htmlspecialchars($_POST['phone'] ?? '+1234567890'); ?>">
                    </div>

                    <div class="form-group">
                        <label>Age</label>
                        <input type="number" name="age" min="18" max="100"
                            value="<?php echo htmlspecialchars($_POST['age'] ?? '30'); ?>">
                    </div>
                </div>

                <div class="form-group full-width">
                    <label>Address <span class="required">*</span></label>
                    <textarea name="address" required
                        placeholder="123 Main St, City, Country"><?php echo htmlspecialchars($_POST['address'] ?? '123 Admin Street, City'); ?></textarea>
                </div>

                <div class="form-group full-width">
                    <label>Occupation</label>
                    <input type="text" name="occupation" placeholder="System Administrator"
                        value="<?php echo htmlspecialchars($_POST['occupation'] ?? 'System Administrator'); ?>">
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Password <span class="required">*</span></label>
                        <input type="password" name="password" required placeholder="Min. 8 characters" minlength="8">
                        <div class="note">At least 8 characters</div>
                    </div>

                    <div class="form-group">
                        <label>Confirm Password <span class="required">*</span></label>
                        <input type="password" name="confirm_password" required placeholder="Re-enter password"
                            minlength="8">
                    </div>
                </div>

                <button type="submit">🚀 Create Admin Account</button>
            </form>

            <div class="login-info">
                <strong>📌 After creation, you can log in with:</strong><br>
                • Email: (the email you entered)<br>
                • Password: (the password you set)<br>
                • Status: Auto-approved with admin privileges
            </div>
        <?php endif; ?>

        <div class="warning">
            ⚠️ <strong>SECURITY WARNING:</strong> Delete this file (create_admin.php) immediately after creating your
            admin account!
        </div>

        <?php if ($success): ?>
            <div style="text-align: center; margin-top: 20px;">
                <a href="login.php" style="color: #1e3c72; font-weight: bold;">→ Go to Login Page ←</a>
            </div>
        <?php endif; ?>
    </div>
</body>

</html>