<?php 
require_once "config.php";
fxh_auth_required();

$db = fxh_db();
$user_email = $_SESSION['fxh_user']['email'];

$rows = $db->prepare("SELECT * FROM fxh_licenses WHERE user_email=? ORDER BY id DESC");
$rows->bind_param("s", $user_email);
$rows->execute();
$res = $rows->get_result();

include "header.php";
?>

<div class="container mt-4">
    <h3>🔑 My Licenses</h3>

    <button class="btn btn-primary mb-3" onclick="createLicense()">Generate License</button>

    <table class="table table-bordered">
        <tr>
            <th>ID</th>
            <th>License</th>
            <th>Plan</th>
            <th>MT5 Account</th>
            <th>Active</th>
            <th>Expires</th>
            <th>Actions</th>
        </tr>

        <?php while ($row = $res->fetch_assoc()): ?>
        <tr>
            <td><?= $row['id'] ?></td>
            <td><?= $row['license_key'] ?></td>
            <td><?= $row['plan'] ?></td>
            <td><?= $row['mt5_account'] ?></td>
            <td><?= $row['active'] ?></td>
            <td><?= $row['expires_at'] ?></td>
            <td>
                <?php if($row['active']==1): ?>
                <button class="btn btn-danger btn-sm" onclick="ban(<?= $row['id'] ?>)">Deactivate</button>
                <?php else: ?>
                —
                <?php endif; ?>
            </td>
        </tr>
        <?php endwhile; ?>
    </table>
</div>

<script>
function createLicense(){
    fetch("api/license_activate.php")
    .then(r=>r.json())
    .then(d=>{
        alert("New License: "+d.license);
        location.reload();
    });
}

function ban(id){
    fetch("api/license_deactivate.php", {
        method: "POST",
        headers: {"Content-Type":"application/x-www-form-urlencoded"},
        body: "id="+id
    })
    .then(r=>r.json())
    .then(()=>location.reload());
}
</script>

<?php include "footer.php"; ?>
