<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;

final class SubscriptionGeneratorService
{
    public static function generateForMonth(string $yearMonth): array
    {
        $db = App::getInstance()->db();

        $periodStart = $yearMonth . '-01';
        $periodEnd = date('Y-m-t', strtotime($periodStart));

        $groups = $db->select(
            "SELECT g.*, p.name_ar as program_name
             FROM sa_groups g
             JOIN sa_programs p ON p.id = g.program_id
             WHERE g.status = 'active' AND g.is_archived = 0",
            []
        );

        $generated = 0;
        $skipped = 0;
        $employeeId = (int) (App::getInstance()->session()->get('employee_id') ?? 0);

        foreach ($groups as $group) {
            $players = $db->select(
                "SELECT gp.*, sp.player_type, sp.full_name_ar
                 FROM sa_group_players gp
                 JOIN sa_players sp ON sp.id = gp.player_id
                 WHERE gp.group_id = ? AND gp.status = 'active'",
                [(int) $group['id']]
            );

            foreach ($players as $player) {
                $existing = $db->selectOne(
                    "SELECT id FROM sa_subscriptions
                     WHERE player_id = ? AND group_id = ? AND period_start = ?",
                    [(int) $player['player_id'], (int) $group['id'], $periodStart]
                );

                if ($existing) {
                    $skipped++;
                    continue;
                }

                $amount = $player['player_type'] === 'member'
                    ? (float) $group['monthly_fee_member']
                    : (float) $group['monthly_fee_nonmember'];

                $subNumber = 'SUB-' . date('Ymd') . '-' . str_pad((string) random_int(1, 9999), 4, '0', STR_PAD_LEFT);

                $db->insert('sa_subscriptions', [
                    'subscription_number' => $subNumber,
                    'player_id'           => (int) $player['player_id'],
                    'group_id'            => (int) $group['id'],
                    'period_start'        => $periodStart,
                    'period_end'          => $periodEnd,
                    'amount'              => $amount,
                    'discount_amount'     => 0.00,
                    'final_amount'        => $amount,
                    'payment_status'      => 'unpaid',
                    'paid_amount'         => 0.00,
                    'created_at'          => date('Y-m-d H:i:s'),
                    'updated_at'          => date('Y-m-d H:i:s'),
                    'created_by'          => $employeeId,
                ]);

                $generated++;
            }
        }

        return [
            'success'   => true,
            'generated' => $generated,
            'skipped'   => $skipped,
            'month'     => $yearMonth,
        ];
    }
}
