<?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\CoachRating;
use App\Modules\Coaches\Services\CoachRatingService;

class CoachRatingController extends Controller
{
    /**
     * List ratings for a coach.
     */
    public function index(Request $request): Response
    {
        $this->authorize('coach.rate');

        $coachId = $request->get('coach_id', '') !== '' ? (int) $request->get('coach_id') : null;

        $filters = [
            'coach_id'   => $coachId,
            'status'     => trim((string) $request->get('status', '')),
            'min_rating' => $request->get('min_rating', '') !== '' ? (int) $request->get('min_rating') : null,
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = CoachRating::search($filters, 25, $page);

        $db = App::getInstance()->db();
        $coaches = $db->select(
            "SELECT id, full_name_ar FROM coaches WHERE is_active = 1 AND is_archived = 0 ORDER BY full_name_ar ASC"
        );

        $averages = null;
        $coach = null;
        if ($coachId) {
            $averages = CoachRating::getAverages($coachId);
            $coach = $db->selectOne("SELECT * FROM coaches WHERE id = ?", [$coachId]);
        }

        return $this->view('Coaches.Views.ratings', [
            'ratings'    => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
            'coaches'    => $coaches,
            'coach'      => $coach,
            'averages'   => $averages,
            'coachId'    => $coachId,
        ]);
    }

    /**
     * Show rating form for a coach.
     */
    public function create(Request $request): Response
    {
        $this->authorize('coach.rate');

        $coachId = (int) $request->get('coach_id', 0);
        $sessionId = $request->get('session_id', '') !== '' ? (int) $request->get('session_id') : null;

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

        $coaches = $db->select(
            "SELECT id, full_name_ar FROM coaches WHERE is_active = 1 AND is_archived = 0 ORDER BY full_name_ar ASC"
        );

        $players = $db->select(
            "SELECT id, full_name_ar, registration_serial FROM players WHERE is_archived = 0 ORDER BY full_name_ar ASC"
        );

        return $this->view('Coaches.Views.rate_coach', [
            'coach'     => $coach,
            'coaches'   => $coaches,
            'players'   => $players,
            'coachId'   => $coachId,
            'sessionId' => $sessionId,
        ]);
    }

    /**
     * Store a new rating.
     */
    public function store(Request $request): Response
    {
        $this->authorize('coach.rate');

        $data = [
            'coach_id'            => (int) $request->post('coach_id', 0),
            'player_id'           => (int) $request->post('player_id', 0),
            'session_id'          => $request->post('session_id', '') !== '' ? (int) $request->post('session_id') : null,
            'punctuality_score'   => (int) $request->post('punctuality_score', 0),
            'communication_score' => (int) $request->post('communication_score', 0),
            'technique_score'     => (int) $request->post('technique_score', 0),
            'motivation_score'    => (int) $request->post('motivation_score', 0),
            'feedback_ar'         => trim((string) $request->post('feedback_ar', '')),
            'is_anonymous'        => (int) $request->post('is_anonymous', 0),
        ];

        // Validation
        $errors = [];
        if ($data['coach_id'] <= 0) $errors[] = 'يجب اختيار المدرب';
        if ($data['player_id'] <= 0) $errors[] = 'يجب اختيار اللاعب';
        if ($data['punctuality_score'] < 1 || $data['punctuality_score'] > 5) $errors[] = 'تقييم الالتزام بالمواعيد يجب أن يكون من 1 إلى 5';
        if ($data['communication_score'] < 1 || $data['communication_score'] > 5) $errors[] = 'تقييم التواصل يجب أن يكون من 1 إلى 5';
        if ($data['technique_score'] < 1 || $data['technique_score'] > 5) $errors[] = 'تقييم الأسلوب الفني يجب أن يكون من 1 إلى 5';
        if ($data['motivation_score'] < 1 || $data['motivation_score'] > 5) $errors[] = 'تقييم التحفيز يجب أن يكون من 1 إلى 5';

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_old_input', $request->all());
            $alerts = array_map(fn($msg) => ['type' => 'error', 'message' => $msg], $errors);
            $session->flash('_alerts', $alerts);
            return $this->redirect('/coach-ratings/create?coach_id=' . $data['coach_id']);
        }

        try {
            CoachRatingService::submitRating($data);
            return $this->redirect('/coach-ratings?coach_id=' . $data['coach_id'])->withSuccess('تم إرسال التقييم بنجاح');
        } catch (\Throwable $e) {
            return $this->redirect('/coach-ratings/create?coach_id=' . $data['coach_id'])->withError($e->getMessage());
        }
    }

    /**
     * Flag a rating as inappropriate (POST).
     */
    public function flagRating(Request $request, int $id): Response
    {
        $this->authorize('coach.manage_ratings');

        $reason = trim((string) $request->post('reason', 'محتوى غير مناسب'));

        try {
            CoachRatingService::flagRating($id, $reason);
            return $this->back()->withSuccess('تم الإبلاغ عن التقييم');
        } catch (\Throwable $e) {
            return $this->back()->withError('حدث خطأ: ' . $e->getMessage());
        }
    }

    /**
     * Admin respond to a rating (POST).
     */
    public function respond(Request $request, int $id): Response
    {
        $this->authorize('coach.manage_ratings');

        $response = trim((string) $request->post('admin_response_ar', ''));
        if (empty($response)) {
            return $this->back()->withError('يجب كتابة الرد');
        }

        try {
            CoachRatingService::respondToRating($id, $response);
            return $this->back()->withSuccess('تم إضافة الرد');
        } catch (\Throwable $e) {
            return $this->back()->withError('حدث خطأ: ' . $e->getMessage());
        }
    }
}
