<?php

if (file_exists(__DIR__ . '/config.php')) {
    require_once __DIR__ . '/config.php';
} else {
    die('গুরুত্বপূর্ণ কনফিগারেশন ফাইল (config.php) খুঁজে পাওয়া যায়নি।');
}


$admin_panel_api_url = 'https://bot.shakiltechnology.com/api/verify.php';
$recheck_interval = 25; 


function get_license_from_db() {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) { return null; }
    
    $result = $conn->query("SELECT setting_key, setting_value FROM total_task");
    if (!$result) { $conn->close(); return null; }
    $settings = [];
    while ($row = $result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    $conn->close();
    return $settings;
}

function save_license_to_db($key, $domain) {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) { return false; }
    $current_time = time();

    
    $queries = [
        "UPDATE total_task SET setting_value = ? WHERE setting_key = 'license_key'",
        "UPDATE total_task SET setting_value = ? WHERE setting_key = 'domain'",
        "UPDATE total_task SET setting_value = ? WHERE setting_key = 'last_check_timestamp'"
    ];
    
    $stmt1 = $conn->prepare($queries[0]); $stmt1->bind_param("s", $key); $stmt1->execute(); $stmt1->close();
    $stmt2 = $conn->prepare($queries[1]); $stmt2->bind_param("s", $domain); $stmt2->execute(); $stmt2->close();
    $stmt3 = $conn->prepare($queries[2]); $stmt3->bind_param("s", $current_time); $stmt3->execute(); $stmt3->close();

    $conn->close();
    return true;
}


function delete_local_license() {
    $empty_value = '';
    $zero_time = '0';
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) { return false; }
    

    $queries = [
        "UPDATE total_task SET setting_value = ? WHERE setting_key = 'license_key'",
        "UPDATE total_task SET setting_value = ? WHERE setting_key = 'domain'",
        "UPDATE total_task SET setting_value = ? WHERE setting_key = 'last_check_timestamp'"
    ];

    $stmt1 = $conn->prepare($queries[0]); $stmt1->bind_param("s", $empty_value); $stmt1->execute(); $stmt1->close();
    $stmt2 = $conn->prepare($queries[1]); $stmt2->bind_param("s", $empty_value); $stmt2->execute(); $stmt2->close();
    $stmt3 = $conn->prepare($queries[2]); $stmt3->bind_param("s", $zero_time); $stmt3->execute(); $stmt3->close();
    
    $conn->close();
    return true;
}

function normalize_domain($domain) {
    $domain = preg_replace('/^https?:\/\//', '', $domain);
    $domain = preg_replace('/^www\./', '', $domain);
    return strtolower(rtrim($domain, '/'));
}
 
$current_domain_normalized = normalize_domain($_SERVER['SERVER_NAME']);
$db_license_data = get_license_from_db();

if ($db_license_data && !empty($db_license_data['license_key'])) {
    $db_domain_normalized = normalize_domain($db_license_data['domain']);
    
    if ($db_domain_normalized === $current_domain_normalized) {
        $last_check = isset($db_license_data['last_check_timestamp']) ? (int)$db_license_data['last_check_timestamp'] : 0;
        $current_time = time();

        if (($current_time - $last_check) > $recheck_interval) {
            $post_data = ['domain' => $_SERVER['SERVER_NAME']];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $admin_panel_api_url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            $response = curl_exec($ch);
            curl_close($ch);
            
            $response_data = json_decode($response, true);
            
            if (isset($response_data['status']) && $response_data['status'] === 'approved') {
                save_license_to_db($db_license_data['license_key'], $db_license_data['domain']);
            } else {
                delete_local_license();
                header("Location: " . $_SERVER['REQUEST_URI']);
                exit;
            }
        }
        return;
    }
}

$post_data = ['domain' => $_SERVER['SERVER_NAME']];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $admin_panel_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false || $http_code !== 200) { die("লাইসেন্স সার্ভারের সাথে সংযোগ করা যাচ্ছে না।"); }
$response_data = json_decode($response, true);
if (is_null($response_data)) { die("লাইসেন্স সার্ভার থেকে একটি অবৈধ প্রতিক্রিয়া এসেছে।"); }

if (isset($response_data['status'])) {
    switch ($response_data['status']) {
        case 'approved':
            if (!empty($response_data['license_key'])) {
                if (!save_license_to_db($response_data['license_key'], $_SERVER['SERVER_NAME'])) {
                     die("ত্রুটি: লাইসেন্স তথ্য লোকাল ডাটাবেসে সেভ করা যায়নি।");
                }
                header("Location: " . $_SERVER['REQUEST_URI']);
                exit();
            } else { die("লাইসেন্স অ্যাপ্রুভ করা হয়েছে কিন্তু কী পাওয়া যায়নি।"); }
            break;
        case 'pending':
            die("ERROR Domin: " . htmlspecialchars($_SERVER['SERVER_NAME']));
            break;
        default:
            die("Error: " . htmlspecialchars($response_data['status']));
            break;
    }
} else { die("লাইসেন্স সার্ভার থেকে একটি অজানা প্রতিক্রিয়া এসেছে।"); }
?>