<?php
// liveaccount.php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || !is_array($data)) {
    echo json_encode([
        'success' => false,
        'error' => 'No input data received or invalid JSON',
        'raw' => $input
    ]);
    exit;
}

// ---------- Include DB config and MT5 connection ----------
require_once __DIR__ . '/config.php';       // DB connection constants
require_once __DIR__ . '/connection.php';   // MT5 API connection

// ---------- Create PDO connection ----------
try {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $dbh = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
} catch (Exception $ex) {
    echo json_encode([
        'success' => false,
        'error' => 'DB connection failed',
        'details' => $ex->getMessage()
    ]);
    exit;
}

// ---------- Map incoming fields ----------
$group          = $data['group'] ?? '';
$name           = $data['account_name'] ?? $data['name'] ?? '';
$leverage       = $data['leverage'] ?? 0;
$currency       = $data['currency'] ?? 'USD';
$mainPassword   = $data['trader_pwd'] ?? $data['mainPassword'] ?? '';
$investPassword = $data['invester_pwd'] ?? $data['investPassword'] ?? '';
$phonePassword  = $data['phone_pwd'] ?? $data['phonePassword'] ?? '';
$userId         = $data['user_id'] ?? 0; // 🔑 new: store logged-in user's ID

// ---------- Validate required fields ----------
if (empty($group) || empty($name) || empty($mainPassword) || empty($userId)) {
    echo json_encode(['success' => false, 'error' => 'Missing required fields (group/name/password/user_id)']);
    exit;
}

// ---------- Connect to MT5 ----------
try {
    $mt5 = new MTWebAPI();
    $ret = $mt5->Connect(
        MT5_SERVER_IP,
        MT5_SERVER_PORT,
        MT5_TIMEOUT,
        MT5_SERVER_WEB_LOGIN,
        MT5_SERVER_WEB_PASSWORD
    );

    if ($ret !== MTRetCode::MT_RET_OK) {
        echo json_encode(['success' => false, 'error' => 'Failed to connect to MT5', 'details' => $ret]);
        exit;
    }
} catch (Exception $ex) {
    echo json_encode(['success' => false, 'error' => 'MT5 connection exception', 'details' => $ex->getMessage()]);
    exit;
}

// ---------- Create MT5 user ----------
$user = new MTUser();
$user->Group          = $group;
$user->MainPassword   = $mainPassword;
$user->InvestPassword = $investPassword;
$user->PhonePassword  = $phonePassword;
$user->Leverage       = (int)$leverage;
$user->Currency       = $currency;
$user->Name           = $name;
$user->Rights         = MTEnUsersRights::USER_RIGHT_ENABLED;

// ---------- Add user via MT5 API ----------
$new_user = null;
$ret = $mt5->UserAdd($user, $new_user);

// ---------- Handle result ----------
if ($ret === MTRetCode::MT_RET_OK) {
    try {
        // Insert into DB with user_id
        $sql = "INSERT INTO liveaccounts 
            (user_id, usercp, trade_id, server, account_type, account_name, leverage, volume, currency, Balance, equity, tradePlatform, trader_pwd, invester_pwd, phone_pwd, status, Registered_Date)
            VALUES (:user_id, '', :trade_id, :server, :account_type, :account_name, :leverage, '0', :currency, 0.0000, 0.0000, 'MetaTrader5', :trader_pwd, :invester_pwd, :phone_pwd, 'active', NOW())";

        $stmt = $dbh->prepare($sql);
        $stmt->execute([
            ':user_id'      => $userId,                   // 🔑 link to logged-in user
            ':trade_id'     => $new_user->Login ?? '',
            ':server'       => 'KF Market-Live',
            ':account_type' => $group,
            ':account_name' => $name,
            ':leverage'     => (string)$leverage,
            ':currency'     => $currency,
            ':trader_pwd'   => $mainPassword,
            ':invester_pwd' => $investPassword,
            ':phone_pwd'    => $phonePassword,
        ]);

        echo json_encode([
            'success' => true,
            'login'   => $new_user->Login ?? null,
            'message' => 'Account created and saved in DB',
        ]);
    } catch (Exception $dbEx) {
        echo json_encode([
            'success'  => true,
            'login'    => $new_user->Login ?? null,
            'warning'  => 'Account created on MT5 but failed to insert in DB',
            'db_error' => $dbEx->getMessage()
        ]);
    }
} else {
    $errorMessage = 'Unknown error: ' . $ret;
    if ($ret == 3) $errorMessage = "Invalid parameters";
    if ($ret == 4) $errorMessage = "User already exists";
    if ($ret == 8) $errorMessage = "Invalid password (MT5 rules)";

    echo json_encode([
        'success' => false,
        'error'   => 'Failed to create account on MT5',
        'details' => $ret,
        'message' => $errorMessage
    ]);
}
