<?php
declare(strict_types=1);

namespace App\Modules\Sessions\Services;

use App\Core\App;

final class MakeupService
{
    /**
     * Use a makeup credit for a given session.
     * Validates the credit is available and not expired.
     * Returns true on success, false otherwise.
     */
    public static function useMakeupCredit(int $creditId, int $sessionId): bool
    {
        $db = App::getInstance()->db();

        $credit = $db->selectOne(
            "SELECT id, status, expires_at FROM makeup_credits WHERE id = ?",
            [$creditId]
        );

        if (!$credit) {
            return false;
        }

        if ($credit['status'] !== 'available') {
            return false;
        }

        // Check expiration
        if ($credit['expires_at'] !== null && $credit['expires_at'] < date('Y-m-d')) {
            return false;
        }

        $db->update('makeup_credits', [
            'status'          => 'used',
            'used_session_id' => $sessionId,
        ], 'id = ?', [$creditId]);

        return true;
    }

    /**
     * Expire all credits that are past their expiration date.
     * Returns count of expired credits.
     */
    public static function expireOldCredits(): int
    {
        $db = App::getInstance()->db();

        $stmt = $db->query(
            "UPDATE makeup_credits
             SET status = 'expired'
             WHERE status = 'available'
               AND expires_at < CURDATE()"
        );

        return $stmt->rowCount();
    }

    /**
     * Get available credits for a player with session/group info.
     */
    public static function getPlayerCredits(int $playerId): array
    {
        $db = App::getInstance()->db();

        return $db->select(
            "SELECT mc.*,
                    ts.session_date AS missed_date,
                    ts.start_time AS missed_start_time,
                    tg.name_ar AS group_name
             FROM makeup_credits mc
             LEFT JOIN training_sessions ts ON ts.id = mc.missed_session_id
             LEFT JOIN training_groups tg ON tg.id = ts.group_id
             WHERE mc.player_id = ?
               AND mc.status = 'available'
               AND (mc.expires_at IS NULL OR mc.expires_at >= CURDATE())
             ORDER BY mc.expires_at ASC",
            [$playerId]
        );
    }
}
