<?php
declare(strict_types=1);

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

header('Content-Type: application/json; charset=utf-8');

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

mocker_require_csrf_post();

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$category = strtolower(trim((string) ($input['category'] ?? '')));
$message = trim((string) ($input['message'] ?? ''));
$sponsorId = trim((string) ($input['sponsorId'] ?? ''));
$sponsorTitle = trim((string) ($input['sponsorTitle'] ?? ''));

if (!in_array($category, ['sponsor', 'other'], true)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'category'], JSON_UNESCAPED_UNICODE);
    exit;
}
if ($category === 'sponsor' && $sponsorId === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'sponsor'], JSON_UNESCAPED_UNICODE);
    exit;
}
$msgLen = mocker_utf8_len($message);
if ($message === '' || $msgLen < 8) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'message'], JSON_UNESCAPED_UNICODE);
    exit;
}
if ($msgLen > 2000) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'message_long'], 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;
}

$stUser = $pdo->prepare('SELECT username, email FROM users WHERE id = :id LIMIT 1');
$stUser->execute([':id' => $uid]);
$u = $stUser->fetch();
if (!$u) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

$now = time();
$ins = $pdo->prepare(
    'INSERT INTO complaints (user_id, username, email, category, sponsor_id, sponsor_title, message, status, created_at, updated_at)
     VALUES (:uid, :un, :em, :cat, :sid, :st, :msg, :status, :t, :t2)'
);
$ins->execute([
    ':uid' => $uid,
    ':un' => (string) $u['username'],
    ':em' => (string) $u['email'],
    ':cat' => $category,
    ':sid' => $category === 'sponsor' ? $sponsorId : null,
    ':st' => $category === 'sponsor' ? ($sponsorTitle !== '' ? $sponsorTitle : null) : null,
    ':msg' => $message,
    ':status' => 'pending',
    ':t' => $now,
    ':t2' => $now,
]);

echo json_encode(
    [
        'ok' => true,
        'complaint' => [
            'id' => (int) $pdo->lastInsertId(),
            'status' => 'pending',
            'createdAt' => $now,
        ],
    ],
    JSON_UNESCAPED_UNICODE
);

