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

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

    if ($license_key !== '') {
        // Determine a deterministic target row:
        // 1) HO/default row (cloud)
        // 2) Default active row
        // 3) First active row
        // 4) First row
        // If none exists, insert one row.
        $targetId = 0;
        $res = $conn->query("
            SELECT id
            FROM branch_info
            WHERE is_active = 1
              AND (branch_type = 'head_office' OR is_default = 1)
            ORDER BY is_default DESC, (branch_type = 'head_office') DESC, id ASC
            LIMIT 1
        ");
        if ($res && $res->num_rows > 0) {
            $targetId = (int)$res->fetch_assoc()['id'];
        } else {
            $res = $conn->query("SELECT id FROM branch_info WHERE is_active = 1 ORDER BY id ASC LIMIT 1");
            if ($res && $res->num_rows > 0) {
                $targetId = (int)$res->fetch_assoc()['id'];
            } else {
                $res = $conn->query("SELECT id FROM branch_info ORDER BY id ASC LIMIT 1");
                if ($res && $res->num_rows > 0) {
                    $targetId = (int)$res->fetch_assoc()['id'];
                }
            }
        }

        if ($targetId > 0) {
            $stmt = $conn->prepare("
                UPDATE branch_info
                SET license_key = ?,
                    machine_id = NULL,
                    license_cache = NULL,
                    last_verified_at = NULL
                WHERE id = ?
            ");
            $stmt->bind_param("si", $license_key, $targetId);
            $stmt->execute();
        } else {
            $stmt = $conn->prepare("
                INSERT INTO branch_info (license_key, machine_id, license_cache, last_verified_at, branch_type, is_active, is_default)
                VALUES (?, NULL, NULL, NULL, 'branch', 1, 1)
            ");
            $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>
