<?php
declare(strict_types=1);

namespace App\Modules\Disciplines\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class SportsDashboardController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();

        // Players summary
        $playerStats = $db->selectOne("
            SELECT
                COUNT(*) AS total,
                SUM(CASE WHEN card_status = 'active' THEN 1 ELSE 0 END) AS active,
                SUM(CASE WHEN card_status = 'suspended' THEN 1 ELSE 0 END) AS suspended,
                SUM(CASE WHEN card_status = 'revoked' THEN 1 ELSE 0 END) AS revoked,
                SUM(CASE WHEN card_status = 'inactive' THEN 1 ELSE 0 END) AS inactive
            FROM players WHERE is_archived = 0
        ") ?: ['total' => 0, 'active' => 0, 'suspended' => 0, 'revoked' => 0, 'inactive' => 0];

        // Active enrollments
        $enrollmentCount = $db->selectOne(
            "SELECT COUNT(*) AS total FROM academy_enrollments WHERE status = 'active'"
        )['total'] ?? 0;

        // This month subscriptions
        $currentMonth = date('Y-m');
        $subStats = $db->selectOne("
            SELECT
                COUNT(*) AS total,
                SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending,
                SUM(CASE WHEN status = 'overdue' THEN 1 ELSE 0 END) AS overdue,
                COALESCE(SUM(CASE WHEN status = 'paid' THEN total_amount ELSE 0 END), 0) AS collected,
                COALESCE(SUM(CASE WHEN status IN ('pending', 'overdue') THEN total_amount ELSE 0 END), 0) AS outstanding
            FROM activity_subscriptions
            WHERE subscription_month = ?
        ", [$currentMonth]) ?: ['total' => 0, 'paid' => 0, 'pending' => 0, 'overdue' => 0, 'collected' => 0, 'outstanding' => 0];

        $collectionRate = ($subStats['total'] > 0)
            ? round(((int) $subStats['paid'] / (int) $subStats['total']) * 100, 1)
            : 0;

        // Facility utilization (reservations this month)
        $monthStart = date('Y-m-01');
        $monthEnd = date('Y-m-t');
        $facilityStats = $db->selectOne("
            SELECT
                COUNT(*) AS total_reservations,
                COALESCE(SUM(total_amount), 0) AS revenue
            FROM reservations
            WHERE reservation_date BETWEEN ? AND ?
              AND status NOT IN ('cancelled')
        ", [$monthStart, $monthEnd]) ?: ['total_reservations' => 0, 'revenue' => 0];

        // Recent registrations (last 10)
        $recentPlayers = $db->select("
            SELECT id, full_name_ar, player_type, card_status, registration_serial, created_at
            FROM players
            WHERE is_archived = 0
            ORDER BY created_at DESC
            LIMIT 10
        ");

        // Unpaid subscriptions (pending + overdue this month)
        $unpaidSubs = $db->select("
            SELECT s.id, s.subscription_month, s.total_amount, s.status, s.due_date,
                   p.full_name_ar AS player_name, p.id AS player_id
            FROM activity_subscriptions s
            JOIN players p ON p.id = s.player_id
            WHERE s.subscription_month = ?
              AND s.status IN ('pending', 'overdue')
            ORDER BY s.due_date ASC
            LIMIT 15
        ", [$currentMonth]);

        // Expiring medical certs (next 30 days)
        $expiringMedical = $db->select("
            SELECT p.id, p.full_name_ar, p.medical_expiry_date, p.medical_status
            FROM players p
            WHERE p.is_archived = 0
              AND p.medical_expiry_date IS NOT NULL
              AND p.medical_expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
            ORDER BY p.medical_expiry_date ASC
            LIMIT 10
        ");

        // Academies count
        $academyCount = $db->selectOne(
            "SELECT COUNT(*) AS total FROM academies WHERE is_active = 1"
        )['total'] ?? 0;

        // Disciplines count
        $disciplineCount = $db->selectOne(
            "SELECT COUNT(*) AS total FROM sport_disciplines WHERE is_active = 1 AND is_archived = 0"
        )['total'] ?? 0;

        return $this->view('Disciplines.Views.sports_dashboard', [
            'playerStats'      => $playerStats,
            'enrollmentCount'  => $enrollmentCount,
            'subStats'         => $subStats,
            'collectionRate'   => $collectionRate,
            'facilityStats'    => $facilityStats,
            'recentPlayers'    => $recentPlayers,
            'unpaidSubs'       => $unpaidSubs,
            'expiringMedical'  => $expiringMedical,
            'academyCount'     => $academyCount,
            'disciplineCount'  => $disciplineCount,
            'currentMonth'     => $currentMonth,
        ]);
    }
}
