<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

require_once __DIR__ . "/../includes/admin_auth.php"; // Must be first
require_once '../includes/db.php';
require_once '../includes/mailer.php';
require_once '../includes/functions.php';

$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $first_name = trim($_POST['first_name']);
    $last_name  = trim($_POST['last_name']);
    $email      = trim($_POST['email']);
    $phone      = trim($_POST['phone']);

    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    $address = $_POST['address'];
    $city    = $_POST['city'];
    $state   = $_POST['state'];
    $zip_code = $_POST['zip_code'];
    $country  = $_POST['country'];

    $account_type = $_POST['account_type'];
    $currency     = $_POST['currency'];

    // =========================
    // VALIDATION
    // =========================
    if ($password !== $confirm_password) {
        $message = "Passwords do not match!";
    } else {

        // =========================
        // CHECK DUPLICATE EMAIL
        // =========================
        $check = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $check->bind_param("s", $email);
        $check->execute();
        $check->store_result();

        if ($check->num_rows > 0) {

            $message = "Error: Email already exists!";

        } else {

            $hashed_password = password_hash($password, PASSWORD_BCRYPT);

            // =========================
            // PROFILE PHOTO
            // =========================
            $profile_photo = "default_profile.png";

            if (!empty($_FILES['profile_photo']['name'])) {

                $targetDir = "../uploads/profile_photos/";

                if (!is_dir($targetDir)) {
                    mkdir($targetDir, 0777, true);
                }

                $fileName = time() . "_" . basename($_FILES["profile_photo"]["name"]);
                move_uploaded_file($_FILES["profile_photo"]["tmp_name"], $targetDir . $fileName);

                $profile_photo = $fileName;
            }

            // =========================
            // INSERT USER
            // =========================
            $stmt = $conn->prepare("
                INSERT INTO users 
                (first_name, last_name, email, phone, password, address, city, state, zip_code, country, profile_photo, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')
            ");

            $stmt->bind_param(
                "sssssssssss",
                $first_name,
                $last_name,
                $email,
                $phone,
                $hashed_password,
                $address,
                $city,
                $state,
                $zip_code,
                $country,
                $profile_photo
            );

            $stmt->execute();

            $user_id = $conn->insert_id;

            // =========================
            // CREATE ACCOUNT
            // =========================
            $account_number = generateAccountNumber($conn);

            createAccountForUser(
                $conn,
                $user_id,
                $account_type,
                $currency,
                $account_number
            );

            // =========================
            // SEND EMAIL (FIXED - USE PROPER FUNCTION)
            // =========================

            $temp_password = $password;

            if (function_exists('sendAccountCreatedEmail')) {
                sendAccountCreatedEmail(
                    $email,
                    $first_name . " " . $last_name,
                    $account_number,
                    $temp_password
                );
            }

            $message = "User created successfully!";
        }
    }
}

ob_start();
?>

<div class="main-content">

    <h2 class="page-title">Create User</h2>

    <?php if ($message): ?>
        <div class="alert"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data" class="panel">

        <h3>Personal Information</h3>

        <input type="text" name="first_name" placeholder="First Name" required>
        <input type="text" name="last_name" placeholder="Last Name" required>
        <input type="email" name="email" placeholder="Email" required>
        <input type="text" name="phone" placeholder="Phone" required>

        <h3>Security</h3>

        <input type="password" name="password" placeholder="Password" required>
        <input type="password" name="confirm_password" placeholder="Confirm Password" required>

        <h3>Address</h3>

        <input type="text" name="address" placeholder="Address">
        <input type="text" name="city" placeholder="City">
        <input type="text" name="state" placeholder="State">
        <input type="text" name="zip_code" placeholder="Zip Code">
        <input type="text" name="country" placeholder="Country">

        <h3>Account Settings</h3>

        <select name="account_type" required>
            <option value="savings">Savings</option>
            <option value="current">Current</option>
            <option value="business">Business</option>
        </select>

        <select name="currency" required>
            <option value="USD">USD ($)</option>
            <option value="EUR">EUR (€)</option>
            <option value="GBP">GBP (£)</option>
            <option value="NGN">NGN (₦)</option>
            <option value="CAD">CAD ($)</option>
            <option value="AUD">AUD ($)</option>
            <option value="JPY">JPY (¥)</option>
            <option value="CNY">CNY (¥)</option>
            <option value="CHF">CHF</option>
            <option value="ZAR">ZAR</option>
        </select>

        <h3>Profile Photo</h3>

        <input type="file" name="profile_photo">

        <button type="submit" class="btn">Create User</button>

    </form>

</div>

<?php
$content = ob_get_clean();
$page_title = "Create User";
include '../components/admin_layout.php';
?>