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

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' => 'No input data received or invalid JSON',
        'raw' => $input
    ]);
    exit;
}

require_once __DIR__ . '/unified_config.php';
require_once __DIR__ . '/connection.php';

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

// ---------- Validate required input ----------
$userId = $data['user_id'] ?? 0;
$accountTypeId = $data['account_type_id'] ?? 0;
$mainPassword = $data['mainPassword'] ?? '';
$investPassword = $data['investPassword'] ?? '';
$frontendLeverage = isset($data['leverage']) ? (int)$data['leverage'] : null;

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

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

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 do not meet MT5 rules']);
    exit;
}

// ---------- Fetch account type ----------
try {
    $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'];
    $maxAllowedLeverage = (int)$accountType['ac_max_leverage'];

    $leverage = ($frontendLeverage !== null && $frontendLeverage >= 1 && $frontendLeverage <= $maxAllowedLeverage)
        ? $frontendLeverage : $maxAllowedLeverage;
} catch (Exception $e) {
    echo json_encode(['success'=>false,'error'=>'Failed to fetch account type', 'details'=>$e->getMessage()]);
    exit;
}

// ---------- Fetch user details & IB chain ----------
$ibChain = [];
$email = $firstName = $lastName = '';
try {
    $stmt = $dbh->prepare("SELECT ib1,ib2,ib3,ib4,ib5,ib6,ib7,ib8,ib9,ib10,email,first_name,last_name FROM loginusers WHERE id=:id LIMIT 1");
    $stmt->execute([':id' => $userId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $email = $row['email'] ?? '';
        $firstName = $row['first_name'] ?? '';
        $lastName = $row['last_name'] ?? '';
        for ($i=1; $i<=10; $i++) {
            $ibChain["ib$i"] = $row["ib$i"] ?? 'noIB';
        }
    }
} catch (Exception $e) {
    for ($i=1; $i<=10; $i++) $ibChain["ib$i"] = 'noIB';
}

// ---------- 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 = '';
$user->Leverage = $leverage;
$user->Currency = 'USD';
$user->Name = trim($firstName . ' ' . $lastName);
$user->Rights = MTEnUsersRights::USER_RIGHT_ENABLED;

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

if ($ret === MTRetCode::MT_RET_OK) {
    try {
        $dbh->beginTransaction();

        // Build parameters FIRST (important!)
        $params = [
            ':user_id'      => $userId,
            ':email'        => $email,
            ':trade_id'     => $new_user->Login ?? '',
            ':account_type' => $accountTypeName,
            ':account_name' => trim($firstName . ' ' . $lastName),
            ':leverage'     => $leverage,
            ':currency'     => 'USD',
            ':trader_pwd'   => $mainPassword,
            ':invester_pwd' => $investPassword,
            ':phone_pwd'    => '',
        ];
        // Add IB parameters
        for ($i=1; $i<=10; $i++) {
            $params[":ib$i"] = $ibChain["ib$i"];
        }

        $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,'Majestyfx',:account_type,:account_name,:leverage,'0',:currency,0.0,0.0,'MetaTrader5',:trader_pwd,:invester_pwd,:phone_pwd,'active',NOW(),
             :ib1,:ib2,:ib3,:ib4,:ib5,:ib6,:ib7,:ib8,:ib9,:ib10)";

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

        // // ==================== AUTO $1000 DEPOSIT FOR DEMO ACCOUNTS ====================
        // if ($accountTypeName === 'Demo') {
        //     $deposit_amount = 100000.00;
        //     $comment = 'Initial demo account funding';

        //     // Handle possible future Cent demo accounts
        //     $centMultiplier = (stripos($accountTypeName, 'Cent') !== false) ? 0.01 : 1.0;
        //     $mt5_amount = $deposit_amount / $centMultiplier;

        //     $ticket = null;
        //     $deposit_ret = $mt5->TradeBalance($new_user->Login, MTEnDealAction::DEAL_BALANCE, $mt5_amount, $comment, $ticket);

        //     if ($deposit_ret === MTRetCode::MT_RET_OK) {
        //         // Update Balance & Equity in DB
        //         $upd = $dbh->prepare("UPDATE liveaccounts SET Balance = Balance + ?, equity = equity + ? WHERE trade_id = ?");
        //         $upd->execute([$deposit_amount, $deposit_amount, $new_user->Login]);

        //         // Log in wallet_deposit (optional but recommended)
        //         $wallet_sql = "INSERT INTO wallet_deposit 
        //             (email, trade_id, deposit_amount, deposit_type, company_bank, client_bank, account_number, deposed_date, Status, image, AdminRemark, Js_Admin_Remark_Date)
        //             VALUES (?, ?, ?, 'balance', '', '', 0, NOW(), 1, 'default_image.jpg', 'Auto demo deposit', NOW())";
        //         $wallet_stmt = $dbh->prepare($wallet_sql);
        //         $wallet_stmt->execute([$email, $new_user->Login, $deposit_amount]);
        //     } else {
        //         error_log("Auto demo deposit failed for login {$new_user->Login} | MT5 code: $deposit_ret");
        //     }
        // }
        
        // ==================== CUSTOM DEMO DEPOSIT FEATURE ====================
if ($accountTypeName === 'Demo') {

    // NEW: Read custom deposit amount from frontend
    $userDeposit = isset($data['demo_deposit_amount']) ? floatval($data['demo_deposit_amount']) : 0;

    // If user didn't send amount → fallback to old default 100000
    if ($userDeposit <= 0) {
        $userDeposit = 100000.00;
    }

    $deposit_amount = $userDeposit;
    $comment = 'Initial demo account funding';

    // Handle cent-type demo groups (future safe)
    $centMultiplier = (stripos($accountTypeName, 'Cent') !== false) ? 0.01 : 1.0;
    $mt5_amount = $deposit_amount / $centMultiplier;

    $ticket = null;
    $deposit_ret = $mt5->TradeBalance($new_user->Login, MTEnDealAction::DEAL_BALANCE, $mt5_amount, $comment, $ticket);

    if ($deposit_ret === MTRetCode::MT_RET_OK) {

        // Update Balance & Equity in DB
        $upd = $dbh->prepare("UPDATE liveaccounts SET Balance = Balance + ?, equity = equity + ? WHERE trade_id = ?");
        $upd->execute([$deposit_amount, $deposit_amount, $new_user->Login]);

        // Log in wallet_deposit table
        $wallet_sql = "INSERT INTO wallet_deposit 
            (email, trade_id, deposit_amount, deposit_type, company_bank, client_bank, account_number, deposed_date, Status, image, AdminRemark, Js_Admin_Remark_Date)
            VALUES (?, ?, ?, 'balance', '', '', 0, NOW(), 1, 'default_image.jpg', 'Auto demo deposit', NOW())";
        $wallet_stmt = $dbh->prepare($wallet_sql);
        $wallet_stmt->execute([$email, $new_user->Login, $deposit_amount]);
    } else {
        error_log("Auto demo deposit failed for login {$new_user->Login} | MT5 code: $deposit_ret");
    }
}
// ====================================================================

        // =============================================================================

        $dbh->commit();

        // Send email
        if (EMAIL_AUTOMATION_ENABLED) {
            $mailSystem = getMailSystem();
            $fullName = trim($firstName . ' ' . $lastName);
            $accountId = $new_user->Login ?? 'N/A';
            $extraNote = ($accountTypeName === 'Demo') ? ' (with $1000 virtual balance)' : '';

            $emailResult = $mailSystem->sendLiveAccountOpened(
                $email, $fullName, $accountId,
                $accountTypeName . $extraNote, $leverage, 'USD',
                $mainPassword, $investPassword
            );
            if (!$emailResult['success']) {
                error_log("Failed to send live account email to $email: " . $emailResult['message']);
            }
        }

        echo json_encode([
            'success' => true,
            'login' => $new_user->Login ?? null,
            'insert_id' => $insertId,
            'message' => 'Account created successfully',
            'email_sent' => EMAIL_AUTOMATION_ENABLED
        ]);
        exit;

    } catch (Throwable $dbEx) {
        if ($dbh->inTransaction()) $dbh->rollBack();
        try { if (!empty($new_user->Login)) $mt5->UserDelete($new_user->Login); } catch(Throwable $e){}
        echo json_encode(['success'=>false,'error'=>'DB insert failed after MT5 creation','db_error'=>$dbEx->getMessage()]);
        exit;
    }
} else {
    $errorMessage = 'Unknown error';
    if ($ret==3) $errorMessage="Invalid parameters";
    if ($ret==4) $errorMessage="User already exists";
    if ($ret==8) $errorMessage="Invalid password";
    echo json_encode(['success'=>false,'error'=>'Failed to create account on MT5','details'=>$ret,'message'=>$errorMessage]);
    exit;
}
?>