<?php
declare(strict_types=1);

namespace App\Modules\ParentApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

final class NotificationController extends ApiController
{
    public function list(Request $request): Response
    {
        $parent = App::getInstance()->currentParent();
        $db = App::getInstance()->db();

        $page = max(1, (int) ($request->get('page') ?? 1));
        $perPage = 25;
        $offset = ($page - 1) * $perPage;

        $total = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM parent_notifications_log WHERE parent_id = ?",
            [(int) $parent->id]
        )['cnt'] ?? 0);

        $notifications = $db->select(
            "SELECT id, player_id, notification_type, title_ar, body_ar, is_read, channel, created_at
             FROM parent_notifications_log
             WHERE parent_id = ?
             ORDER BY created_at DESC
             LIMIT ? OFFSET ?",
            [(int) $parent->id, $perPage, $offset]
        );

        return $this->paginatedResponse($notifications, $total, $page, $perPage);
    }

    public function markRead(Request $request, int $id): Response
    {
        $parent = App::getInstance()->currentParent();
        $db = App::getInstance()->db();

        $db->update('parent_notifications_log', [
            'is_read' => 1,
            'read_at' => date('Y-m-d H:i:s'),
        ], 'id = ? AND parent_id = ?', [$id, (int) $parent->id]);

        return $this->successResponse(['read' => true]);
    }

    public function markAllRead(Request $request): Response
    {
        $parent = App::getInstance()->currentParent();
        $db = App::getInstance()->db();

        $db->query(
            "UPDATE parent_notifications_log SET is_read = 1, read_at = ? WHERE parent_id = ? AND is_read = 0",
            [date('Y-m-d H:i:s'), (int) $parent->id]
        );

        return $this->successResponse(['read_all' => true]);
    }

    public function unreadCount(Request $request): Response
    {
        $parent = App::getInstance()->currentParent();
        $db = App::getInstance()->db();

        $count = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM parent_notifications_log WHERE parent_id = ? AND is_read = 0",
            [(int) $parent->id]
        )['cnt'] ?? 0);

        return $this->successResponse(['unread_count' => $count]);
    }
}
