<?php
// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once 'config.php';
require_once 'db.php';
require_once __DIR__ . '/auth.php';

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// Enforce admin
requireAdmin(true);

$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['username'], $data['name'], $data['email'], $data['status'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing required fields"]);
    exit;
}

try {
    // Detect optional columns
    $hasAcc = false; $hasPic = false;
    try { $c1 = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_number'"); $hasAcc = $c1 && $c1->rowCount() > 0; } catch (Exception $e) {}
    try { $c2 = $pdo->query("SHOW COLUMNS FROM users LIKE 'profile_picture'"); $hasPic = $c2 && $c2->rowCount() > 0; } catch (Exception $e) {}

    // Generate account_number if column exists and value missing
    $accountNumber = isset($data['account_number']) && $data['account_number'] !== '' ? $data['account_number'] : null;
    if ($hasAcc && $accountNumber) {
        $chk = $pdo->prepare('SELECT id FROM users WHERE account_number = ? LIMIT 1');
        $chk->execute([$accountNumber]);
        if ($chk->fetch(PDO::FETCH_ASSOC)) {
            http_response_code(400);
            echo json_encode(["success" => false, "error" => "Account number already in use by another user"]);
            exit;
        }
    }
    if ($hasAcc && empty($accountNumber)) {
        $attempts = 0;
        do {
            $candidate = str_pad((string)random_int(0, 999999999999), 12, '0', STR_PAD_LEFT);
            $chk = $pdo->prepare('SELECT id FROM users WHERE account_number = ? LIMIT 1');
            $chk->execute([$candidate]);
            $exists = $chk->fetch(PDO::FETCH_ASSOC);
            $attempts++;
        } while ($exists && $attempts < 10);
        $accountNumber = $candidate;
    }

    // Uniqueness checks
    $chkU = $pdo->prepare('SELECT id FROM users WHERE username = ? LIMIT 1');
    $chkU->execute([$data['username']]);
    if ($chkU->fetch(PDO::FETCH_ASSOC)) {
        http_response_code(400);
        echo json_encode(["success" => false, "error" => "Username already exists"]);
        exit;
    }
    $chkE = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
    $chkE->execute([$data['email']]);
    if ($chkE->fetch(PDO::FETCH_ASSOC)) {
        http_response_code(400);
        echo json_encode(["success" => false, "error" => "Email already exists"]);
        exit;
    }

    // Build insert dynamically
    $cols = ['username','name','email','status','kycStatus','balance'];
    $vals = ['?','?','?','?','?','?'];
    $params = [
        $data['username'],
        $data['name'],
        $data['email'],
        $data['status'],
        $data['kycStatus'] ?? 'pending',
        $data['balance'] ?? 0,
    ];
    if ($hasPic) { $cols[]='profile_picture'; $vals[]='?'; $params[] = $data['profile_picture'] ?? null; }
    if ($hasAcc) { $cols[]='account_number'; $vals[]='?'; $params[] = $accountNumber; }

    $sql = 'INSERT INTO users (' . implode(',', $cols) . ') VALUES (' . implode(',', $vals) . ')';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    echo json_encode([
        "success" => true,
        "id" => $pdo->lastInsertId(),
        "account_number" => $hasAcc ? $accountNumber : null
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => $e->getMessage()]);
}
