<?php
require_once '../config.php';
$pdo = get_pdo();

$key = trim($_GET['key'] ?? '');
$domain = trim($_GET['domain'] ?? '');
$ip = trim($_GET['ip'] ?? '');

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

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

// تحقق أولاً من الترخيص الرسمي
$stmt = $pdo->prepare("SELECT * FROM license_keys WHERE license_key = ? LIMIT 1");
$stmt->execute([$key]);
$lic = $stmt->fetch();
$table = 'license_keys';

if (!$lic) {
    // إذا لم يوجد رسمي، تحقق في التراخيص التجريبية
    $stmt = $pdo->prepare("SELECT * FROM license_info WHERE license_key = ? LIMIT 1");
    $stmt->execute([$key]);
    $lic = $stmt->fetch();
    $table = 'license_info';
    
    if (!$lic) {
        echo json_encode(['status'=>'invalid','message'=>'رمز التفعيل غير موجود']);
        exit;
    }
}

// تحقق من الحالة والتاريخ
$today = date('Y-m-d');

$is_active = false;
if ($table === 'license_keys') {
    $is_active = $lic['status'] === 'valid';
} else {
    $is_active = in_array($lic['status'], ['trial','active']);
}

if (!$is_active || ($lic['expiry_date'] && $lic['expiry_date'] < $today)) {
    echo json_encode(['status'=>'expired','message'=>'رمز التفعيل منتهي']);
    exit;
}

// تحقق من النطاق / IP
$max = MAX_ALLOWED_DOMAINS;
$domains = !empty($lic['allowed_domains']) ? array_filter(array_map('trim', explode(',', $lic['allowed_domains']))) : [];

if ($domain && !in_array($domain, $domains)) {
    if (count($domains) < $max) {
        $domains[] = $domain;
        $upd = $pdo->prepare("UPDATE $table SET allowed_domains = ?, ip = ? WHERE id = ?");
        $upd->execute([implode(',', $domains), $ip, $lic['id']]);
    } else {
        echo json_encode(['status'=>'invalid','message'=>'تم استخدام الكود على الحد الأقصى من المواقع']);
        exit;
    }
}

// نجاح
$response = [
    'status'=>'valid',
    'expiry_date'=>$lic['expiry_date'],
];

if ($table === 'license_keys') {
    $response['client_name'] = $lic['client_name'];
}

echo json_encode($response);
