<?php
session_start();
if (empty($_SESSION['admin_logged_in'])) { http_response_code(403); exit('Yetkisiz'); }
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/db.php';
$db     = getDB();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

// USOM listesini çek ve cache'le (1 saat)
function getUsomList() {
    $cacheFile = __DIR__ . '/../data/usom_cache.txt';
    $cacheTime = 3600; // 1 saat

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
        return file($cacheFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    }

    $ctx = stream_context_create(['http' => [
        'timeout'     => 15,
        'user_agent'  => 'Mozilla/5.0 (compatible; USOM-Checker/1.0)',
        'method'      => 'GET',
    ]]);

    $data = @file_get_contents('https://www.usom.gov.tr/url-list.txt', false, $ctx);
    if ($data === false) {
        // Cache varsa eski listeyi kullan
        if (file_exists($cacheFile)) {
            return file($cacheFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        }
        return null;
    }

    file_put_contents($cacheFile, $data);
    return explode("\n", trim($data));
}

// Liste güncelle
if ($action === 'refresh') {
    $cacheFile = __DIR__ . '/../data/usom_cache.txt';
    if (file_exists($cacheFile)) unlink($cacheFile);
    $list = getUsomList();
    if ($list === null) {
        echo json_encode(['error' => 'USOM listesi alınamadı. Sunucu erişilemez olabilir.'], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(['success' => true, 'count' => count($list), 'updated' => date('d.m.Y H:i:s')], JSON_UNESCAPED_UNICODE);
    }
    exit;
}

// Cache bilgisi
if ($action === 'info') {
    $cacheFile = __DIR__ . '/../data/usom_cache.txt';
    if (file_exists($cacheFile)) {
        $lines = file($cacheFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        echo json_encode([
            'cached'   => true,
            'count'    => count($lines),
            'updated'  => date('d.m.Y H:i:s', filemtime($cacheFile)),
            'age_min'  => round((time() - filemtime($cacheFile)) / 60),
        ], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(['cached' => false, 'count' => 0], JSON_UNESCAPED_UNICODE);
    }
    exit;
}

// Domain/URL sorgula
if ($action === 'check' && $method === 'POST') {
    $d     = json_decode(file_get_contents('php://input'), true) ?: [];
    $input = trim($d['domain'] ?? '');

    if (empty($input)) {
        echo json_encode(['error' => 'Domain boş olamaz'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Domain temizle
    $clean = strtolower($input);
    $clean = preg_replace('#^https?://#', '', $clean);
    $clean = preg_replace('#^www\.#', '', $clean);
    $clean = explode('/', $clean)[0]; // path kısmını at
    $clean = explode('?', $clean)[0]; // query kısmını at

    $list = getUsomList();
    if ($list === null) {
        echo json_encode(['error' => 'USOM listesi alınamadı'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $found    = false;
    $matches  = [];
    foreach ($list as $line) {
        $line = trim(strtolower($line));
        if (empty($line) || $line[0] === '#') continue;
        $lineDomain = preg_replace('#^https?://#', '', $line);
        $lineDomain = preg_replace('#^www\.#', '', $lineDomain);
        $lineDomain = explode('/', $lineDomain)[0];
        if ($lineDomain === $clean || 
            (strlen($clean) > strlen($lineDomain) && substr($clean, -(strlen($lineDomain)+1)) === '.'.$lineDomain) ||
            (strlen($lineDomain) > strlen($clean) && substr($lineDomain, -(strlen($clean)+1)) === '.'.$clean)) {
            $found     = true;
            $matches[] = $line;
            if (count($matches) >= 5) break; // max 5 eşleşme göster
        }
    }

    echo json_encode([
        'domain'   => $clean,
        'original' => $input,
        'found'    => $found,
        'matches'  => $matches,
        'total'    => count($list),
        'checked'  => date('d.m.Y H:i:s'),
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// Toplu sorgula
if ($action === 'bulk' && $method === 'POST') {
    $d       = json_decode(file_get_contents('php://input'), true) ?: [];
    $domains = array_filter(array_map('trim', explode("\n", $d['domains'] ?? '')));

    if (empty($domains)) {
        echo json_encode(['error' => 'Domain listesi boş'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (count($domains) > 100) {
        echo json_encode(['error' => 'En fazla 100 domain sorgulanabilir'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $list = getUsomList();
    if ($list === null) {
        echo json_encode(['error' => 'USOM listesi alınamadı'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Listeyi set'e çevir (hızlı arama)
    $listSet = [];
    foreach ($list as $line) {
        $line = trim(strtolower($line));
        if (empty($line) || $line[0] === '#') continue;
        $d2 = preg_replace('#^https?://#', '', $line);
        $d2 = preg_replace('#^www\.#', '', $d2);
        $d2 = explode('/', $d2)[0];
        $listSet[$d2] = true;
    }

    $results = [];
    foreach ($domains as $input) {
        $clean = strtolower($input);
        $clean = preg_replace('#^https?://#', '', $clean);
        $clean = preg_replace('#^www\.#', '', $clean);
        $clean = explode('/', $clean)[0];
        $clean = explode('?', $clean)[0];
        $found = isset($listSet[$clean]);
        $results[] = ['domain' => $clean, 'found' => $found];
    }

    $zarali = array_values(array_filter($results, function($r) { return $r['found']; }));
    echo json_encode([
        'results'       => $results,
        'total_checked' => count($results),
        'total_zarali'  => count($zarali),
        'list_size'     => count($list),
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode(['error' => 'Geçersiz istek'], JSON_UNESCAPED_UNICODE);
