<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use App\Models\Tugas;
use App\Models\PengumpulanTugas;
use App\Models\Kelas;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class TugasController extends Controller
{
    public function index(): View
    {
        $siswa = auth()->user();
        $siswaProfile = $siswa->siswaProfile;
        $kelas = $siswaProfile ? $siswaProfile->kelas : null;

        $tugasList = collect();
        $submissions = collect();

        if ($kelas) {
            $kelasModel = Kelas::where('nama_kelas', $kelas)->first();
            if ($kelasModel) {
                $tugasList = Tugas::where('kelas_id', $kelasModel->id)
                    ->where('status', '!=', 'Draft')
                    ->with(['mataPelajaran', 'guru'])
                    ->latest()
                    ->get();

                $submissions = PengumpulanTugas::where('siswa_id', $siswa->id)
                    ->get()
                    ->keyBy('tugas_id');
            }
        }

        return view('siswa.tugas', [
            'tugasList' => $tugasList,
            'submissions' => $submissions,
            'kelas' => $kelas,
        ]);
    }

    public function show(Tugas $tugas): View
    {
        $siswa = auth()->user();
        $siswaProfile = $siswa->siswaProfile;
        $kelas = $siswaProfile ? $siswaProfile->kelas : null;

        // Verify authorization
        if (!$kelas || !$tugas->kelas || $tugas->kelas->nama_kelas !== $kelas) {
            abort(403, 'Anda tidak memiliki akses ke tugas kelas lain.');
        }

        $tugas->load(['mataPelajaran', 'guru']);

        $submission = PengumpulanTugas::where('tugas_id', $tugas->id)
            ->where('siswa_id', $siswa->id)
            ->first();

        return view('siswa.tugas-detail', [
            'tugas' => $tugas,
            'submission' => $submission,
            'kelas' => $kelas,
        ]);
    }

    public function submit(Request $request, Tugas $tugas): RedirectResponse
    {
        $siswa = auth()->user();
        $siswaProfile = $siswa->siswaProfile;
        $kelas = $siswaProfile ? $siswaProfile->kelas : null;

        if (!$kelas || !$tugas->kelas || $tugas->kelas->nama_kelas !== $kelas) {
            abort(403, 'Anda tidak memiliki akses ke tugas kelas lain.');
        }

        if ($tugas->status === 'Ditutup') {
            return back()->withErrors(['tugas' => 'Tugas ini sudah ditutup dan tidak menerima pengumpulan jawaban.']);
        }

        $request->validate([
            'file_jawaban' => ['required', 'file', 'mimes:pdf,doc,docx', 'max:10240'],
            'catatan_siswa' => ['nullable', 'string'],
        ]);

        $submission = PengumpulanTugas::where('tugas_id', $tugas->id)
            ->where('siswa_id', $siswa->id)
            ->first();

        if ($submission && $submission->status === 'Dinilai') {
            return back()->withErrors(['tugas' => 'Tugas ini sudah dinilai dan tidak dapat dikumpulkan kembali.']);
        }

        if ($request->hasFile('file_jawaban')) {
            // Store file in storage/app/public/jawaban for public download links.
            $path = $request->file('file_jawaban')->store('jawaban', 'public');
            $fileName = basename($path);

            if ($submission) {
                // Delete old file
                if ($submission->file_jawaban) {
                    Storage::disk('public')->delete('jawaban/' . $submission->file_jawaban);
                    Storage::delete('public/jawaban/' . $submission->file_jawaban);
                }
                $submission->update([
                    'file_jawaban' => $fileName,
                    'catatan_siswa' => $request->catatan_siswa,
                    'tanggal_pengumpulan' => now(),
                    'status' => 'Sudah Mengumpulkan',
                ]);
            } else {
                PengumpulanTugas::create([
                    'tugas_id' => $tugas->id,
                    'siswa_id' => $siswa->id,
                    'file_jawaban' => $fileName,
                    'catatan_siswa' => $request->catatan_siswa,
                    'tanggal_pengumpulan' => now(),
                    'status' => 'Sudah Mengumpulkan',
                ]);
            }
        }

        return redirect()
            ->route('siswa.tugas.show', $tugas)
            ->with('success', 'Tugas berhasil dikumpulkan.');
    }
}
