<?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;

        // Coaches stats
        $coachStats = $db->selectOne("
            SELECT
                COUNT(*) AS total,
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) AS active
            FROM coaches WHERE is_archived = 0
        ") ?: ['total' => 0, 'active' => 0];

        // Training sessions this week
        $weekStart = date('Y-m-d', strtotime('monday this week'));
        $weekEnd = date('Y-m-d', strtotime('sunday this week'));
        $sessionStats = $db->selectOne("
            SELECT
                COUNT(*) AS total,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed,
                SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled,
                SUM(CASE WHEN status = 'scheduled' THEN 1 ELSE 0 END) AS scheduled
            FROM training_sessions
            WHERE session_date BETWEEN ? AND ?
        ", [$weekStart, $weekEnd]) ?: ['total' => 0, 'completed' => 0, 'cancelled' => 0, 'scheduled' => 0];

        // Active contracts
        $contractStats = $db->selectOne("
            SELECT
                COUNT(*) AS total,
                SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active,
                SUM(CASE WHEN status = 'active' AND end_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) AS expiring_soon
            FROM academy_contracts
        ") ?: ['total' => 0, 'active' => 0, 'expiring_soon' => 0];

        // Training groups capacity
        $groupStats = $db->selectOne("
            SELECT
                COUNT(*) AS total,
                SUM(CASE WHEN is_full = 1 THEN 1 ELSE 0 END) AS full_groups,
                COALESCE(SUM(current_count), 0) AS total_players
            FROM training_groups
            WHERE is_active = 1
        ") ?: ['total' => 0, 'full_groups' => 0, 'total_players' => 0];

        // Pool utilization today
        $poolStats = $db->selectOne("
            SELECT
                COUNT(*) AS total_bookings,
                SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) AS confirmed,
                SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) AS in_progress
            FROM pool_bookings
            WHERE booking_date = CURDATE()
        ") ?: ['total_bookings' => 0, 'confirmed' => 0, 'in_progress' => 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,
            'coachStats'       => $coachStats,
            'sessionStats'     => $sessionStats,
            'contractStats'    => $contractStats,
            'groupStats'       => $groupStats,
            'poolStats'        => $poolStats,
        ]);
    }
}
