<?php

namespace App\Http\Controllers\Teacher;

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

class HomeworkController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);
        $teacherId = $schoolId ? $this->teacherId($request, (int) $schoolId) : null;

        $classes = $schoolId
            ? DB::table('classrooms')
                ->where('school_id', $schoolId)
                ->where('status', 'active')
                ->orderBy('name')
                ->get(['id', 'name'])
            : collect();

        $subjects = $schoolId
            ? DB::table('subjects')
                ->where('school_id', $schoolId)
                ->where('status', 'active')
                ->orderBy('name')
                ->get(['id', 'name'])
            : collect();

        $homeworks = ($schoolId && $teacherId)
            ? DB::table('homeworks')
                ->leftJoin('classrooms', 'classrooms.id', '=', 'homeworks.classroom_id')
                ->leftJoin('subjects', 'subjects.id', '=', 'homeworks.subject_id')
                ->where('homeworks.school_id', $schoolId)
                ->where('homeworks.teacher_id', $teacherId)
                ->select(['homeworks.id', 'homeworks.title', 'homeworks.status', 'homeworks.due_at', 'classrooms.name as classroom_name', 'subjects.name as subject_name'])
                ->latest('homeworks.created_at')
                ->limit(30)
                ->get()
                ->map(function ($hw) use ($schoolId): array {
                    $submissionCount = DB::table('homework_submissions')
                        ->where('school_id', $schoolId)
                        ->where('homework_id', $hw->id)
                        ->count();

                    return [
                        'id' => (int) $hw->id,
                        'title' => $hw->title,
                        'classroom' => $hw->classroom_name ?: '—',
                        'subject' => $hw->subject_name ?: '—',
                        'status' => $hw->status,
                        'dueAt' => $hw->due_at ? $this->jalaliDate($hw->due_at, true) : '—',
                        'submissionCount' => $submissionCount,
                    ];
                })
                ->values()
            : collect()->values();

        return Inertia::render('Teacher/Homeworks', [
            'homeworks' => $homeworks,
            'classes' => $classes->map(fn ($c): array => ['value' => $c->id, 'label' => $c->name])->values(),
            'subjects' => $subjects->map(fn ($s): array => ['value' => $s->id, 'label' => $s->name])->values(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $data = $request->validate([
            'title' => 'required|string|max:190',
            'classroom_id' => 'required|integer',
            'subject_id' => 'nullable|integer',
            'description' => 'nullable|string|max:2000',
            'due_at' => 'nullable|date',
            'allow_file_upload' => 'boolean',
        ]);

        $teacherId = $this->teacherId($request, (int) $schoolId);

        if (! $teacherId) {
            return back()->withErrors(['title' => 'برای کاربر فعلی معلمی ثبت نشده است.'])->withInput();
        }

        $classOk = DB::table('classrooms')->where('school_id', $schoolId)->where('id', $data['classroom_id'])->exists();
        if (! $classOk) {
            return back()->withErrors(['classroom_id' => 'کلاس برای این مدرسه معتبر نیست.'])->withInput();
        }

        if (! empty($data['subject_id'])) {
            $subjectOk = DB::table('subjects')->where('school_id', $schoolId)->where('id', $data['subject_id'])->exists();
            if (! $subjectOk) {
                return back()->withErrors(['subject_id' => 'درس برای این مدرسه معتبر نیست.'])->withInput();
            }
        }

        DB::table('homeworks')->insert([
            'school_id' => $schoolId,
            'classroom_id' => $data['classroom_id'],
            'subject_id' => $data['subject_id'] ?? null,
            'teacher_id' => $teacherId,
            'title' => $data['title'],
            'description' => $data['description'] ?? null,
            'due_at' => $data['due_at'] ?? null,
            'allow_file_upload' => $data['allow_file_upload'] ?? true,
            'status' => 'published',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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

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

        $teacherId = $this->teacherId($request, (int) $schoolId);

        $deleted = DB::table('homeworks')
            ->where('school_id', $schoolId)
            ->where('id', $id)
            ->when($teacherId, fn ($q) => $q->where('teacher_id', $teacherId))
            ->delete();

        abort_unless($deleted, 404);

        return back()->with('success', 'تکلیف حذف شد.');
    }

    private function teacherId(Request $request, int $schoolId): ?int
    {
        $userId = $request->user()?->id;

        return $userId
            ? DB::table('teachers')->where('school_id', $schoolId)->where('user_id', $userId)->value('id')
            : null;
    }
}
