<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

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

class DashboardController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');

        $branchScope = '';
        $branchParams = [];
        if (function_exists('branch_scope')) {
            $branchScope = branch_scope('', 'branch_id');
            $branchParams = branch_params();
        }

        $stats = $db->selectOne("
            SELECT
                (SELECT COUNT(*) FROM sa_disciplines WHERE is_active = 1) as active_disciplines,
                (SELECT COUNT(*) FROM sa_facilities WHERE is_active = 1 AND is_archived = 0) as active_facilities,
                (SELECT COUNT(*) FROM sa_facility_units WHERE is_active = 1) as active_units,
                (SELECT COUNT(*) FROM sa_coaches WHERE is_active = 1 AND is_archived = 0) as active_coaches,
                (SELECT COUNT(*) FROM sa_players WHERE is_archived = 0{$branchScope}) as total_players,
                (SELECT COUNT(*) FROM sa_groups WHERE status = 'active' AND is_archived = 0) as active_groups,
                (SELECT COUNT(*) FROM sa_group_players WHERE status = 'active') as enrolled_players,
                (SELECT COUNT(*) FROM sa_bookings WHERE booking_date = ? AND status NOT IN ('cancelled','no_show'){$branchScope}) as today_bookings,
                (SELECT COUNT(*) FROM sa_player_documents WHERE document_type = 'medical_cert' AND approval_status = 'pending') as pending_medical,
                (SELECT COUNT(*) FROM sa_subscriptions WHERE payment_status IN ('unpaid','overdue') AND period_end < ?) as overdue_subscriptions
        ", array_merge([$today], $branchParams, $branchParams, [$today]));

        return $this->view('SportsActivity.Views.dashboard', [
            'stats' => [
                'active_disciplines'    => (int) ($stats['active_disciplines'] ?? 0),
                'active_facilities'     => (int) ($stats['active_facilities'] ?? 0),
                'active_units'          => (int) ($stats['active_units'] ?? 0),
                'active_coaches'        => (int) ($stats['active_coaches'] ?? 0),
                'total_players'         => (int) ($stats['total_players'] ?? 0),
                'active_groups'         => (int) ($stats['active_groups'] ?? 0),
                'enrolled_players'      => (int) ($stats['enrolled_players'] ?? 0),
                'today_bookings'        => (int) ($stats['today_bookings'] ?? 0),
                'pending_medical'       => (int) ($stats['pending_medical'] ?? 0),
                'overdue_subscriptions' => (int) ($stats['overdue_subscriptions'] ?? 0),
            ],
            'today' => $today,
        ]);
    }
}
