<?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['id'], $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; $hasKyc = false; $hasCur = 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) {}
    try { $c3 = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_currency'"); $hasCur = $c3 && $c3->rowCount() > 0; } catch (Exception $e) {}
    try { $cols = $pdo->query("SHOW COLUMNS FROM users"); if ($cols) { while ($c = $cols->fetch(PDO::FETCH_ASSOC)) { if (strtolower($c['Field'] ?? '') === 'kycstatus') { $hasKyc = true; break; } } } } catch (Exception $e) {}

    // If updating account_number, enforce uniqueness
    if ($hasAcc && isset($data['account_number']) && $data['account_number'] !== '') {
        $chk = $pdo->prepare('SELECT id FROM users WHERE account_number = ? AND id != ? LIMIT 1');
        $chk->execute([$data['account_number'], $data['id']]);
        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;
        }

    // Ensure user_profiles.account_currency mirrors users.account_currency when provided
    if (array_key_exists('account_currency', $data)) {
        try {
            $pdo->exec("CREATE TABLE IF NOT EXISTS user_profiles (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                first_name VARCHAR(100) NULL,
                last_name VARCHAR(100) NULL,
                address1 VARCHAR(200) NULL,
                address2 VARCHAR(200) NULL,
                city VARCHAR(100) NULL,
                state VARCHAR(100) NULL,
                zip VARCHAR(40) NULL,
                phone VARCHAR(40) NULL,
                dob DATE NULL,
                country VARCHAR(100) NULL,
                gender VARCHAR(20) NULL,
                account_currency VARCHAR(10) NULL,
                account_type VARCHAR(100) NULL,
                account_photo_path VARCHAR(255) NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX (user_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

            // Ensure account_currency column exists on user_profiles
            try {
                $c = $pdo->query("SHOW COLUMNS FROM user_profiles LIKE 'account_currency'");
                if (!$c || $c->rowCount() === 0) {
                    $pdo->exec("ALTER TABLE user_profiles ADD COLUMN account_currency VARCHAR(10) NULL");
                }
            } catch (Exception $e) { /* ignore */ }

            $cur = isset($data['account_currency']) && $data['account_currency'] !== ''
                ? strtoupper(trim($data['account_currency']))
                : null;
            $up = $pdo->prepare("UPDATE user_profiles SET account_currency = ? WHERE user_id = ?");
            $up->execute([$cur, $data['id']]);
            if ($up->rowCount() === 0) {
                $ins = $pdo->prepare("INSERT INTO user_profiles (user_id, account_currency) VALUES (?, ?)");
                $ins->execute([$data['id'], $cur]);
            }
        } catch (Exception $e) { /* ignore fallback issues for currency */ }
    }
    }

    $fields = ['username = ?','name = ?','email = ?','status = ?','balance = ?'];
    $params = [
        $data['username'],
        $data['name'],
        $data['email'],
        $data['status'],
        $data['balance'] ?? 0,
    ];
    if ($hasKyc) { $fields[] = 'kycStatus = ?'; $params[] = $data['kycStatus'] ?? 'pending'; }
    if ($hasCur && array_key_exists('account_currency', $data)) {
        $fields[] = 'account_currency = ?';
        $params[] = isset($data['account_currency']) && $data['account_currency'] !== ''
            ? strtoupper(trim($data['account_currency']))
            : null;
    }
    if ($hasPic && array_key_exists('profile_picture', $data)) { $fields[] = 'profile_picture = ?'; $params[] = $data['profile_picture'] ?: null; }
    if ($hasAcc && array_key_exists('account_number', $data)) { $fields[] = 'account_number = ?'; $params[] = $data['account_number'] ?: null; }
    $sql = 'UPDATE users SET ' . implode(', ', $fields) . ' WHERE id = ?';
    $params[] = $data['id'];
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    // Fallback: if users.profile_picture column is missing but profile_picture provided,
    // persist it to user_profiles.account_photo_path (create table if needed)
    if (!$hasPic && array_key_exists('profile_picture', $data)) {
        try {
            $pdo->exec("CREATE TABLE IF NOT EXISTS user_profiles (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                first_name VARCHAR(100) NULL,
                last_name VARCHAR(100) NULL,
                address1 VARCHAR(200) NULL,
                address2 VARCHAR(200) NULL,
                city VARCHAR(100) NULL,
                state VARCHAR(100) NULL,
                zip VARCHAR(40) NULL,
                phone VARCHAR(40) NULL,
                dob DATE NULL,
                country VARCHAR(100) NULL,
                gender VARCHAR(20) NULL,
                account_currency VARCHAR(10) NULL,
                account_type VARCHAR(100) NULL,
                account_photo_path VARCHAR(255) NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX (user_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
            $up = $pdo->prepare("UPDATE user_profiles SET account_photo_path = ? WHERE user_id = ?");
            $up->execute([$data['profile_picture'] ?: null, $data['id']]);
            if ($up->rowCount() === 0) {
                $ins = $pdo->prepare("INSERT INTO user_profiles (user_id, account_photo_path) VALUES (?, ?)");
                $ins->execute([$data['id'], $data['profile_picture'] ?: null]);
            }
        } catch (Exception $e) { /* ignore fallback issues */ }
    }

    echo json_encode(["success" => true]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => $e->getMessage()]);
}
