<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Siswa;
use App\Models\Absensi;
use Carbon\Carbon;
use App\Imports\SiswaImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;

class SiswaController extends Controller
{
    /**
     * TAMPILKAN DATA SISWA + FILTER + PAGINATION
     */
    public function index(Request $request)
    {
        $query = Siswa::where('kelas', '!=', 'Lulus');

        if ($request->filled('kelas')) {
            $query->where('kelas', $request->kelas);
        }

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('nama', 'like', '%' . $request->search . '%')
                    ->orWhere('nisn', 'like', '%' . $request->search . '%');
            });
        }

        // 15 per halaman — bisa diganti sesuai kebutuhan
        $siswas = $query->orderBy('kelas')->orderBy('nama')->paginate(10)->withQueryString();

        $totalSiswa     = Siswa::where('kelas', '!=', 'Lulus')->count();
        $totalLaki      = Siswa::where('kelas', '!=', 'Lulus')->where('jenis_kelamin', 'L')->count();
        $totalPerempuan = Siswa::where('kelas', '!=', 'Lulus')->where('jenis_kelamin', 'P')->count();
        $jumlahKelas    = Siswa::where('kelas', '!=', 'Lulus')->distinct('kelas')->count('kelas');

        return view('siswa.index', compact(
            'siswas',
            'totalSiswa',
            'totalLaki',
            'totalPerempuan',
            'jumlahKelas'
        ));
    }

    /**
     * CETAK QR SATUAN
     */
    public function cetakQr($id)
    {
        $siswas = Siswa::where('id', $id)->get();
        return view('siswa.siswa_cetak', compact('siswas'));
    }

    /**
     * CETAK QR MASSAL
     */
    public function cetakSemua(Request $request)
    {
        $query = Siswa::where('kelas', '!=', 'Lulus');

        if ($request->filled('kelas')) {
            $query->where('kelas', $request->kelas);
        }

        $siswas = $query->orderBy('kelas')->orderBy('nama')->get();
        return view('siswa.siswa_cetak', compact('siswas'));
    }

    /**
     * TAMBAH DATA SISWA
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'nisn'          => 'required|unique:siswas,nisn',
            'nama'          => 'required',
            'kelas'         => 'required|in:VII-A,VII-B,VII-C,VII-D,VIII-A,VIII-B,VIII-C,VIII-D,IX-A,IX-B,IX-C,IX-D',
            'jenis_kelamin' => 'required|in:L,P',
        ], [
            'nisn.unique' => 'NISN sudah terdaftar!',
            'kelas.in'    => 'Kelas tidak valid.',
            'required'    => 'Kolom ini wajib diisi.',
        ]);

        $validated['nisn']    = str_pad($validated['nisn'], 10, '0', STR_PAD_LEFT);
        $validated['qr_code'] = 'MTs-' . $validated['nisn'];

        try {
            Siswa::create($validated);

            return redirect()->route('admin.siswa.index')
                ->with('success', 'Data siswa berhasil ditambahkan');
        } catch (\Exception $e) {
            return back()->withInput()->withErrors([
                'msg' => 'Gagal menambahkan data siswa: ' . $e->getMessage(),
            ]);
        }
    }

    /**
     * UPDATE DATA SISWA
     */
    public function update(Request $request, $id)
    {
        // Seluruh proses (termasuk findOrFail) dibungkus try-catch supaya
        // data yang sudah terhapus/tidak ditemukan tetap menghasilkan
        // notifikasi "Gagal!", bukan halaman error 404 polos.
        try {
            $siswa = Siswa::findOrFail($id);

            $validated = $request->validate([
                'nisn'          => 'required|unique:siswas,nisn,' . $id,
                'nama'          => 'required',
                'kelas'         => 'required|in:VII-A,VII-B,VII-C,VII-D,VIII-A,VIII-B,VIII-C,VIII-D,IX-A,IX-B,IX-C,IX-D',
                'jenis_kelamin' => 'required|in:L,P',
            ], [
                'nisn.unique' => 'NISN sudah digunakan siswa lain!',
                'kelas.in'    => 'Kelas tidak valid.',
                'required'    => 'Kolom ini wajib diisi.',
            ]);

            $validated['nisn']    = str_pad($validated['nisn'], 10, '0', STR_PAD_LEFT);
            $validated['qr_code'] = 'MTs-' . $validated['nisn'];

            $siswa->update($validated);

            return redirect()->route('admin.siswa.index')
                ->with('success', 'Data berhasil diperbarui');
        } catch (\Illuminate\Validation\ValidationException $e) {
            // Biarkan Laravel menangani seperti biasa (redirect back dengan
            // $errors bag) — Blade sudah punya handler khusus untuk ini.
            throw $e;
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()->route('admin.siswa.index')->withErrors([
                'msg' => 'Gagal memperbarui: data siswa tidak ditemukan (mungkin sudah dihapus).',
            ]);
        } catch (\Exception $e) {
            return back()->withInput()->withErrors([
                'msg' => 'Gagal memperbarui data: ' . $e->getMessage(),
            ]);
        }
    }

    /**
     * HAPUS DATA SISWA
     */
    public function destroy($id)
    {
        try {
            $siswa = Siswa::findOrFail($id);

            // Hapus histori absensi terkait dulu (sama seperti kosongkanKelas())
            // supaya tidak kena foreign key constraint saat menghapus siswa.
            DB::transaction(function () use ($siswa) {
                Absensi::where('siswa_id', $siswa->id)->delete();
                $siswa->delete();
            });

            return redirect()->route('admin.siswa.index')
                ->with('success', 'Data berhasil dihapus');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()->route('admin.siswa.index')->withErrors([
                'msg' => 'Gagal menghapus: data siswa tidak ditemukan (mungkin sudah dihapus sebelumnya).',
            ]);
        } catch (\Exception $e) {
            return back()->withErrors([
                'msg' => 'Gagal menghapus data: ' . $e->getMessage(),
            ]);
        }
    }

    /**
     * KENAIKAN KELAS OTOMATIS
     */
    public function naikKelas()
    {
        try {
            DB::transaction(function () {
                Siswa::where('kelas', 'like', 'IX-%')->update(['kelas' => 'Lulus']);

                $kelas8 = Siswa::where('kelas', 'like', 'VIII-%')->get();
                foreach ($kelas8 as $siswa) {
                    $siswa->update(['kelas' => str_replace('VIII-', 'IX-', $siswa->kelas)]);
                }

                $kelas7 = Siswa::where('kelas', 'like', 'VII-%')->get();
                foreach ($kelas7 as $siswa) {
                    $siswa->update(['kelas' => str_replace('VII-', 'VIII-', $siswa->kelas)]);
                }
            });

            return redirect()->route('admin.siswa.index')
                ->with('success', 'Proses kenaikan kelas berhasil dilakukan!');
        } catch (\Exception $e) {
            return back()->withErrors(['msg' => 'Gagal memproses kenaikan kelas: ' . $e->getMessage()]);
        }
    }

    /**
     * IMPORT DATA SISWA (EXCEL)
     */
    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv',
        ], [
            'file.required' => 'Pilih file Excel terlebih dahulu.',
            'file.mimes'    => 'Format file harus .xlsx, .xls, atau .csv',
        ]);

        try {
            $import = new SiswaImport;
            Excel::import($import, $request->file('file'));

            $jumlahBerhasil = count($import->berhasil);
            $jumlahGagal    = count($import->gagal);

            $detailGagal = collect($import->gagal)->map(function ($g) {
                return "• {$g['nama']} (NISN: {$g['baris']}): {$g['alasan']}";
            })->implode('||');

            $skippedErrors = collect($import->errors())->map(function ($e) {
                return '• ' . $e->getMessage();
            })->implode('||');

            return redirect()->route('admin.siswa.index')
                ->with('import_berhasil', $jumlahBerhasil)
                ->with('import_gagal',    $jumlahGagal)
                ->with('import_detail',   $detailGagal)
                ->with('import_errors',   $skippedErrors);
        } catch (\Exception $e) {
            return back()->with('import_fatal', $e->getMessage());
        }
    }

    /**
     * KOSONGKAN KELAS
     */
    public function kosongkanKelas(Request $request)
    {
        $request->validate([
            'kelas' => 'required|string',
        ], [
            'kelas.required' => 'Pilih kelas yang ingin dikosongkan.',
        ]);

        try {
            DB::transaction(function () use ($request) {
                $ids = Siswa::where('kelas', $request->kelas)->pluck('id');
                Absensi::whereIn('siswa_id', $ids)->delete();
                Siswa::where('kelas', $request->kelas)->delete();
            });

            return redirect()->route('admin.siswa.index')
                ->with('success', "Semua siswa kelas {$request->kelas} berhasil dihapus.");
        } catch (\Exception $e) {
            return back()->withErrors(['msg' => 'Gagal mengosongkan kelas: ' . $e->getMessage()]);
        }
    }
}
