<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__ . '/../../engine/Logger.php';
$type    = preg_replace('/[^a-z_]/', '', $_GET['type'] ?? '');
$service = preg_replace('/[^a-z_]/', '', $_GET['service'] ?? '');
$sort    = $_GET['sort'] === 'votes' ? 'votes_count' : 'created_at';
$limit   = min(50, max(1, (int)($_GET['limit'] ?? 20)));
$offset  = max(0, (int)($_GET['offset'] ?? 0));

try {
    $where = ["status NOT IN ('rejected','duplicate')"];
    $params = [];
    if ($type) { $where[] = "type=?"; $params[] = $type; }
    if ($service) { $where[] = "service=?"; $params[] = $service; }

    $whereSQL = implode(' AND ', $where);
    $st = db()->prepare(
        "SELECT id,ref_no,type,service,title,description,priority_label,
                votes_count,status,created_at,
                CASE WHEN user_id IS NULL THEN 'زائر' ELSE 'مستخدم' END as poster
         FROM user_suggestions WHERE {$whereSQL}
         ORDER BY {$sort} DESC LIMIT ? OFFSET ?"
    );
    $params[] = $limit; $params[] = $offset;
    $st->execute($params);
    $suggestions = $st->fetchAll();

    $totalSt = db()->prepare("SELECT COUNT(*) FROM user_suggestions WHERE {$whereSQL}");
    $totalSt->execute(array_slice($params, 0, -2));
    $total = (int)$totalSt->fetchColumn();

    echo json_encode([
        'ok'          => true,
        'suggestions' => $suggestions,
        'total'       => $total,
        'has_more'    => ($offset + $limit) < $total,
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
