<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\Services;

use App\Core\App;
use App\Shared\Services\PushNotificationService;

final class CoachNotificationService
{
    public static function notify(int $coachId, string $category, string $title, string $body, array $data = []): void
    {
        $db = App::getInstance()->db();

        $db->insert('coach_notifications', [
            'coach_id' => $coachId,
            'category' => $category,
            'title_ar' => $title,
            'body_ar' => $body,
            'data_json' => !empty($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : null,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        PushNotificationService::send('coach', $coachId, $title, $body, $data);
    }

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

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