<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

class HomeworkController extends Controller
{
    private const MAX_FILE_BYTES = 10 * 1024 * 1024;

    private const ALLOWED_MIMES = [
        'application/pdf',
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'text/plain',
    ];

    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);
        $userId = $request->user()?->id;
        $studentId = $userId && $schoolId
            ? DB::table('students')->where('school_id', $schoolId)->where('user_id', $userId)->value('id')
            : null;

        $classroomIds = $studentId
            ? DB::table('class_students')
                ->where('school_id', $schoolId)
                ->where('student_id', $studentId)
                ->where('status', 'active')
                ->pluck('classroom_id')
            : collect();

        $homeworks = ($schoolId && $classroomIds->isNotEmpty())
            ? DB::table('homeworks')
                ->leftJoin('classrooms', 'classrooms.id', '=', 'homeworks.classroom_id')
                ->leftJoin('subjects', 'subjects.id', '=', 'homeworks.subject_id')
                ->leftJoin('homework_submissions', function ($join) use ($studentId): void {
                    $join->on('homework_submissions.homework_id', '=', 'homeworks.id')
                         ->where('homework_submissions.student_id', '=', $studentId);
                })
                ->whereIn('homeworks.classroom_id', $classroomIds)
                ->where('homeworks.school_id', $schoolId)
                ->where('homeworks.status', 'published')
                ->select([
                    'homeworks.id',
                    'homeworks.title',
                    'homeworks.description',
                    'homeworks.due_at',
                    'homeworks.allow_file_upload',
                    'classrooms.name as classroom_name',
                    'subjects.name as subject_name',
                    'homework_submissions.id as submission_id',
                    'homework_submissions.status as submission_status',
                    'homework_submissions.submitted_at',
                ])
                ->orderByDesc('homeworks.created_at')
                ->limit(30)
                ->get()
                ->map(fn ($hw): array => [
                    'id' => (int) $hw->id,
                    'title' => $hw->title,
                    'description' => $hw->description,
                    'dueAt' => $hw->due_at ? $this->jalaliDate($hw->due_at, true) : '—',
                    'allowFileUpload' => (bool) $hw->allow_file_upload,
                    'classroom' => $hw->classroom_name ?: '—',
                    'subject' => $hw->subject_name ?: '—',
                    'submitted' => (bool) $hw->submission_id,
                    'submissionStatus' => $hw->submission_status,
                    'submittedAt' => $hw->submitted_at ? $this->jalaliDate($hw->submitted_at, true) : null,
                ])
                ->values()
            : collect()->values();

        return Inertia::render('Student/Homeworks', [
            'homeworks' => $homeworks,
        ]);
    }

    public function store(Request $request, int $id): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 403);

        $userId = $request->user()?->id;
        $studentId = $userId
            ? DB::table('students')->where('school_id', $schoolId)->where('user_id', $userId)->value('id')
            : null;

        abort_unless($studentId, 403, 'دانش‌آموزی برای این کاربر ثبت نشده است.');

        $homework = DB::table('homeworks')
            ->where('school_id', $schoolId)
            ->where('id', $id)
            ->where('status', 'published')
            ->first();

        abort_unless($homework, 404);

        $inClass = DB::table('class_students')
            ->where('school_id', $schoolId)
            ->where('student_id', $studentId)
            ->where('classroom_id', $homework->classroom_id)
            ->where('status', 'active')
            ->exists();

        abort_unless($inClass, 403, 'شما در این کلاس نیستید.');

        $alreadySubmitted = DB::table('homework_submissions')
            ->where('homework_id', $id)
            ->where('student_id', $studentId)
            ->exists();

        if ($alreadySubmitted) {
            return back()->withErrors(['body' => 'قبلاً تکلیف را ارسال کرده‌اید.']);
        }

        $data = $request->validate([
            'body' => 'nullable|string|max:5000',
            'file' => 'nullable|file|max:10240',
        ]);

        $filePath = null;
        if ($request->hasFile('file') && $homework->allow_file_upload) {
            $file = $request->file('file');
            $mime = $file->getMimeType() ?? '';

            if (! in_array($mime, self::ALLOWED_MIMES, true)) {
                return back()->withErrors(['file' => 'نوع فایل مجاز نیست.']);
            }
            if ($file->getSize() > self::MAX_FILE_BYTES) {
                return back()->withErrors(['file' => 'حجم فایل بیش از ۱۰ مگابایت است.']);
            }

            $filePath = $file->store("schools/{$schoolId}/homeworks", 'local');
        }

        DB::table('homework_submissions')->insert([
            'school_id' => $schoolId,
            'homework_id' => $id,
            'student_id' => $studentId,
            'body' => $data['body'] ?? null,
            'file_path' => $filePath,
            'status' => 'submitted',
            'submitted_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return back()->with('success', 'تکلیف با موفقیت ارسال شد.');
    }
}
