<?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 OPTIONS preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include_once __DIR__ . "/connection.php";   // DB + MT5 connection
include_once __DIR__ . "/mt5_api/mt5_api.php";
include_once __DIR__ . "/unified_config.php";

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

$trade_id = $data['trade_id'] ?? '';
$action   = $data['action'] ?? 'fetch';   // default is fetch
$new_pass = $data['new_password'] ?? '';

if (!$trade_id) {
    echo json_encode(["success" => false, "error" => "Missing trade_id"]);
    exit;
}

// ✅ 1. Fetch current passwords from DB
$stmt = $conn->prepare("SELECT trader_pwd, invester_pwd, phone_pwd FROM liveaccounts WHERE trade_id=? LIMIT 1");
$stmt->bind_param("s", $trade_id);
$stmt->execute();
$res = $stmt->get_result();
$account = $res->fetch_assoc();

if (!$account) {
    echo json_encode(["success" => false, "error" => "Trade ID not found"]);
    exit;
}

// ✅ If action is just fetch → return current passwords
if ($action === "fetch") {
    echo json_encode([
        "success" => true,
        "trade_id" => $trade_id,
        "passwords" => $account
    ]);
    exit;
}

// ✅ 2. If action is update → Connect to MT5
$api = new MTWebAPI("ChangePassAPI", "./logs", true);
$ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
if ($ret != MTRetCode::MT_RET_OK) {
    echo json_encode(["success" => false, "error" => "MT5 connection failed", "code" => $ret]);
    exit;
}

// ✅ Decide which password type to change
switch ($action) {
    case "mainPassword":
        $type = MTProtocolConsts::WEB_VAL_USER_PASS_MAIN;
        $db_field = "trader_pwd";
        break;

    case "investPassword":
        $type = MTProtocolConsts::WEB_VAL_USER_PASS_INVESTOR;
        $db_field = "invester_pwd";
        break;

    case "phonePassword":
        $type = MTProtocolConsts::WEB_VAL_USER_PASS_PHONE;
        $db_field = "phone_pwd";
        break;

    default:
        $api->Disconnect();
        echo json_encode(["success" => false, "error" => "Invalid action"]);
        exit;
}

// ✅ Update MT5 password using correct method
$retUpdate = $api->UserPasswordChange(intval($trade_id), $new_pass, $type);
$api->Disconnect();

if ($retUpdate != MTRetCode::MT_RET_OK) {
    echo json_encode([
        "success" => false,
        "error" => "MT5 password update failed",
        "code" => $retUpdate
    ]);
    exit;
}

// ✅ Update DB only if MT5 update succeeds
$stmt = $conn->prepare("UPDATE liveaccounts SET $db_field=? WHERE trade_id=?");
$stmt->bind_param("ss", $new_pass, $trade_id);
$stmt->execute();

// ------------------
// Send password change notification email
// ------------------
$emailSent = false;
if (EMAIL_AUTOMATION_ENABLED) {
    // Get user details for email
    $userStmt = $conn->prepare("
        SELECT lu.email, lu.first_name, lu.last_name 
        FROM liveaccounts la 
        JOIN loginusers lu ON lu.id = la.user_id 
        WHERE la.trade_id = ?
    ");
    $userStmt->bind_param("s", $trade_id);
    $userStmt->execute();
    $userResult = $userStmt->get_result();
    
    if ($userDetails = $userResult->fetch_assoc()) {
        $fullName = trim($userDetails['first_name'] . ' ' . $userDetails['last_name']);
        
        $mailSystem = getMailSystem();
        $emailResult = $mailSystem->sendPasswordChanged(
            $userDetails['email'], 
            $fullName, 
            $_SERVER['REMOTE_ADDR'] ?? 'Unknown'
        );
        
        $emailSent = $emailResult['success'];
        
        // Log email result
        if (!$emailResult['success']) {
            error_log("Failed to send password change email to " . $userDetails['email'] . ": " . $emailResult['message']);
        }
    }
    $userStmt->close();
}

echo json_encode([
    "success" => true,
    "message" => "Password updated successfully",
    "trade_id" => $trade_id,
    "action" => $action,
    "email_sent" => $emailSent
]);
?>
