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


$domain = $_SERVER['SERVER_NAME'];
$ip = $_SERVER['SERVER_ADDR'] ?? $_SERVER['REMOTE_ADDR'];
$today = date('Y-m-d');


// ابحث عن آخر سجل مرتبط بالدومين أو الـ IP
$stmt = $pdo->prepare("SELECT * FROM license_info WHERE domain = ? OR ip = ? ORDER BY id DESC LIMIT 1");
$stmt->execute([$domain, $ip]);
$license = $stmt->fetch();


if (!$license) {
// لم يتم العثور على سجل — إنشاء ترخيص تجريبي
$start = $today;
$expiry = date('Y-m-d', strtotime("+" . TRIAL_DAYS . " days"));
$key = 'TRIAL-'.strtoupper(substr(md5($domain . time()), 0, 10));


$ins = $pdo->prepare("INSERT INTO license_info (license_key, start_date, expiry_date, status, domain, ip) VALUES (?, ?, ?, 'trial', ?, ?)");
$ins->execute([$key, $start, $expiry, $domain, $ip]);


// إعادة تحميل حتى يتعرف التطبيق على السجل الجديد
header('Refresh:0');
exit;
}


// تحديث الحالة إذا انتهت الصلاحية
if ($license['status'] !== 'active' && $today > $license['expiry_date']) {
$upd = $pdo->prepare("UPDATE license_info SET status='expired' WHERE id = ?");
$upd->execute([$license['id']]);
include 'license_expired.php';
exit;
}


// إذا كانت الحالة expired قد تم شراء مفتاح دائم مرتبط بالدومين، فجرّب الترقية التلقائية
if ($license['status'] === 'expired') {
$chk = $pdo->prepare("SELECT * FROM license_keys WHERE domain = ? AND status = 'valid' LIMIT 1");
$chk->execute([$domain]);
$keyData = $chk->fetch();
if ($keyData) {
$pdo->prepare("UPDATE license_info SET status='active', license_key = ?, expiry_date = ? WHERE id = ?")
->execute([$keyData['license_key'], $keyData['expiry_date'], $license['id']]);
// استمرار التنفيذ
} else {
include 'license_expired.php';
exit;
}
}


// إذا وصلت هنا => الترخيص صالح (trial أو active)
return true;