<?php
header("Access-Control-Allow-Origin: *"); 
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Max-Age: 86400"); 

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once __DIR__ . '/../config.php';        // $conn (mysqli)
require_once __DIR__ . '/../connection.php';    // MT5Connection etc.

// ===== Parse JSON =====
$data = json_decode(file_get_contents("php://input"), true);

// Accept either 'id' or 'request_id'
$id = isset($data['id']) ? intval($data['id']) : (isset($data['request_id']) ? intval($data['request_id']) : null);
$action = strtolower(trim($data['action'] ?? ''));

if (!$id || !in_array($action, ['approve','reject'])) {
    echo json_encode(["status"=>"error","message"=>"Invalid request: provide id and action=approve|reject"]);
    exit;
}

// ===== Fetch investment record safely =====
$stmt = $conn->prepare("SELECT * FROM copyaccounts WHERE id = ? LIMIT 1");
if (!$stmt) {
    exit(json_encode(["status"=>"error","message"=>"DB prepare failed: ".$conn->error]));
}
$stmt->bind_param("i", $id);
$stmt->execute();
$res = $stmt->get_result();
$inv = $res->fetch_assoc();
$stmt->close();

if (!$inv) {
    echo json_encode(["status"=>"error","message"=>"Record not found"]);
    exit;
}

// ensure pending status (0) before processing
if (intval($inv['status']) !== 0) {
    echo json_encode(["status"=>"error","message"=>"Record already processed or not pending", "current_status" => intval($inv['status'])]);
    exit;
}

// ===== Handle Rejection =====
if ($action === 'reject') {
    $stmt = $conn->prepare("UPDATE copyaccounts SET status = ? WHERE id = ?");
    $rej_status = 3; // rejected
    $stmt->bind_param("ii", $rej_status, $id);
    $stmt->execute();
    $stmt->close();
    echo json_encode(["status"=>"rejected","message"=>"Investment request rejected."]);
    exit;
}

// ===== Proceed with Approval =====
$mastertrade = $inv['mastertrade'];
$slavetrade  = $inv['slavetrade'];
$mastername  = $inv['mastername'];
$slavename   = $inv['slavename'];
$email       = $inv['email'];
$volumeselect = isset($inv['volumeselect']) && $inv['volumeselect'] != '' ? $inv['volumeselect'] : 'fixed';
$volume = isset($inv['volume']) && $inv['volume'] != '' ? floatval($inv['volume']) : 1.0;
$copyid = $inv['copyid'];

// ===== Connect to MT5 =====
$mt5 = new MT5Connection();
if (!$mt5->connect()) {
    echo json_encode(["status"=>"error","message"=>"MT5 connection failed: ".$mt5->lastError()]);
    exit;
}

// ===== Fetch MT5 Info for master & slave =====
$masterInfo = $slaveInfo = null;
$masterAccInfo = $slaveAccInfo = null;

if ($mt5->api->UserGet($mastertrade, $masterInfo) !== MTRetCode::MT_RET_OK ||
    $mt5->api->UserAccountGet($mastertrade, $masterAccInfo) !== MTRetCode::MT_RET_OK) {
    echo json_encode(["status"=>"error","message"=>"Failed to fetch master account info"]);
    exit;
}
if ($mt5->api->UserGet($slavetrade, $slaveInfo) !== MTRetCode::MT_RET_OK ||
    $mt5->api->UserAccountGet($slavetrade, $slaveAccInfo) !== MTRetCode::MT_RET_OK) {
    echo json_encode(["status"=>"error","message"=>"Failed to fetch slave account info"]);
    exit;
}

// ===== Insert into tbl_master (main DB) =====
$stmt = $conn->prepare("
    INSERT INTO tbl_master (login, tradeid, name, email, balance, account, leverage)
    VALUES (?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    exit(json_encode(["status"=>"error","message"=>"Master DB prepare failed: ".$conn->error]));
}

$login = MT5_SERVER_WEB_LOGIN;
$tradeid = $mastertrade;
$name = $masterInfo->Name;
$emailAddr = $masterInfo->Email;
$balance = strval($masterInfo->Balance);
$account = $masterInfo->Group;
$leverage = strval($masterInfo->Leverage);

$stmt->bind_param("sssssss", $login, $tradeid, $name, $emailAddr, $balance, $account, $leverage);
if (!$stmt->execute()) {
    exit(json_encode(["status"=>"error","message"=>"Master insert failed: ".$stmt->error]));
}
$stmt->close();

// ===== Insert into tbl_slave (main DB) =====
$stmt = $conn->prepare("
    INSERT INTO tbl_slave (login, mastertrade, slavetrade, name, email, balance, account, leverage)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    exit(json_encode(["status"=>"error","message"=>"Slave DB prepare failed: ".$conn->error]));
}

$login = MT5_SERVER_WEB_LOGIN;
$masterId = $mastertrade;
$slaveId = $slavetrade;
$sName = $slaveInfo->Name;
$sEmail = $slaveInfo->Email;
$sBalance = strval($slaveInfo->Balance);
$sAccount = $slaveInfo->Group;
$sLeverage = strval($slaveInfo->Leverage);

$stmt->bind_param("ssssssss", $login, $masterId, $slaveId, $sName, $sEmail, $sBalance, $sAccount, $sLeverage);
if (!$stmt->execute()) {
    exit(json_encode(["status"=>"error","message"=>"Slave insert failed: ".$stmt->error]));
}
$stmt->close();

// ===== Append to PositionPairs.txt =====
$positionLine = "{$mastertrade},{$slavetrade},{$volumeselect},{$volume}\n";
file_put_contents(__DIR__."/PositionPairs.txt", $positionLine, FILE_APPEND);

// ===== Send POST to Server B =====
try {
    $serverB_url = "https://devilforex.com/trade_copier_newcrm/update_user_txt.php";
    $postData = [
        'mastertradeid' => $mastertrade,
        'slavetradeid' => $slavetrade,
        'volumeselect' => $volumeselect,
        'volume' => $volume
    ];

    $ch = curl_init($serverB_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    $response = curl_exec($ch);
    curl_close($ch);
} catch (Exception $e) {
    file_put_contents("serverB_error.log", $e->getMessage()."\n", FILE_APPEND);
}

// ===== Update Status in copyaccounts =====
$upd = $conn->prepare("UPDATE copyaccounts SET status = ?, executed = ? WHERE id = ?");
$approved_status = 1;
$exec_flag = 1;
$upd->bind_param("iii", $approved_status, $exec_flag, $id);
$upd->execute();
$upd->close();

echo json_encode([
    "status" => "approved",
    "message" => "Investment approved and copied successfully.",
    "master" => $mastertrade,
    "slave" => $slavetrade
]);
?>
