<?php
/**
 * سودانا — Cache Management API v21
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => 'admin', 'public' => false]);
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE

// session_start() removed — Kernel::handle manages sessions
if (empty($_SESSION['admin']) && ($_GET['key'] ?? '') !== ADMIN_PASSWORD)
    Kernel::fail('unauthorized', '', 401);

$action = $_GET['action'] ?? 'stats';

if ($action === 'stats') {
    try {
        $st = db()->query("SELECT COUNT(*) AS total, SUM(hits) AS total_hits, COUNT(CASE WHEN expires_at < NOW() THEN 1 END) AS expired, COUNT(CASE WHEN is_valid=0 THEN 1 END) AS invalid FROM ai_cache");
        $stats = $st->fetch();
        $byService = db()->query("SELECT service, COUNT(*) AS cnt, SUM(hits) AS hits FROM ai_cache GROUP BY service ORDER BY hits DESC")->fetchAll();
        json_response(['success'=>true,'stats'=>$stats,'by_service'=>$byService]);
    } catch (Throwable $e) { echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE); }
}

if ($action === 'clear_expired') {
    try {
        $st = db()->prepare('DELETE FROM ai_cache WHERE expires_at < NOW()');
        $st->execute();
        json_response(['success'=>true,'deleted'=>$st->rowCount()]);
    } catch (Throwable $e) { echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE); }
}

if ($action === 'clear_service') {
    $service = $_GET['service'] ?? '';
    if (!$service) Kernel::fail('service_required', '', 400);
    try {
        $st = db()->prepare('DELETE FROM ai_cache WHERE service=?');
        $st->execute([$service]);
        json_response(['success'=>true,'deleted'=>$st->rowCount(),'service'=>$service]);
    } catch (Throwable $e) { echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE); }
}

if ($action === 'invalidate') {
    $key = $_GET['cache_key'] ?? '';
    if (!$key) Kernel::fail('cache_key_required', '', 400);
    try {
        db()->prepare('UPDATE ai_cache SET is_valid=0 WHERE cache_key=?')->execute([$key]);
        json_response(['success'=>true,'message'=>'تم إبطال المفتاح']);
    } catch (Throwable $e) { echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE); }
}

if ($action === 'clear_all') {
    try {
        $count = (int)db()->query("SELECT COUNT(*) FROM ai_cache")->fetchColumn();
        db()->exec("TRUNCATE TABLE ai_cache");
        json_response(['success'=>true,'deleted'=>$count,'warning'=>'تم حذف كل الـ cache — سيزداد استهلاك AI مؤقتاً']);
    } catch (Throwable $e) { echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE); }
}

Kernel::fail('unknown_action', '', 400);
