<?php
declare(strict_types=1);

namespace App\Modules\SportsDashboard\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\SportsDashboard\Services\DashboardMetricsService;
use App\Shared\Services\PdfExportService;

class SportsDashboardController extends Controller
{
    public function clubLevel(Request $request): Response
    {
        $this->authorize('sports_dashboard.view');

        $period = trim((string) $request->get('period', 'month'));
        $from = trim((string) $request->get('from', ''));
        $to = trim((string) $request->get('to', ''));

        $range = DashboardMetricsService::getDateRange($period, $from ?: null, $to ?: null);
        $start = $range['start'];
        $end = $range['end'];

        // Revenue with comparison
        $revenueComparison = DashboardMetricsService::getPreviousPeriodComparison($start, $end, 'revenue');

        // Player demographics
        $demographics = DashboardMetricsService::getPlayerDemographics();

        // Disciplines breakdown
        $disciplines = DashboardMetricsService::getDisciplineBreakdown($start, $end);

        // Facility utilization
        $facilities = DashboardMetricsService::getFacilityUtilization($start, $end);
        $avgUtilization = 0;
        if (!empty($facilities)) {
            $avgUtilization = round(array_sum(array_column($facilities, 'utilization')) / count($facilities), 1);
        }

        return $this->view('SportsDashboard.Views.club_dashboard', [
            'period'            => $period,
            'from'              => $from,
            'to'                => $to,
            'start'             => $start,
            'end'               => $end,
            'revenueComparison' => $revenueComparison,
            'demographics'      => $demographics,
            'disciplines'       => $disciplines,
            'facilities'        => $facilities,
            'avgUtilization'    => $avgUtilization,
            'baseUrl'           => '/sports-dashboard',
            'export'            => false,
        ]);
    }

    public function sportLevel(Request $request, string $id): Response
    {
        $this->authorize('sports_dashboard.view');
        $db = App::getInstance()->db();

        $discipline = $db->selectOne("SELECT * FROM disciplines WHERE id = ? AND is_archived = 0", [(int) $id]);
        if (!$discipline) {
            return $this->redirect('/sports-dashboard')->withError('الرياضة غير موجودة');
        }

        $period = trim((string) $request->get('period', 'month'));
        $from = trim((string) $request->get('from', ''));
        $to = trim((string) $request->get('to', ''));

        $range = DashboardMetricsService::getDateRange($period, $from ?: null, $to ?: null);
        $start = $range['start'];
        $end = $range['end'];

        // Revenue for this discipline
        $revenueComparison = DashboardMetricsService::getPreviousPeriodComparison($start, $end, 'revenue', null, (int) $id);

        // Players for this discipline
        $demographics = DashboardMetricsService::getPlayerDemographics((int) $id);

        // Coaches for this discipline
        $coaches = DashboardMetricsService::getCoachesForDiscipline((int) $id, $start, $end);

        // Session count
        $sessionCount = $db->selectOne("
            SELECT COUNT(*) AS cnt FROM facility_zone_schedules
            WHERE discipline_id = ? AND schedule_date BETWEEN ? AND ?
        ", [(int) $id, $start, $end]);

        // Linked academies
        $academies = $db->select("
            SELECT a.id, a.name_ar, COUNT(DISTINCT ae.player_id) AS player_count
            FROM academies a
            LEFT JOIN academy_enrollments ae ON ae.academy_id = a.id AND ae.status = 'active'
            WHERE a.discipline_id = ? AND a.is_archived = 0
            GROUP BY a.id, a.name_ar
        ", [(int) $id]);

        return $this->view('SportsDashboard.Views.sport_dashboard', [
            'discipline'        => $discipline,
            'period'            => $period,
            'from'              => $from,
            'to'                => $to,
            'start'             => $start,
            'end'               => $end,
            'revenueComparison' => $revenueComparison,
            'demographics'      => $demographics,
            'coaches'           => $coaches,
            'sessionCount'      => (int) ($sessionCount['cnt'] ?? 0),
            'academies'         => $academies,
            'baseUrl'           => '/sports-dashboard/sport/' . $id,
            'export'            => false,
        ]);
    }

    public function facilityLevel(Request $request, string $id): Response
    {
        $this->authorize('sports_dashboard.view');
        $db = App::getInstance()->db();

        $facility = $db->selectOne("SELECT * FROM facilities WHERE id = ? AND is_archived = 0", [(int) $id]);
        if (!$facility) {
            return $this->redirect('/sports-dashboard')->withError('المرفق غير موجود');
        }

        $period = trim((string) $request->get('period', 'month'));
        $from = trim((string) $request->get('from', ''));
        $to = trim((string) $request->get('to', ''));

        $range = DashboardMetricsService::getDateRange($period, $from ?: null, $to ?: null);
        $start = $range['start'];
        $end = $range['end'];

        // Revenue for this facility
        $revenueComparison = DashboardMetricsService::getPreviousPeriodComparison($start, $end, 'revenue', (int) $id);

        // Bookings count
        $bookings = $db->selectOne("
            SELECT COUNT(*) AS cnt FROM reservations
            WHERE facility_id = ? AND reservation_date BETWEEN ? AND ? AND status NOT IN ('cancelled')
        ", [(int) $id, $start, $end]);

        // Utilization
        $utilization = DashboardMetricsService::getFacilityUtilization($start, $end, (int) $id);
        $utilizationRate = !empty($utilization) ? $utilization[0]['utilization'] : 0;

        // Popular time slots
        $popularSlots = DashboardMetricsService::getPopularTimeSlots((int) $id, $start, $end);

        return $this->view('SportsDashboard.Views.facility_dashboard', [
            'facility'          => $facility,
            'period'            => $period,
            'from'              => $from,
            'to'                => $to,
            'start'             => $start,
            'end'               => $end,
            'revenueComparison' => $revenueComparison,
            'bookingsCount'     => (int) ($bookings['cnt'] ?? 0),
            'utilizationRate'   => $utilizationRate,
            'popularSlots'      => $popularSlots,
            'baseUrl'           => '/sports-dashboard/facility/' . $id,
            'export'            => false,
        ]);
    }

    public function export(Request $request): Response
    {
        $this->authorize('sports_dashboard.export');

        $level = trim((string) $request->get('level', 'club'));
        $referenceId = (int) $request->get('reference_id', '0');
        $period = trim((string) $request->get('period', 'month'));
        $from = trim((string) $request->get('from', ''));
        $to = trim((string) $request->get('to', ''));

        $range = DashboardMetricsService::getDateRange($period, $from ?: null, $to ?: null);
        $start = $range['start'];
        $end = $range['end'];

        $db = App::getInstance()->db();

        if ($level === 'sport' && $referenceId > 0) {
            $discipline = $db->selectOne("SELECT * FROM disciplines WHERE id = ?", [$referenceId]);
            $revenueComparison = DashboardMetricsService::getPreviousPeriodComparison($start, $end, 'revenue', null, $referenceId);
            $demographics = DashboardMetricsService::getPlayerDemographics($referenceId);
            $coaches = DashboardMetricsService::getCoachesForDiscipline($referenceId, $start, $end);
            $title = 'تقرير الرياضة: ' . ($discipline['name_ar'] ?? '');
        } elseif ($level === 'facility' && $referenceId > 0) {
            $facility = $db->selectOne("SELECT * FROM facilities WHERE id = ?", [$referenceId]);
            $revenueComparison = DashboardMetricsService::getPreviousPeriodComparison($start, $end, 'revenue', $referenceId);
            $bookings = $db->selectOne("SELECT COUNT(*) AS cnt FROM reservations WHERE facility_id = ? AND reservation_date BETWEEN ? AND ? AND status NOT IN ('cancelled')", [$referenceId, $start, $end]);
            $popularSlots = DashboardMetricsService::getPopularTimeSlots($referenceId, $start, $end);
            $title = 'تقرير المرفق: ' . ($facility['name_ar'] ?? '');
        } else {
            $revenueComparison = DashboardMetricsService::getPreviousPeriodComparison($start, $end, 'revenue');
            $demographics = DashboardMetricsService::getPlayerDemographics();
            $disciplines = DashboardMetricsService::getDisciplineBreakdown($start, $end);
            $facilities = DashboardMetricsService::getFacilityUtilization($start, $end);
            $title = 'تقرير لوحة المعلومات الرياضية';
        }

        // Build export HTML
        $html = $this->buildExportHtml($level, $title, $start, $end, $revenueComparison ?? [], $demographics ?? [], $disciplines ?? [], $facilities ?? [], $coaches ?? [], $bookings ?? [], $popularSlots ?? []);

        $filename = 'sports_dashboard_' . $level . '_' . date('Ymd_His') . '.pdf';

        return PdfExportService::renderToPdf($html, $filename);
    }

    private function buildExportHtml(string $level, string $title, string $start, string $end, array $revenueComparison, array $demographics, array $disciplines, array $facilities, array $coaches, array $bookings, array $popularSlots): string
    {
        $html = '<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="utf-8"><title>' . htmlspecialchars($title) . '</title>';
        $html .= '<style>body{font-family:Arial,sans-serif;padding:30px;direction:rtl;} table{width:100%;border-collapse:collapse;margin:15px 0;} th,td{border:1px solid #ddd;padding:8px;text-align:right;font-size:13px;} th{background:#f5f5f5;} .header{text-align:center;margin-bottom:30px;} .stat{display:inline-block;width:22%;text-align:center;padding:15px;margin:5px;border:1px solid #ddd;border-radius:8px;}</style>';
        $html .= '</head><body>';
        $html .= '<div class="header"><h2>' . htmlspecialchars($title) . '</h2>';
        $html .= '<p>الفترة: ' . $start . ' إلى ' . $end . ' | تاريخ التقرير: ' . date('Y-m-d H:i') . '</p></div>';

        // Revenue KPI
        if (!empty($revenueComparison)) {
            $arrow = $revenueComparison['direction'] === 'up' ? '&#x25B2;' : '&#x25BC;';
            $html .= '<div style="text-align:center;margin:20px 0;">';
            $html .= '<div class="stat"><strong>' . number_format($revenueComparison['current'], 2) . ' ج.م</strong><br>الإيرادات الحالية</div>';
            $html .= '<div class="stat"><strong>' . number_format($revenueComparison['previous'], 2) . ' ج.م</strong><br>الفترة السابقة</div>';
            $html .= '<div class="stat"><strong>' . $arrow . ' ' . $revenueComparison['change_pct'] . '%</strong><br>نسبة التغيير</div>';
            $html .= '</div>';
        }

        // Demographics
        if (!empty($demographics) && ($demographics['total'] ?? 0) > 0) {
            $html .= '<div style="text-align:center;margin:20px 0;">';
            $html .= '<div class="stat"><strong>' . $demographics['total'] . '</strong><br>إجمالي اللاعبين</div>';
            $html .= '<div class="stat"><strong>' . $demographics['members'] . '</strong><br>أعضاء</div>';
            $html .= '<div class="stat"><strong>' . $demographics['non_members'] . '</strong><br>غير أعضاء</div>';
            $html .= '</div>';
        }

        // Disciplines table
        if (!empty($disciplines)) {
            $html .= '<h3>الرياضات</h3><table><tr><th>الرياضة</th><th>الإيرادات</th><th>عدد اللاعبين</th></tr>';
            foreach ($disciplines as $d) {
                $html .= '<tr><td>' . htmlspecialchars($d['name_ar'] ?? '') . '</td><td>' . number_format((float) ($d['revenue'] ?? 0), 2) . '</td><td>' . (int) ($d['player_count'] ?? 0) . '</td></tr>';
            }
            $html .= '</table>';
        }

        // Facilities table
        if (!empty($facilities)) {
            $html .= '<h3>المرافق</h3><table><tr><th>المرفق</th><th>الحجوزات</th><th>نسبة الإشغال</th></tr>';
            foreach ($facilities as $f) {
                $html .= '<tr><td>' . htmlspecialchars($f['name_ar'] ?? '') . '</td><td>' . (int) ($f['booked_slots'] ?? 0) . '</td><td>' . ($f['utilization'] ?? 0) . '%</td></tr>';
            }
            $html .= '</table>';
        }

        // Coaches table
        if (!empty($coaches)) {
            $html .= '<h3>المدربين</h3><table><tr><th>المدرب</th><th>عدد الحصص</th></tr>';
            foreach ($coaches as $c) {
                $html .= '<tr><td>' . htmlspecialchars($c['name_ar'] ?? '') . '</td><td>' . (int) ($c['session_count'] ?? 0) . '</td></tr>';
            }
            $html .= '</table>';
        }

        // Popular slots
        if (!empty($popularSlots)) {
            $html .= '<h3>الأوقات الأكثر حجزاً</h3><table><tr><th>الساعة</th><th>عدد الحجوزات</th><th>الإيرادات</th></tr>';
            foreach ($popularSlots as $slot) {
                $html .= '<tr><td>' . (int) $slot['hour_slot'] . ':00</td><td>' . (int) $slot['booking_count'] . '</td><td>' . number_format((float) ($slot['revenue'] ?? 0), 2) . '</td></tr>';
            }
            $html .= '</table>';
        }

        $html .= '</body></html>';
        return $html;
    }
}
