<?php
require_once '../config.php';
session_start();

if(!isset($_SESSION['admin_logged_in'])){
    header("Location: login.php");
    exit;
}

$id = $_GET['id'];

// Fetch license
$license = $conn->query("SELECT * FROM fxh_licenses WHERE id=$id")->fetch_assoc();

// Fetch users list
$users = $conn->query("SELECT id, email FROM fxh_users ORDER BY email ASC");

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $user_id = $_POST['user_id'];
    $status  = $_POST['status'];
    $expiry  = $_POST['expiry'];

    $stmt = $conn->prepare("UPDATE fxh_licenses SET user_id=?, status=?, expiry=? WHERE id=?");
    $stmt->bind_param("issi", $user_id, $status, $expiry, $id);
    $stmt->execute();
    $stmt->close();

    header("Location: licenses.php");
    exit;
}
?>
<!DOCTYPE html>
<html>
<body>
<h2>Edit License</h2>

<form method="post">

User:<br>
<select name="user_id">
    <option value="">-- Unassigned --</option>
    <?php while($u = $users->fetch_assoc()): ?>
        <option value="<?= $u['id'] ?>" 
            <?= $license['user_id'] == $u['id'] ? 'selected' : '' ?>>
            <?= $u['email'] ?>
        </option>
    <?php endwhile; ?>
</select><br><br>

Status:<br>
<select name="status">
    <option value="active"   <?= $license['status']=='active' ? 'selected' : '' ?>>Active</option>
    <option value="inactive" <?= $license['status']=='inactive'? 'selected' : '' ?>>Inactive</option>
</select><br><br>

Expiry:<br>
<input type="date" name="expiry" value="<?= $license['expiry'] ?>"><br><br>

<button type="submit">Save</button>

</form>

</body>
</html>
