<?php

namespace App\Http\Controllers;

use App\Models\MentorStudent;
use App\Models\MentorSetting;
use App\Models\Trade;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class StudentReviewController extends Controller
{
    public function index(Request $request): View
    {
        abort_unless(MentorSetting::enabled(), 404);

        $mentorLinks = MentorStudent::query()
            ->with('mentor')
            ->where('student_id', $request->user()->id)
            ->latest()
            ->get();

        $reviewedTrades = Trade::query()
            ->with('comments.mentor')
            ->where('user_id', $request->user()->id)
            ->whereHas('comments')
            ->latest()
            ->paginate(10);

        return view('student-reviews.index', [
            'mentorLinks' => $mentorLinks,
            'reviewedTrades' => $reviewedTrades,
        ]);
    }

    public function join(Request $request): RedirectResponse
    {
        abort_unless(MentorSetting::enabled(), 404);

        $data = $request->validate([
            'invite_code' => ['required', 'string', 'exists:mentor_students,invite_code'],
        ]);

        $invite = MentorStudent::query()
            ->where('invite_code', $data['invite_code'])
            ->where('status', 'invited')
            ->firstOrFail();

        if (filled($invite->student_email) && strtolower($invite->student_email) !== strtolower($request->user()->email)) {
            return back()->with('error', 'This invite code was created for a different email address.');
        }

        $invite->update([
            'student_id' => $request->user()->id,
            'status' => 'active',
            'joined_at' => now(),
        ]);

        if ($request->user()->role === 'user') {
            $request->user()->update(['role' => 'student']);
        }

        return redirect()->route('student.reviews.index')->with('success', 'You joined your mentor successfully.');
    }

    public function submit(Trade $trade, Request $request): RedirectResponse
    {
        abort_unless(MentorSetting::enabled(), 404);
        abort_unless($trade->user_id === $request->user()->id, 403);

        $hasMentor = MentorStudent::query()
            ->where('student_id', $request->user()->id)
            ->where('status', 'active')
            ->exists();

        if (! $hasMentor) {
            return redirect()->route('student.reviews.index')->with('error', 'Join a mentor before submitting trades for review.');
        }

        $trade->update([
            'review_status' => 'submitted',
            'submitted_for_review_at' => now(),
        ]);

        return redirect()->route('trades.show', $trade)->with('success', 'Trade submitted to your mentor for review.');
    }
}
