<?php
require_once 'config.php';

header('Content-Type: application/json; charset=utf-8');

$license_key = trim($_GET['license_key'] ?? '');
$domain = $_SERVER['HTTP_HOST'];
$ip = $_SERVER['SERVER_ADDR'];

if(!$license_key) {
    echo json_encode(['status'=>'error','message'=>'رمز التفعيل غير موجود']);
    exit;
}

// خادم التفعيل
$server_url = "https://lughatalarabinstitute.net/system/license_server/verify.php";
$url = $server_url . "?key=" . urlencode($license_key) . "&domain=" . urlencode($domain) . "&ip=" . urlencode($ip);

$response = @file_get_contents($url);
if(!$response) {
    echo json_encode(['status'=>'error','message'=>'فشل الاتصال بخادم التفعيل']);
    exit;
}

$data = json_decode($response,true);
if(!$data) {
    echo json_encode(['status'=>'error','message'=>'رد غير صالح من الخادم']);
    exit;
}

try {
    $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    if($data['status'] === 'valid') {
        // تحديث النظام المحلي
        $stmt = $pdo->prepare("UPDATE license_info 
            SET license_key=?, start_date=?, expiry_date=?, status='active' 
            WHERE id=(SELECT id FROM (SELECT id FROM license_info ORDER BY id DESC LIMIT 1) t)");
        $stmt->execute([$license_key, date('Y-m-d'), $data['expiry_date']]);

        // حساب الأماكن المتبقية (حتى 3)
        $stmt2 = $pdo->prepare("SELECT allowed_domains FROM license_keys WHERE license_key=?");
        $stmt2->execute([$license_key]);
        $allowed = $stmt2->fetch(PDO::FETCH_ASSOC);
        $count = 0;
        if(!empty($allowed['allowed_domains'])) {
            $count = count(explode(',', $allowed['allowed_domains']));
        }
        $remaining = 3 - $count;

        echo json_encode([
            'status'=>'valid',
            'expiry_date'=>$data['expiry_date'],
            'remaining_places'=>$remaining >=0 ? $remaining : 0
        ]);
    } else {
        echo json_encode([
            'status'=>'invalid',
            'message'=>$data['message'] ?? 'كود غير صالح أو منتهي'
        ]);
    }

} catch(Exception $e) {
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
