<?php
include 'db.php';
include 'linkrel.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $license_key = trim($_POST['license_key'] ?? '');

    if ($license_key !== '') {
        // Clear any previous cache and machine binding if license changes
        $stmt = $conn->prepare("
            INSERT INTO branch_info (license_key, machine_id, license_cache, last_verified_at, branch_name, branch_address)
            VALUES (?, NULL, NULL, NULL, NULL, NULL)
            ON DUPLICATE KEY UPDATE
                license_key = VALUES(license_key),
                machine_id = NULL,
                license_cache = NULL,
                last_verified_at = NULL,
                branch_name = NULL,
                branch_address = NULL
        ");
        $stmt->bind_param("s", $license_key);
        $stmt->execute();

        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'License Saved',
                text: 'Your license has been saved successfully.'
            }).then(() => {
                window.location.href = 'index.php';
            });
        </script>";
        exit;
    } else {
        echo "<script>
            Swal.fire({icon: 'error', title: 'Error', text: 'License key is required.'});
        </script>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Activate ITR POS License</title>
    <?php include 'linkrel.php'; ?>
    <style>
        body {
            background: #f8f9fa;
        }
        .license-card {
            border: 1px solid #ddd;
            padding: 30px;
            border-radius: 10px;
            background-color: #fff;
        }
    </style>
</head>
<body class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="license-card shadow-sm">
                <h4 class="text-center mb-3">Welcome to ITR POS</h4>
                <p class="text-center text-muted">
                    License not found.<br>
                    Please contact <strong>IT Resources</strong> for a license.<br>
                    WhatsApp/Call: <a href="tel:03113917777">0311-391-7777</a><br>
                    Or enter your license key below:
                </p>
                <form method="post">
                    <div class="form-group mb-3">
                        <label for="license_key">License Key</label>
                        <input type="text" name="license_key" id="license_key" class="form-control" placeholder="Enter your license key" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Activate License</button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
