<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\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
    {
        $coach = App::getInstance()->currentCoach();
        $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 coach_notifications WHERE coach_id = ?",
            [(int) $coach->id]
        )['cnt'] ?? 0);

        $notifications = $db->select(
            "SELECT id, category, title_ar, body_ar, data_json, is_read, created_at
             FROM coach_notifications
             WHERE coach_id = ?
             ORDER BY created_at DESC
             LIMIT ? OFFSET ?",
            [(int) $coach->id, $perPage, $offset]
        );

        foreach ($notifications as &$n) {
            $n['data'] = $n['data_json'] ? json_decode($n['data_json'], true) : null;
            unset($n['data_json']);
        }

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

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

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

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

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

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

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

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

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

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