<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;

class AcademySettlementJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        $day = (int) date('j');
        $hasContracts = $this->db->selectOne(
            "SELECT 1 FROM academy_contracts WHERE status = 'active' AND settlement_day = ?",
            [$day]
        );
        return $hasContracts !== null;
    }

    public function run(): array
    {
        $today = (int) date('j');
        $period = date('Y-m', strtotime('-1 month'));
        $generated = 0;

        $contracts = $this->db->select(
            "SELECT id, academy_id, minimum_revenue_guarantee, club_commission_pct,
                    academy_share_pct, contract_type
             FROM academy_contracts
             WHERE status = 'active' AND settlement_day = ?",
            [$today]
        );

        foreach ($contracts as $contract) {
            $exists = $this->db->selectOne(
                "SELECT id FROM academy_settlements WHERE contract_id = ? AND period_month = ?",
                [(int) $contract['id'], $period]
            );
            if ($exists) {
                continue;
            }

            $revenue = $this->db->selectOne("
                SELECT COALESCE(SUM(s.total_amount), 0) AS total
                FROM activity_subscriptions s
                JOIN academy_enrollments ae ON ae.player_id = s.player_id AND ae.academy_id = ?
                WHERE s.subscription_month = ? AND s.status = 'paid'
            ", [(int) $contract['academy_id'], $period])['total'] ?? 0;

            $totalRevenue = (float) $revenue;
            $minimum = (float) $contract['minimum_revenue_guarantee'];
            $clubPct = (float) $contract['club_commission_pct'];
            $academyPct = (float) $contract['academy_share_pct'];

            $surplus = 0;
            $shortfall = 0;
            $clubCommission = 0;
            $academyShare = 0;
            $direction = 'balanced';
            $netAmount = 0;

            if ($totalRevenue >= $minimum) {
                $surplus = $totalRevenue - $minimum;
                $clubCommission = $totalRevenue * ($clubPct / 100);
                $academyShare = $surplus * ($academyPct / 100);
                $netAmount = $academyShare - $clubCommission;
                $direction = $netAmount > 0 ? 'club_pays_academy' : 'academy_pays_club';
                $netAmount = abs($netAmount);
            } else {
                $shortfall = $minimum - $totalRevenue;
                $direction = 'academy_pays_club';
                $netAmount = $shortfall;
            }

            $settlementNumber = 'STL-' . date('Ym') . '-' . str_pad((string) ($generated + 1), 3, '0', STR_PAD_LEFT);

            $this->db->insert('academy_settlements', [
                'settlement_number'    => $settlementNumber,
                'contract_id'          => (int) $contract['id'],
                'period_month'         => $period,
                'total_revenue'        => $totalRevenue,
                'minimum_guarantee'    => $minimum,
                'revenue_surplus'      => $surplus,
                'revenue_shortfall'    => $shortfall,
                'club_commission'      => $clubCommission,
                'academy_share'        => $academyShare,
                'net_amount'           => $netAmount,
                'direction'            => $direction,
                'status'               => 'draft',
            ]);
            $generated++;
        }

        return [
            'status'  => 'success',
            'message' => "Generated {$generated} academy settlements for period {$period}.",
        ];
    }
}
