<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';

mocker_admin_require_permission('complaints');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

require_once __DIR__ . '/db.php';

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$rows = $pdo->query(
    'SELECT id, user_id, username, email, category, sponsor_id, sponsor_title, message, status, created_at, updated_at
     FROM complaints
     ORDER BY created_at DESC, id DESC'
)->fetchAll(PDO::FETCH_ASSOC);

$out = [];
foreach ($rows as $r) {
    $out[] = [
        'id' => (int) $r['id'],
        'userId' => (int) $r['user_id'],
        'username' => (string) $r['username'],
        'email' => (string) $r['email'],
        'category' => (string) $r['category'],
        'sponsorId' => $r['sponsor_id'] !== null ? (string) $r['sponsor_id'] : '',
        'sponsorTitle' => $r['sponsor_title'] !== null ? (string) $r['sponsor_title'] : '',
        'message' => (string) $r['message'],
        'status' => (string) ($r['status'] ?? 'pending'),
        'createdAt' => (int) $r['created_at'],
        'updatedAt' => $r['updated_at'] !== null ? (int) $r['updated_at'] : null,
    ];
}

echo json_encode(
    [
        'ok' => true,
        'complaints' => $out,
    ],
    JSON_UNESCAPED_UNICODE
);

