<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');

ob_start();

function respond(int $status_code, array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($status_code);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    respond(204, []);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    respond(405, [
        'success' => false,
        'message' => 'Method tidak dibenarkan.',
    ]);
}

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

$raw = file_get_contents('php://input');
$payload = json_decode($raw ?: '', true);
if (!is_array($payload)) {
    $payload = $_POST;
}

$user_id = (int) ($payload['user_id'] ?? 0);
if ($user_id <= 0) {
    respond(422, [
        'success' => false,
        'message' => 'User tidak sah.',
    ]);
}

$user_stmt = mysqli_prepare($conn, "SELECT id FROM users WHERE id = ? AND status = 'approved' LIMIT 1");
if (!$user_stmt) {
    respond(500, [
        'success' => false,
        'message' => 'Ralat sistem semasa membaca pengguna.',
    ]);
}

mysqli_stmt_bind_param($user_stmt, 'i', $user_id);
mysqli_stmt_execute($user_stmt);
$user_result = mysqli_stmt_get_result($user_stmt);
if (!$user_result || !mysqli_fetch_assoc($user_result)) {
    respond(403, [
        'success' => false,
        'message' => 'Akaun tidak dibenarkan.',
    ]);
}

$action = strtolower(trim((string) ($payload['action'] ?? 'list')));

function normalizeNotificationKeys(mixed $value): array
{
    if (is_string($value)) {
        $decoded = json_decode($value, true);
        $value = is_array($decoded) ? $decoded : [$value];
    }

    if (!is_array($value)) {
        return [];
    }

    $keys = [];
    foreach ($value as $key) {
        $normalized = trim((string) $key);
        if ($normalized !== '' && preg_match('/^[a-z0-9_-]{1,100}$/i', $normalized)) {
            $keys[] = $normalized;
        }
    }

    return array_values(array_unique($keys));
}

if ($action === 'list') {
    $stmt = mysqli_prepare(
        $conn,
        'SELECT notification_key FROM user_notification_reads WHERE user_id = ? ORDER BY read_at DESC'
    );
    if (!$stmt) {
        respond(500, [
            'success' => false,
            'message' => 'Ralat sistem semasa membaca notifikasi.',
        ]);
    }

    mysqli_stmt_bind_param($stmt, 'i', $user_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $keys = [];
    while ($result && ($row = mysqli_fetch_assoc($result))) {
        $key = trim((string) ($row['notification_key'] ?? ''));
        if ($key !== '') {
            $keys[] = $key;
        }
    }

    respond(200, [
        'success' => true,
        'read_ids' => array_values(array_unique($keys)),
    ]);
}

if ($action !== 'read' && $action !== 'read_all') {
    respond(422, [
        'success' => false,
        'message' => 'Tindakan tidak sah.',
    ]);
}

$keys = normalizeNotificationKeys($payload['notification_keys'] ?? []);
if (empty($keys) && isset($payload['notification_key'])) {
    $keys = normalizeNotificationKeys([$payload['notification_key']]);
}

if (empty($keys)) {
    respond(200, [
        'success' => true,
        'read_count' => 0,
    ]);
}

$stmt = mysqli_prepare(
    $conn,
    'INSERT IGNORE INTO user_notification_reads (user_id, notification_key, read_at) VALUES (?, ?, NOW())'
);
if (!$stmt) {
    respond(500, [
        'success' => false,
        'message' => 'Ralat sistem semasa menyimpan status notifikasi.',
    ]);
}

$read_count = 0;
foreach ($keys as $key) {
    mysqli_stmt_bind_param($stmt, 'is', $user_id, $key);
    if (mysqli_stmt_execute($stmt)) {
        $read_count += mysqli_stmt_affected_rows($stmt) > 0 ? 1 : 0;
    }
}

respond(200, [
    'success' => true,
    'read_count' => $read_count,
]);
