<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\Services;

use App\Core\App;

final class PlayerNotificationService
{
    public static function notify(int $playerId, string $category, string $title, string $body, array $data = []): void
    {
        $db = App::getInstance()->db();
        $db->insert('player_notifications', [
            'player_id' => $playerId,
            'category' => $category,
            'title_ar' => $title,
            'body_ar' => $body,
            'data_json' => !empty($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : null,
        ]);
    }

    public static function getForPlayer(int $playerId, ?string $category = null, ?bool $isRead = null, int $page = 1, int $perPage = 25): array
    {
        $db = App::getInstance()->db();
        $where = ['player_id = ?'];
        $params = [$playerId];

        if ($category !== null) {
            $where[] = 'category = ?';
            $params[] = $category;
        }
        if ($isRead !== null) {
            $where[] = 'is_read = ?';
            $params[] = $isRead ? 1 : 0;
        }

        $whereClause = implode(' AND ', $where);

        $total = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM player_notifications WHERE {$whereClause}",
            $params
        )['cnt'] ?? 0);

        $lastPage = max(1, (int) ceil($total / $perPage));
        $page = min($page, $lastPage);
        $offset = ($page - 1) * $perPage;

        $items = $db->select(
            "SELECT id, category, title_ar, body_ar, data_json, is_read, read_at, created_at
             FROM player_notifications WHERE {$whereClause}
             ORDER BY created_at DESC LIMIT ? OFFSET ?",
            array_merge($params, [$perPage, $offset])
        );

        return [
            'data' => $items,
            'pagination' => [
                'total' => $total,
                'per_page' => $perPage,
                'current_page' => $page,
                'last_page' => $lastPage,
            ],
        ];
    }

    public static function markRead(int $notificationId, int $playerId): bool
    {
        $db = App::getInstance()->db();
        $db->update('player_notifications', [
            'is_read' => 1,
            'read_at' => date('Y-m-d H:i:s'),
        ], 'id = ? AND player_id = ?', [$notificationId, $playerId]);
        return true;
    }

    public static function markAllRead(int $playerId): void
    {
        $db = App::getInstance()->db();
        $db->query(
            "UPDATE player_notifications SET is_read = 1, read_at = NOW() WHERE player_id = ? AND is_read = 0",
            [$playerId]
        );
    }

    public static function unreadCount(int $playerId): int
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM player_notifications WHERE player_id = ? AND is_read = 0",
            [$playerId]
        );
        return (int) ($row['cnt'] ?? 0);
    }
}
