<?php
include 'db.php';
if (session_status() === PHP_SESSION_NONE) session_start();

$result = $conn->query("SELECT license_key, machine_id, last_verified_at, license_cache FROM branch_info LIMIT 1");
$row = $result->fetch_assoc();

$license_key = $row['license_key'] ?? '';
$local_machine_id = $row['machine_id'] ?? '';
$last_verified_at = $row['last_verified_at'] ?? null;
$cached_data = json_decode($row['license_cache'] ?? '', true);
$machine_id = md5(php_uname());

// First-time install
if (!$license_key) {
    echo "<script>
        Swal.fire({
            icon: 'warning',
            title: 'License Not Found',
            text: 'Please enter your license key to activate ITR POS.',
            confirmButtonText: 'Activate Now',
            allowOutsideClick: false
        }).then(() => {
            window.location.href = 'license_form.php';
        });
    </script>";
    exit;
}

// Bind machine if not already
if (!$local_machine_id) {
    $stmt = $conn->prepare("UPDATE branch_info SET machine_id = ? WHERE license_key = ?");
    $stmt->bind_param("ss", $machine_id, $license_key);
    $stmt->execute();
}

// Try online verification
$ch = curl_init("https://itresources.com.pk/itr/api/verify_license.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'license_key' => $license_key,
    'machine_id' => $machine_id
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

// ✅ Case 1: Online response received
if ($data) {
    if (isset($data['expired']) && $data['expired'] === true) {
        echo "<script>Swal.fire({
            icon: 'error',
            title: 'License Expired',
            text: 'Your license expired on " . addslashes($data['support_end_date']) . ". Please contact IT Resources to renew.',
            allowOutsideClick: false
        }).then(() => {
            window.location.href = 'license_error.php';
        });</script>";
        exit;
    }

    if ($data['success']) {
        $branchName = $data['branch_name'] ?? '';
        $branchAddress = $data['branch_address'] ?? $data['branch_location'] ?? '';
        $json = json_encode($data);

        $stmt = $conn->prepare("UPDATE branch_info SET branch_name = ?, branch_address = ?, last_verified_at = NOW(), license_cache = ? WHERE license_key = ?");
        $stmt->bind_param("ssss", $branchName, $branchAddress, $json, $license_key);
        $stmt->execute();

        $_SESSION['license_verified'] = true;
        return;
    }
}

// ✅ Case 2: Fallback with cache
if ($cached_data && $last_verified_at) {
    $days_since_last = (new DateTime())->diff(new DateTime($last_verified_at))->days;
    $support_end_date = $cached_data['support_end_date'] ?? null;

    // ❌ Block if cached license has expired
    if ($support_end_date && strtotime($support_end_date) < time()) {
        echo "<script>Swal.fire({
            icon: 'error',
            title: 'License Expired',
            text: 'Your license expired on $support_end_date. Please connect to internet to renew. Call/Whastapp 0311-391-7777',
            allowOutsideClick: false
        }).then(() => {
            window.location.href = 'license_error.php';
        });</script>";
        exit;
    }

    // ✅ Allow grace period of 7 days
    if ($days_since_last <= 7) {
        $_SESSION['license_verified'] = true;
        return;
    } else {
        echo "<script>Swal.fire({
            icon: 'error',
            title: 'License Check Overdue',
            text: 'License could not be verified in the last 7 days.',
            allowOutsideClick: false
        }).then(() => {
            window.location.href = 'license_error.php';
        });</script>";
        exit;
    }
}

// ❌ No internet + no valid cache
echo "<script>Swal.fire({
    icon: 'error',
    title: 'License Check Failed',
    text: 'Unable to verify license. Please connect to the internet.',
    allowOutsideClick: false
}).then(() => {
    window.location.href = 'license_error.php';
});</script>";
exit;
?>
