<?php
declare(strict_types=1);

namespace App\Modules\Training\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Training\Models\SessionFeedback;
use App\Modules\Training\Services\SessionFeedbackService;

class SessionFeedbackController extends Controller
{
    /**
     * Show the feedback submission form for a session.
     */
    public function create(Request $request, string $sessionId): Response
    {
        $this->authorize('training.submit_feedback');

        $db = App::getInstance()->db();
        $session = $db->selectOne("SELECT * FROM sessions WHERE id = ?", [(int) $sessionId]);

        if (!$session) {
            return $this->redirect('/sessions')->withError('الحصة غير موجودة');
        }

        // Get current player ID from auth
        $currentUser = App::getInstance()->session()->get('user');
        $playerId = (int) ($currentUser['member_id'] ?? $currentUser['id'] ?? 0);

        // Check if already rated
        $alreadyRated = SessionFeedback::hasPlayerRated((int) $sessionId, $playerId);

        return $this->view('Training.Views.feedback_form', [
            'session'      => $session,
            'playerId'     => $playerId,
            'alreadyRated' => $alreadyRated,
        ]);
    }

    /**
     * Store submitted feedback.
     */
    public function store(Request $request, string $sessionId): Response
    {
        $this->authorize('training.submit_feedback');

        $currentUser = App::getInstance()->session()->get('user');
        $playerId = (int) ($currentUser['member_id'] ?? $currentUser['id'] ?? 0);

        $data = [
            'session_id'       => (int) $sessionId,
            'player_id'        => $playerId,
            'rating'           => (int) $request->post('rating', 3),
            'energy_level'     => (string) $request->post('energy_level', 'medium'),
            'enjoyment_level'  => (int) $request->post('enjoyment_level', 3),
            'difficulty_level' => (int) $request->post('difficulty_level', 3),
            'comments_ar'      => (string) $request->post('comments_ar', ''),
            'is_anonymous'     => $request->post('is_anonymous') ? 1 : 0,
        ];

        $result = SessionFeedbackService::submitFeedback($data);

        if ($result['success']) {
            return $this->redirect('/sessions/' . $sessionId)->withSuccess($result['message']);
        }

        return $this->redirect('/session-feedback/' . $sessionId . '/create')->withError($result['message']);
    }

    /**
     * Show feedback report for a session (coach/admin view).
     */
    public function report(Request $request, string $sessionId): Response
    {
        $this->authorize('training.view_feedback');

        $db = App::getInstance()->db();
        $session = $db->selectOne("SELECT * FROM sessions WHERE id = ?", [(int) $sessionId]);

        if (!$session) {
            return $this->redirect('/sessions')->withError('الحصة غير موجودة');
        }

        $report = SessionFeedbackService::getSessionReport((int) $sessionId);

        return $this->view('Training.Views.feedback_report', [
            'session'  => $session,
            'averages' => $report['averages'],
            'entries'  => $report['entries'],
        ]);
    }

    /**
     * Show coach feedback summary over a date range.
     */
    public function coachSummary(Request $request, string $coachId): Response
    {
        $this->authorize('training.view_feedback');

        $dateFrom = (string) $request->get('date_from', date('Y-m-01'));
        $dateTo = (string) $request->get('date_to', date('Y-m-d'));

        $db = App::getInstance()->db();
        $coach = $db->selectOne("SELECT * FROM coaches WHERE id = ?", [(int) $coachId]);

        if (!$coach) {
            return $this->redirect('/coaches')->withError('المدرب غير موجود');
        }

        $summary = SessionFeedbackService::getCoachFeedbackSummary((int) $coachId, $dateFrom, $dateTo);

        return $this->view('Training.Views.feedback_report', [
            'session'  => null,
            'coach'    => $coach,
            'averages' => $summary['summary'],
            'entries'  => $summary['by_session'],
            'dateFrom' => $dateFrom,
            'dateTo'   => $dateTo,
            'isCoachSummary' => true,
        ]);
    }
}
