<?php
require_once "/var/www/html/config.database.php";
ini_set("display_errors",1);
error_reporting(E_ALL);

header("Content-Type: application/json");
header("Cache-Control: no-cache, no-store");

// ------------------------------------------------------
// DB
// ------------------------------------------------------
$mysqli = new mysqli(FXH_DB_HOST, FXH_DB_USER, FXH_DB_PASS, FXH_DB_NAME);
if ($mysqli->connect_errno) {
    echo json_encode(["status"=>"error","message"=>"DB_FAIL"]);
    exit;
}

// ------------------------------------------------------
// INPUT
// ------------------------------------------------------
$key     = trim($_GET["key"] ?? "");
$account = (int)($_GET["account"] ?? 0);
$release = isset($_GET["release"]);

if ($key == "" || $account == 0) {
    echo json_encode(["status"=>"invalid","error"=>"MISSING_PARAMS"]);
    exit;
}

// ------------------------------------------------------
// FETCH LICENSE
// ------------------------------------------------------
$stmt = $mysqli->prepare("
    SELECT user_email, plan, expires_at
    FROM fxh_licenses
    WHERE license_key = ?
    LIMIT 1
");
$stmt->bind_param("s", $key);
$stmt->execute();
$lic = $stmt->get_result()->fetch_assoc();

if (!$lic) {
    echo json_encode(["status"=>"invalid","error"=>"NOT_FOUND"]);
    exit;
}

$email = $lic['user_email'];
$plan  = strtoupper($lic['plan']);

if (!empty($lic['expires_at']) && strtotime($lic['expires_at']) < time()) {
    echo json_encode(["status"=>"expired"]);
    exit;
}

// ------------------------------------------------------
// PLAN LIMITS
// ------------------------------------------------------
$max = 1;
if ($plan == "SILVER")  $max = 3;
if ($plan == "GOLD")    $max = 10;
if ($plan == "DIAMOND") $max = 10;

// ------------------------------------------------------
// RELEASE (Option A = instant release)
// ------------------------------------------------------
if ($release) {

    $stmt = $mysqli->prepare("
        DELETE FROM fxh_license_activations
        WHERE license_key=? AND mt5_account=?
    ");
    $stmt->bind_param("si", $key, $account);
    $stmt->execute();

    $stmt = $mysqli->prepare("
        UPDATE fxh_licenses
        SET mt5_account = 0, active = 0
        WHERE license_key=? AND mt5_account=?
    ");
    $stmt->bind_param("si", $key, $account);
    $stmt->execute();

    echo json_encode(["status"=>"released"]);
    exit;
}

// ------------------------------------------------------
// CHECK ACTIVE SESSION FOR THIS KEY
// ------------------------------------------------------
$stmt = $mysqli->prepare("
    SELECT mt5_account
    FROM fxh_license_activations
    WHERE license_key = ?
    LIMIT 1
");
$stmt->bind_param("s", $key);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();

// CASE 1 — same key active but on another MT5
if ($row && (int)$row['mt5_account'] !== $account) {
    echo json_encode([
        "status"      => "locked",
        "mt5_account" => $row['mt5_account']
    ]);
    exit;
}

// CASE 2 — same key heartbeat
if ($row && (int)$row['mt5_account'] === $account) {

    $stmt = $mysqli->prepare("
        UPDATE fxh_license_activations
        SET last_seen = NOW()
        WHERE license_key=? AND mt5_account=?
    ");
    $stmt->bind_param("si", $key, $account);
    $stmt->execute();
}

// CASE 3 — NEW ACTIVATION
if (!$row) {

    // Count ACTUAL plan usage based on PLAN
    $stmt = $mysqli->prepare("
        SELECT COUNT(*) AS used
        FROM fxh_license_activations la
        JOIN fxh_licenses l ON la.license_key = l.license_key
        WHERE l.user_email = ?
        AND l.plan = ?
    ");
    $stmt->bind_param("ss", $email, $plan);
    $stmt->execute();
    $used = (int)$stmt->get_result()->fetch_assoc()['used'];

    if ($used >= $max) {
        echo json_encode([
            "status" => "limit",
            "used"   => $used,
            "max"    => $max
        ]);
        exit;
    }

    // Register activation
    $stmt = $mysqli->prepare("
        INSERT INTO fxh_license_activations(license_key, mt5_account, last_seen)
        VALUES (?, ?, NOW())
    ");
    $stmt->bind_param("si", $key, $account);
    $stmt->execute();

    $stmt = $mysqli->prepare("
        UPDATE fxh_licenses SET active=1 WHERE license_key=?
    ");
    $stmt->bind_param("s", $key);
    $stmt->execute();
}

// ------------------------------------------------------
// SYNC LICENSE → server binding
// ------------------------------------------------------
$stmt = $mysqli->prepare("
    UPDATE fxh_licenses
    SET mt5_account = ?
    WHERE license_key = ?
");
$stmt->bind_param("is", $account, $key);
$stmt->execute();

// ------------------------------------------------------
// FINAL PLAN-BASED SEAT COUNT
// ------------------------------------------------------
$stmt = $mysqli->prepare("
    SELECT COUNT(*) AS used
    FROM fxh_license_activations la
    JOIN fxh_licenses l ON la.license_key = l.license_key
    WHERE l.user_email = ?
    AND l.plan = ?
");
$stmt->bind_param("ss", $email, $plan);
$stmt->execute();
$used = (int)$stmt->get_result()->fetch_assoc()['used'];

// ------------------------------------------------------
// RESPONSE
// ------------------------------------------------------
echo json_encode([
    "status"      => "active",
    "plan"        => $plan,
    "expires_at"  => $lic['expires_at'],
    "used"        => $used,
    "max"         => $max,
    "mt5_account" => $account,
    "file"        => "latest_signal_$key.txt",
    "time"        => gmdate("Y-m-d H:i:s")
]);
exit;
?>
