<?php
require_once __DIR__ . "/../config.php";

if(!isset($_SESSION['email'])){
    fxh_set_flash("You must login first.");
    header("Location:/portal/login.php");
    exit;
}

$email = $_SESSION['email'];
$key   = trim($_POST['license_key'] ?? '');

if($key==""){
    fxh_set_flash("License key required.");
    header("Location:/portal/user/dashboard.php");
    exit;
}

/* Find license */
$st = $conn->prepare("
    SELECT id,user_email,expires_at,active
    FROM fxh_licenses
    WHERE license_key = ?
    LIMIT 1
");
$st->bind_param("s",$key);
$st->execute();
$r = $st->get_result();

if(!$r->num_rows){
    fxh_set_flash("Invalid License key.");
    header("Location:/portal/user/dashboard.php");
    exit;
}

$lic = $r->fetch_assoc();

/* Already owned */
if(!empty($lic['user_email'])){
    if($lic['user_email'] == $email){
        fxh_set_flash("License already attached to your account.","success");
    } else {
        fxh_set_flash("License belongs to another user.");
    }
    header("Location:/portal/user/dashboard.php");
    exit;
}

/* Expiration check */
if(!empty($lic['expires_at']) && strtotime($lic['expires_at']) < time()){
    fxh_set_flash("License is expired.");
    header("Location:/portal/user/dashboard.php");
    exit;
}

/* Attach to user */
$up = $conn->prepare("
    UPDATE fxh_licenses
    SET user_email = ?, active = 1
    WHERE license_key = ?
");
$up->bind_param("ss",$email,$key);
$up->execute();

/* Success */
fxh_set_flash("✅ License successfully claimed!", "success");
header("Location:/portal/user/dashboard.php");
exit;
