<?php
declare(strict_types=1);

namespace App\Modules\Coaches\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Coaches\Models\Coach;
use App\Modules\Coaches\Models\CoachPerformanceMetric;
use App\Modules\Coaches\Services\CoachPerformanceService;

class CoachPerformanceController extends Controller
{
    /**
     * Performance dashboard - overview of all coaches.
     */
    public function dashboard(Request $request): Response
    {
        $this->authorize('coach.view_performance');

        $yearMonth = trim((string) $request->get('month', date('Y-m')));

        // Get ranking for the month
        $ranking = CoachPerformanceService::getRanking($yearMonth);

        // Available months (last 12)
        $months = [];
        for ($i = 0; $i < 12; $i++) {
            $m = date('Y-m', strtotime("-{$i} months"));
            $months[] = $m;
        }

        return $this->view('Coaches.Views.performance_dashboard', [
            'ranking'   => $ranking,
            'yearMonth' => $yearMonth,
            'months'    => $months,
        ]);
    }

    /**
     * Detailed performance view for a single coach.
     */
    public function detail(Request $request, int $id): Response
    {
        $this->authorize('coach.view_performance');

        $coach = Coach::findOrFail($id);

        $fromMonth = trim((string) $request->get('from', date('Y-m', strtotime('-6 months'))));
        $toMonth = trim((string) $request->get('to', date('Y-m')));

        $report = CoachPerformanceService::getPerformanceReport($id, $fromMonth, $toMonth);
        $summary = CoachPerformanceService::getCoachSummary($id);

        // Get rating averages
        $db = App::getInstance()->db();
        $ratingAverages = $db->selectOne(
            "SELECT AVG(rating) AS avg_rating, COUNT(*) AS total_ratings
             FROM coach_ratings WHERE coach_id = ? AND status = 'published'",
            [$id]
        );

        return $this->view('Coaches.Views.performance_detail', [
            'coach'          => $coach,
            'report'         => $report,
            'summary'        => $summary,
            'fromMonth'      => $fromMonth,
            'toMonth'        => $toMonth,
            'ratingAverages' => $ratingAverages,
        ]);
    }

    /**
     * Performance ranking view.
     */
    public function ranking(Request $request): Response
    {
        $this->authorize('coach.view_performance');

        $yearMonth = trim((string) $request->get('month', date('Y-m')));
        $ranking = CoachPerformanceService::getRanking($yearMonth);

        $months = [];
        for ($i = 0; $i < 12; $i++) {
            $months[] = date('Y-m', strtotime("-{$i} months"));
        }

        return $this->view('Coaches.Views.performance_ranking', [
            'ranking'   => $ranking,
            'yearMonth' => $yearMonth,
            'months'    => $months,
        ]);
    }

    /**
     * Trigger performance recalculation for a month (POST).
     */
    public function calculate(Request $request): Response
    {
        $this->authorize('coach.view_performance');

        $yearMonth = trim((string) $request->post('month', date('Y-m')));
        $coachId = $request->post('coach_id', '') !== '' ? (int) $request->post('coach_id') : null;

        try {
            if ($coachId) {
                CoachPerformanceService::calculateMonthlyMetrics($coachId, $yearMonth);
                return $this->redirect('/coach-performance/' . $coachId)->withSuccess("تم إعادة حساب أداء المدرب لشهر {$yearMonth}");
            } else {
                $count = CoachPerformanceService::calculateAllCoachesMetrics($yearMonth);
                return $this->redirect('/coach-performance?month=' . $yearMonth)->withSuccess("تم حساب أداء {$count} مدرب لشهر {$yearMonth}");
            }
        } catch (\Throwable $e) {
            return $this->back()->withError('حدث خطأ: ' . $e->getMessage());
        }
    }
}
