<?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__ . '/unified_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;
}

// ---------- Validate required input ----------
$userId = $data['user_id'] ?? 0;
$accountTypeId = $data['account_type_id'] ?? 0;
$mainPassword = $data['mainPassword'] ?? '';
$investPassword = $data['investPassword'] ?? '';

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

// ---------- Validate passwords ----------
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 from DB ----------
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']; // MT5 expects single backslash
    $leverage = (int)$accountType['ac_max_leverage'];
    $accountTypeName = $accountType['ac_name']; // ✅ Added: store account type name

} catch (Exception $e) {
    echo json_encode(['success'=>false, 'error'=>'Failed to fetch account type', 'details'=>$e->getMessage()]);
    exit;
}

// ---------- Fetch IB chain and email + first_name/last_name for user ----------
$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 = ''; // optional
$user->Leverage = $leverage;
$user->Currency = 'USD';

// ✅ Store first_name + last_name in MT5 user
$user->Name = trim($firstName . ' ' . $lastName);
$user->Rights = MTEnUsersRights::USER_RIGHT_ENABLED;

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

if ($ret === MTRetCode::MT_RET_OK) {
    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,'PrimewaveFX',: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);
        $params = [
            ':user_id'=>$userId,
            ':email'=>$email,
            ':trade_id'=>$new_user->Login ?? '',
            ':account_type'=>$accountTypeName, // ✅ Store account type name
            ':account_name'=>trim($firstName . ' ' . $lastName),
            ':leverage'=>$leverage,
            ':currency'=>'USD',
            ':trader_pwd'=>$mainPassword,
            ':invester_pwd'=>$investPassword,
            ':phone_pwd'=>'',
        ];
        for ($i=1;$i<=10;$i++) $params[":ib$i"] = $ibChain["ib$i"];

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

        // ------------------
        // Send live account opening email
        // ------------------
        if (EMAIL_AUTOMATION_ENABLED) {
            $mailSystem = getMailSystem();
            $fullName = trim($firstName . ' ' . $lastName);
            $accountId = $new_user->Login ?? 'N/A';
            
            $emailResult = $mailSystem->sendLiveAccountOpened(
                $email, 
                $fullName, 
                $accountId, 
                $accountTypeName, 
                $leverage, 
                'USD'
            );
            
            // Log email result
            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 on MT5 and saved in DB',
            '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 $cleanupEx){ }
        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 (MT5 rules)";
    echo json_encode(['success'=>false,'error'=>'Failed to create account on MT5','details'=>$ret,'message'=>$errorMessage]);
    exit;
}
?>
