<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['valid'=>false,'message'=>'Method not allowed']); exit;
}

require_once dirname(__DIR__) . '/db.php';

$ip   = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$body = json_decode(file_get_contents('php://input'), true);
$key  = trim(strtoupper($body['key'] ?? ''));
$did  = trim($body['device_id'] ?? '');

if (empty($key) || empty($did)) {
    logVerify($key,$did,$ip,'error','Eksik parametre');
    echo json_encode(['valid'=>false,'message'=>'Eksik parametre']); exit;
}

if (!preg_match('/^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/', $key)) {
    logVerify($key,$did,$ip,'invalid','Gecersiz format');
    echo json_encode(['valid'=>false,'message'=>'Geçersiz lisans formatı']); exit;
}

try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM licenses WHERE lic_key = ?");
    $stmt->execute([$key]);
    $lic = $stmt->fetch();

    if (!$lic) {
        logVerify($key,$did,$ip,'not_found','Bulunamadi');
        echo json_encode(['valid'=>false,'message'=>'Geçersiz lisans anahtarı']); exit;
    }
    if (!$lic['active']) {
        logVerify($key,$did,$ip,'revoked','Iptal edilmis');
        echo json_encode(['valid'=>false,'message'=>'Lisans iptal edilmiş']); exit;
    }
    if (strtotime($lic['expiry']) < time()) {
        logVerify($key,$did,$ip,'expired','Suresi dolmus');
        echo json_encode(['valid'=>false,'message'=>'Lisans süresi dolmuş']); exit;
    }

    $stmt = $db->prepare("SELECT id FROM activations WHERE lic_key=? AND device_id=?");
    $stmt->execute([$key,$did]);
    $existing = $stmt->fetch();

    if (!$existing) {
        $stmt = $db->prepare("SELECT COUNT(*) as cnt FROM activations WHERE lic_key=?");
        $stmt->execute([$key]);
        $total = $stmt->fetch()['cnt'];
        if ($total >= $lic['max_devices']) {
            logVerify($key,$did,$ip,'device_limit','Cihaz limiti');
            echo json_encode(['valid'=>false,'message'=>"Maksimum cihaz sayısına ulaşıldı ({$lic['max_devices']})"]);
            exit;
        }
        $stmt = $db->prepare("INSERT INTO activations (lic_key,device_id) VALUES (?,?)");
        $stmt->execute([$key,$did]);
    }

    logVerify($key,$did,$ip,'success','Dogrulandi');
    echo json_encode(['valid'=>true,'plan'=>$lic['plan'],'expiry'=>$lic['expiry'],'message'=>'Lisans geçerli']);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['valid'=>false,'message'=>'Sunucu hatası']);
}
