<?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");

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

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

if (!$data || !is_array($data)) {
    echo json_encode(['success' => false, 'error' => 'Invalid or empty JSON']);
    exit;
}

// Include config and MT5 connection
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../connection.php';

// 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;
}

// Required fields
$email = trim($data['email'] ?? '');
$accountTypeId = $data['account_type'] ?? 0;
$leverage = (int)($data['leverage'] ?? 0);
$mainPassword = trim($data['mainPassword'] ?? '');
$investPassword = trim($data['investPassword'] ?? '');

if (!$email || !$accountTypeId || !$leverage || !$mainPassword || !$investPassword) {
    echo json_encode(['success' => false, 'error' => 'Missing required fields']);
    exit;
}

if ($mainPassword === $investPassword) {
    echo json_encode(['success' => false, 'error' => 'Main and investor passwords must be different']);
    exit;
}

// Password rule check
function isValidMT5Password($pwd) {
    return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$/', $pwd);
}

if (!isValidMT5Password($mainPassword) || !isValidMT5Password($investPassword)) {
    echo json_encode(['success' => false, 'error' => 'Passwords must contain upper, lower, and digit (8-15 chars)']);
    exit;
}

// Fetch user info
$stmt = $dbh->prepare("SELECT id, first_name, last_name, ib1,ib2,ib3,ib4,ib5,ib6,ib7,ib8,ib9,ib10 FROM loginusers WHERE email = :email LIMIT 1");
$stmt->execute([':email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode(['success' => false, 'error' => 'User not found for given email']);
    exit;
}

$userId = $user['id'];
$fullName = trim($user['first_name'] . ' ' . $user['last_name']);
$ibChain = [];
for ($i = 1; $i <= 10; $i++) {
    $ibChain["ib$i"] = $user["ib$i"] ?? 'noIB';
}

// Fetch account type
$stmt = $dbh->prepare("SELECT * FROM account_types WHERE ac_index = :id LIMIT 1");
$stmt->execute([':id' => $accountTypeId]);
$accountType = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$accountType) {
    echo json_encode(['success' => false, 'error' => 'Account type not found']);
    exit;
}

$group = $accountType['ac_group'];
$accountTypeName = $accountType['ac_name'];
$maxLeverage = (int)$accountType['ac_max_leverage'];

if ($leverage < 1 || $leverage > $maxLeverage) {
    echo json_encode(['success' => false, 'error' => "Invalid leverage. Must be between 1 and $maxLeverage"]);
    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 $e) {
    echo json_encode(['success' => false, 'error' => 'MT5 connection failed', 'details' => $e->getMessage()]);
    exit;
}

// Create MT5 user
$userObj = new MTUser();
$userObj->Group = $group;
$userObj->MainPassword = $mainPassword;
$userObj->InvestPassword = $investPassword;
$userObj->Leverage = $leverage;
$userObj->Currency = 'USD';
$userObj->Name = $fullName;
$userObj->Rights = MTEnUsersRights::USER_RIGHT_ENABLED;

$new_user = null;
$ret = $mt5->UserAdd($userObj, $new_user);

if ($ret !== MTRetCode::MT_RET_OK) {
    echo json_encode(['success' => false, 'error' => 'Failed to create user on MT5', 'details' => $ret]);
    exit;
}

try {
    $dbh->beginTransaction();

    $sql = "INSERT INTO liveaccounts (
        user_id,email,usercp,trade_id,server,account_type,account_name,leverage,volume,
        currency,Balance,equity,tradePlatform,trader_pwd,invester_pwd,phone_pwd,status,Registered_Date,
        ib1,ib2,ib3,ib4,ib5,ib6,ib7,ib8,ib9,ib10
    ) VALUES (
        :user_id,:email,'',:trade_id,'devilforex',:account_type,:account_name,:leverage,'0',
        'USD',0.0,0.0,'MetaTrader5',:trader_pwd,:invester_pwd,'','active',NOW(),
        :ib1,:ib2,:ib3,:ib4,:ib5,:ib6,:ib7,:ib8,:ib9,:ib10
    )";

    $stmt = $dbh->prepare($sql);
    $params = [
        ':user_id' => $userId,
        ':email' => $email,
        ':trade_id' => $new_user->Login ?? '',
        ':account_type' => $accountTypeName,
        ':account_name' => $fullName,
        ':leverage' => $leverage,
        ':trader_pwd' => $mainPassword,
        ':invester_pwd' => $investPassword,
    ];
    for ($i = 1; $i <= 10; $i++) {
        $params[":ib$i"] = $ibChain["ib$i"];
    }

    $stmt->execute($params);
    $insertId = $dbh->lastInsertId();
    $dbh->commit();

    echo json_encode([
        'success' => true,
        'login' => $new_user->Login ?? null,
        'insert_id' => $insertId,
        'message' => 'Live account created successfully (Admin)'
    ]);
} catch (Throwable $e) {
    if ($dbh->inTransaction()) $dbh->rollBack();
    echo json_encode(['success' => false, 'error' => 'DB insert failed', 'details' => $e->getMessage()]);
}
?>
