<?php
define("FXH_PORTAL", true);

require_once __DIR__ . "/config.php";
require_once __DIR__ . "/middleware/user_auth.php";

/* ===============================
   LOAD PAID ORDER (NO INSERT!)
================================ */

$order_id = intval($_GET['order'] ?? 0);

if (!$order_id) {
    header("Location: /portal/plans.php");
    exit;
}

$stmt = $conn->prepare("
    SELECT *
    FROM fxh_orders
    WHERE id = ? AND payment_status = 'PAID'
    LIMIT 1
");
$stmt->bind_param("i", $order_id);
$stmt->execute();
$res = $stmt->get_result();

if (!$res || !$res->num_rows) {
    fxh_set_flash("Invalid or unpaid order.");
    header("Location: /portal/plans.php");
    exit;
}

$order = $res->fetch_assoc();

/* ===============================
   GENERATE LICENSE KEYS
   + CREATE SIGNAL FILES
================================ */

$total_keys = intval($order['licenses']);
$license_keys = [];

$signal_dir = "/var/www/html/webhook/signals/";

if (!is_dir($signal_dir)) {
    mkdir($signal_dir, 0775, true);
}

for ($i = 0; $i < $total_keys; $i++) {

    // ---------- UNIQUE 16 DIGIT KEY ----------
    do {
        $key = fxh_generate_license_key();

        $chk = $conn->prepare("
            SELECT 1 FROM fxh_licenses 
            WHERE license_key = ? 
            LIMIT 1
        ");
        $chk->bind_param("s", $key);
        $chk->execute();
        $chk->store_result();

    } while ($chk->num_rows > 0);

    // ---------- EXPIRY ----------
    if (strtoupper($order['term']) === "LIFETIME") {
        $expires_at = NULL;
    } else {
        $expires_at = date("Y-m-d H:i:s", strtotime("+30 days"));
    }

    // ---------- INSERT INTO fxh_licenses ----------
    $ins = $conn->prepare("
        INSERT INTO fxh_licenses
            (license_key, order_id, plan, user_email, mt5_account, active, created_at, expires_at)
        VALUES
            (?, ?, ?, ?, 0, 1, NOW(), ?)
    ");

    $ins->bind_param(
        "sisss",
        $key,
        $order['id'],
        $order['plan'],
        $_SESSION['email'],
        $expires_at
    );

    $ins->execute();

    // ---------- CREATE SIGNAL FILE ----------
    $signal_file = $signal_dir . "latest_signal_{$key}.txt";

    file_put_contents(
        $signal_file,
        json_encode([
            "action" => "IDLE",
            "time"   => date("Y-m-d H:i:s")
        ])
    );

    chmod($signal_file, 0664);

    $license_keys[] = $key;
}

/* ===============================
   UI
================================ */

require_once __DIR__ . "/user/includes/header.php";
require_once __DIR__ . "/user/includes/sidebar.php";
?>

<style>
.fxh-box{
    max-width:820px;
    background:#0a101c;
    margin:30px auto;
    padding:36px;
    border-radius:22px;
    border:1px solid rgba(0,234,255,.25);
    box-shadow:0 0 28px rgba(0,234,255,.20);
}

.fxh-title{
    color:#00ff9c;
    text-align:center;
    letter-spacing:2px;
}

.fxh-table{
    width:100%;
    margin-top:22px;
    border-collapse:collapse;
}

.fxh-table th{
    text-align:left;
    color:#00eaff;
    padding:8px 0;
}

.fxh-table td{
    text-align:right;
    padding:8px 0;
    color:#fff;
}

.fxh-table tr{
    border-bottom:1px solid rgba(255,255,255,.08);
}

.paid{
    color:#00ff9c;
    font-weight:bold;
}

.keys-box{
    margin-top:26px;
    padding:16px;
    border-radius:18px;
    border:1px solid #ffd15c;
    background:#070b12;
}

.key{
    color:#ffd15c;
    font-size:18px;
    letter-spacing:3px;
    padding:6px;
    text-align:center;
    cursor:pointer;
}

.key:hover{
    text-shadow:0 0 12px gold;
}

.btn-neon{
    display:block;
    margin:28px auto 0;
    width:320px;
    text-align:center;
    padding:14px;
    border-radius:18px;
    color:#fff;
    font-weight:700;
    text-decoration:none;
    background:linear-gradient(90deg,#00eaff,#7a35ff);
    box-shadow:0 0 18px rgba(0,234,255,.5);
}

.btn-neon:hover{
    box-shadow:0 0 32px rgba(0,234,255,.9);
}
</style>

<div class="fxh-main">

<div class="fxh-box">

<h2 class="fxh-title">✅ PAYMENT SUCCESSFUL</h2>
<p style="text-align:center;opacity:.8">
Your crypto payment has been confirmed successfully.
</p>

<table class="fxh-table">
<tr><th>PLAN</th><td><?= htmlspecialchars($order['plan']) ?></td></tr>
<tr><th>PRICE</th><td>$<?= number_format($order['amount'],2) ?></td></tr>
<tr><th>TERMINALS</th><td><?= intval($order['licenses']) ?></td></tr>
<tr><th>VALIDITY</th><td><?= htmlspecialchars($order['term']) ?></td></tr>
<tr><th>STATUS</th><td class="paid"><?= htmlspecialchars($order['payment_status']) ?></td></tr>
<tr><th>ORDER ID</th><td>#<?= intval($order['id']) ?></td></tr>
</table>

<div class="keys-box">
<h3 style="text-align:center">LICENSE KEYS</h3>
<p style="opacity:.6;text-align:center">Click to copy</p>

<?php foreach($license_keys as $k): ?>
    <div class="key"
         onclick="navigator.clipboard.writeText(this.innerText)">
         <?= htmlspecialchars($k) ?>
    </div>
<?php endforeach; ?>

</div>

<a class="btn-neon" href="/portal/user/dashboard.php">
➡ CONTINUE TO DASHBOARD
</a>

</div>
</div>

<?php require_once __DIR__ . "/user/includes/footer.php"; ?>
