<?php
// verify_license.php
require_once 'config.php';
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') throw new Exception('Bad request');
$license_key = trim($_POST['license_key'] ?? '');
if (!$license_key) throw new Exception('رمز التفعيل غير موجود');


$domain = $_SERVER['HTTP_HOST'];
$ip = $_SERVER['SERVER_ADDR'] ?? $_SERVER['REMOTE_ADDR'];


// طلب إلى خادم التفعيل (استخدم cURL)
$url = LICENSE_SERVER_URL . '?key=' . urlencode($license_key) . '&domain=' . urlencode($domain) . '&ip=' . urlencode($ip);


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, LICENSE_CLIENT_UA);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$resp = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);


if (!$resp) throw new Exception('فشل الاتصال بخادم التفعيل');


$data = json_decode($resp, true);
if (!$data) throw new Exception('رد غير صالح من خادم التفعيل');


$pdo = get_pdo();


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']]);


echo "<script>alert('تم تفعيل النظام حتى {$data['expiry_date']}');window.location='index.php';</script>";
exit;
} else {
$msg = $data['message'] ?? 'كود غير صالح';
echo "<script>alert('{$msg}');window.location='license_expired.php';</script>";
exit;
}


} catch (Exception $e) {
echo "<script>alert('".addslashes($e->getMessage())."');window.history.back();</script>";
}