<?php
/**
 * GET /api/admin/reports_list.php
 * Admin-only. Query params: status=open|reviewing|resolved|dismissed
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

require_login();
require_role(['admin']);

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 25;
$offset = ($page - 1) * $perPage;

$pdo = Database::connect();

$where = [];
$params = [];
if (!empty($_GET['status'])) {
    $where[] = 'r.status = ?';
    $params[] = $_GET['status'];
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM reports r $whereSql");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT r.id, r.reason, r.status, r.created_at,
           reporter.email AS reporter_email,
           p.id AS product_id, p.name AS product_name,
           ru.email AS reported_user_email
    FROM reports r
    JOIN users reporter ON reporter.id = r.reported_by
    LEFT JOIN products p ON p.id = r.product_id
    LEFT JOIN users ru ON ru.id = r.reported_user_id
    $whereSql
    ORDER BY r.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$reports = $stmt->fetchAll();

send_json(true, 'OK', [
    'reports' => $reports,
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
