<?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'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_require_csrf_post();

require_once __DIR__ . '/db.php';

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$complaintId = (int) ($input['complaintId'] ?? 0);
$status = strtolower(trim((string) ($input['status'] ?? '')));
$allowed = ['pending', 'approved', 'rejected'];

if ($complaintId <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'complaint'], JSON_UNESCAPED_UNICODE);
    exit;
}
if (!in_array($status, $allowed, true)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'status'], JSON_UNESCAPED_UNICODE);
    exit;
}

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

$up = $pdo->prepare('UPDATE complaints SET status = :s, updated_at = :t WHERE id = :id');
$up->execute([':s' => $status, ':t' => time(), ':id' => $complaintId]);
if ($up->rowCount() !== 1) {
    $st = $pdo->prepare('SELECT id FROM complaints WHERE id = :id LIMIT 1');
    $st->execute([':id' => $complaintId]);
    if (!$st->fetch()) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

echo json_encode(
    [
        'ok' => true,
        'complaintId' => $complaintId,
        'status' => $status,
    ],
    JSON_UNESCAPED_UNICODE
);

