<?php
// -----------------------------
// CONFIG
// -----------------------------
$MASTER_SECRET = "YOUR_MASTER_SECRET_KEY"; // Must match the main app
date_default_timezone_set("UTC");

// -----------------------------
// FUNCTIONS
// -----------------------------
function generate_signature($data, $secret)
{
    $string = implode("|", $data);
    return hash_hmac("sha256", $string, $secret);
}

// -----------------------------
// HANDLE LICENSE CREATION
// -----------------------------
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $owner = trim($_POST["owner"]);
    $start = trim($_POST["start"]);
    $end = trim($_POST["end"]);
    $apikey = trim($_POST["apikey"]);
    $domain = trim($_POST["domain"]);
    $salt = bin2hex(random_bytes(16));

    // Validate dates
    if (strtotime($end) <= strtotime($start)) {
        die("End date must be after start date.");
    }

    // Data for signature
    $data = [
        $owner,
        $start,
        $end,
        $salt,
        $apikey,
        $domain
    ];

    $signature = generate_signature($data, $MASTER_SECRET);

    // Build license content
    $license = "
LICENSE_OWNER={$owner}
LICENSE_START={$start}
LICENSE_END={$end}
LICENSE_SALT={$salt}
LICENSE_API_KEY={$apikey}
LICENSE_DOMAIN={$domain}
SIGNATURE={$signature}
";

    // Download file
    header("Content-Type: text/plain");
    header("Content-Disposition: attachment; filename=license_" . strtolower($owner) . ".key");
    echo $license;
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>License Generator</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
</head>

<body class="container py-5">

<h2 class="mb-4">🔐 License Generator</h2>

<form method="POST" class="card p-4">

    <label class="form-label">Client / Business Name</label>
    <input name="owner" class="form-control" required>

    <label class="form-label mt-3">License Start Date</label>
    <input type="date" name="start" class="form-control" required>

    <label class="form-label mt-3">License End Date</label>
    <input type="date" name="end" class="form-control" required>

    <label class="form-label mt-3">API Key (You choose any format)</label>
    <input name="apikey" class="form-control" placeholder="MEIRAN-API-2939-ABSD2" required>

    <label class="form-label mt-3">Allowed Domain (optional)</label>
    <input name="domain" class="form-control" placeholder="storeclient.com">

    <button class="btn btn-primary mt-4">Generate License</button>
</form>

</body>
</html>
