<?php
ob_start();
session_start();

require '../includes/db.php';
require '../includes/functions.php';

include 'includes/header.php'; 
include 'includes/sidebar.php';

// ?? Protect page (admin only)
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

// ?? Generate referral code
function generateRefCode($length = 8) {
    return substr(str_shuffle("ABCDEFGH123456789XYZ"), 0, $length);
}

$error = "";
$success = "";

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

    $customer_id = mysqli_real_escape_string($conn, $_POST['customer_id']);
    $plain_password = $_POST['password'];
    $currency = mysqli_real_escape_string($conn, $_POST['currency']);
    $referral = mysqli_real_escape_string($conn, $_POST['referral'] ?? '');

    // ?? Validate password
    if (strlen($plain_password) < 6) {
        $error = "? Password must be at least 6 characters.";
    } else {

        $password = password_hash($plain_password, PASSWORD_DEFAULT);

        // ?? Generate referral code
        $myRefCode = generateRefCode();

        // ?? Validate referral
        $validRef = NULL;
        if (!empty($referral)) {
            $refCheck = mysqli_query($conn, "
                SELECT referral_code FROM users 
                WHERE referral_code='$referral'
            ");
            if (mysqli_num_rows($refCheck)) {
                $validRef = $referral;
            }
        }

        // ? INSERT USER (NO PASSWORD HERE)
        $insertUser = mysqli_query($conn, "
            INSERT INTO users (customer_id, currency, referral_code, referred_by)
            VALUES ('$customer_id', '$currency', '$myRefCode', '$validRef')
        ");

        if ($insertUser) {

            $user_id = mysqli_insert_id($conn);

            // ? INSERT PASSWORD INTO NEW SYSTEM
            $insertPass = mysqli_query($conn, "
                INSERT INTO user_passwords (user_id, password_hash)
                VALUES ('$user_id', '$password')
            ");

            if ($insertPass) {
                $success = "? User created successfully!";
            } else {
                $error = "? Failed to save password.";
            }

        } else {
            $error = "? Failed to create user.";
        }
    }
}
?>

<div class="container mt-5">
    <div class="col-md-5 mx-auto">

        <div class="card p-4">

            <h4 class="text-center text-primary mb-4">👨‍💼 Admin Create User</h4>

            <?php if($error): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
            <?php endif; ?>

            <?php if($success): ?>
                <div class="alert alert-success"><?php echo $success; ?></div>
            <?php endif; ?>

            <form method="POST">

                <!-- Customer ID -->
                <div class="mb-3">
                    <label>Customer ID</label>
                    <input type="text" name="customer_id" class="form-control" required>
                </div>

                <!-- Password -->
                <div class="mb-3">
                    <label>Password</label>
                    <input type="text" name="password" class="form-control" required>
                </div>

                <!-- Currency -->
                <div class="mb-3">
                    <label>Currency</label>
                    <select name="currency" class="form-control">
    <option value="USD">USD - US Dollar</option>
    <option value="EUR">EUR - Euro</option>
    <option value="GBP">GBP - British Pound</option>
    <option value="ZAR">ZAR - South African Rand</option>
    <option value="NGN">NGN - Nigerian Naira</option>
    <option value="KES">KES - Kenyan Shilling</option>
    <option value="GHS">GHS - Ghanaian Cedi</option>
    <option value="INR">INR - Indian Rupee</option>
    <option value="AUD">AUD - Australian Dollar</option>
    <option value="CAD">CAD - Canadian Dollar</option>
    <option value="JPY">JPY - Japanese Yen</option>
    <option value="CNY">CNY - Chinese Yuan</option>
    <option value="AED">AED - UAE Dirham</option>
    <option value="SAR">SAR - Saudi Riyal</option>
    <option value="CHF">CHF - Swiss Franc</option>
    <option value="SEK">SEK - Swedish Krona</option>
    <option value="NOK">NOK - Norwegian Krone</option>
    <option value="DKK">DKK - Danish Krone</option>
    <option value="BRL">BRL - Brazilian Real</option>
    <option value="MXN">MXN - Mexican Peso</option>
    <option value="RUB">RUB - Russian Ruble</option>
    <option value="TRY">TRY - Turkish Lira</option>
    <option value="KRW">KRW - South Korean Won</option>
    <option value="HKD">HKD - Hong Kong Dollar</option>
    <option value="SGD">SGD - Singapore Dollar</option>
    <option value="THB">THB - Thai Baht</option>
    <option value="MYR">MYR - Malaysian Ringgit</option>
    <option value="IDR">IDR - Indonesian Rupiah</option>
    <option value="PKR">PKR - Pakistani Rupee</option>
    <option value="EGP">EGP - Egyptian Pound</option>
    <option value="MAD">MAD - Moroccan Dirham</option>
    <option value="TND">TND - Tunisian Dinar</option>
</select>
                </div>

                <!-- Referral -->
                <div class="mb-3">
                    <label>Referral Code (Optional)</label>
                    <input type="text" name="referral" class="form-control">
                </div>

                <button class="btn btn-primary w-100">
                    Create User
                </button>

            </form>

        </div>

    </div>
</div>

