<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Siswa;
use App\Models\User;
use App\Services\ExcelImportService;
use App\Services\LaporanService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class SiswaController extends Controller
{
    public function __construct(
        protected ExcelImportService $importService,
        protected LaporanService $laporanService,
    ) {}

    public function index(Request $request)
    {
        $query = Siswa::with(['user', 'kelas.tingkatSekolah'])
            ->when($request->search, fn($q) =>
                $q->where('nama', 'like', '%' . $request->search . '%')
                ->orWhere('nis', 'like', '%' . $request->search . '%')
                ->orWhere('nisn', 'like', '%' . $request->search . '%')
            )
            ->when($request->kelas_id, fn($q) => $q->where('kelas_id', $request->kelas_id))
            ->when($request->boolean('tanpa_kelas'), fn($q) => $q->whereNull('kelas_id')) // ← tambah ini
            ->orderBy('nama');

        $data = $request->boolean('all') ? $query->get() : $query->paginate(15);

        return response()->json(['success' => true, 'data' => $data]);
    }

    // ← tambah method baru ini
    public function assignKelas(Request $request)
    {
        $request->validate([
            'siswa_ids'   => 'required|array|min:1',
            'siswa_ids.*' => 'exists:siswa,id',
            'kelas_id'    => 'required|exists:kelas,id',
        ]);

        DB::beginTransaction();
        try {
            $kelas    = \App\Models\Kelas::findOrFail($request->kelas_id);
            $jumlah   = count($request->siswa_ids);

            Siswa::whereIn('id', $request->siswa_ids)
                ->update(['kelas_id' => $request->kelas_id]);

            $kelas->increment('jumlah_siswa', $jumlah);

            DB::commit();
            return response()->json([
                'success' => true,
                'message' => "{$jumlah} siswa berhasil ditambahkan ke kelas {$kelas->nama}.",
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama'          => 'required|string|max:255',
            'email'         => 'required|email|unique:users,email',
            'password'      => 'required|string|min:6',
            'kelas_id'      => 'required|exists:kelas,id',
            'nis'           => 'nullable|string|max:20|unique:siswa,nis',
            'nisn'          => 'nullable|string|max:20|unique:siswa,nisn',
            'jenis_kelamin' => 'required|in:L,P',
            'no_hp'         => 'nullable|string|max:20',
            'alamat'        => 'nullable|string',
        ]);

        DB::beginTransaction();
        try {
            $user = User::create([
                'name'     => $request->nama,
                'email'    => $request->email,
                'password' => Hash::make($request->password),
                'role'     => 'siswa',
                'is_aktif' => true,
            ]);

            $siswa = Siswa::create([
                'user_id'      => $user->id,
                'kelas_id'     => $request->kelas_id,
                'nis'          => $request->nis,
                'nisn'         => $request->nisn,
                'nama'         => $request->nama,
                'jenis_kelamin'=> $request->jenis_kelamin,
                'no_hp'        => $request->no_hp,
                'alamat'       => $request->alamat,
            ]);

            // Update jumlah siswa di kelas
            $siswa->kelas->increment('jumlah_siswa');

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Siswa berhasil ditambahkan.', 'data' => $siswa->load(['user', 'kelas'])], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function show(Siswa $siswa)
    {
        $siswa->load(['user', 'kelas.tingkatSekolah', 'nilaiUjian.ujian']);
        return response()->json(['success' => true, 'data' => $siswa]);
    }

    public function update(Request $request, Siswa $siswa)
    {
        $request->validate([
            'nama'          => 'sometimes|string|max:255',
            'kelas_id'      => 'sometimes|exists:kelas,id',
            'nis'           => 'nullable|string|max:20|unique:siswa,nis,' . $siswa->id,
            'nisn'          => 'nullable|string|max:20|unique:siswa,nisn,' . $siswa->id,
            'jenis_kelamin' => 'sometimes|in:L,P',
            'no_hp'         => 'nullable|string|max:20',
            'alamat'        => 'nullable|string',
            'password'      => 'nullable|string|min:6',
        ]);

        DB::beginTransaction();
        try {
            $oldKelasId = $siswa->kelas_id;

            $siswa->update($request->only(['nama', 'kelas_id', 'nis', 'nisn', 'jenis_kelamin', 'no_hp', 'alamat']));

            if ($request->filled('nama')) {
                $siswa->user->update(['name' => $request->nama]);
            }

            if ($request->filled('password')) {
                $siswa->user->update(['password' => Hash::make($request->password)]);
            }

            // Update jumlah siswa jika pindah kelas
            if ($request->filled('kelas_id') && $oldKelasId != $request->kelas_id) {
                \App\Models\Kelas::find($oldKelasId)?->decrement('jumlah_siswa');
                \App\Models\Kelas::find($request->kelas_id)?->increment('jumlah_siswa');
            }

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data siswa berhasil diperbarui.', 'data' => $siswa->load(['user', 'kelas'])]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function destroy(Siswa $siswa)
    {
        DB::beginTransaction();
        try {
            $userId  = $siswa->user_id;
            $kelasId = $siswa->kelas_id;
            $siswa->delete();
            User::destroy($userId);
            \App\Models\Kelas::find($kelasId)?->decrement('jumlah_siswa');
            DB::commit();

            return response()->json(['success' => true, 'message' => 'Data siswa berhasil dihapus.']);
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function importExcel(Request $request)
    {
        $request->validate([
            'file'     => 'required|file|mimes:xlsx,xls|max:5120',
            'kelas_id' => 'required|exists:kelas,id',
        ]);

        $result = $this->importService->importSiswa($request->file('file'), $request->kelas_id);

        return response()->json([
            'success' => true,
            'message' => "Import selesai: {$result['berhasil']} berhasil, " . count($result['gagal']) . " gagal.",
            'data'    => $result,
        ]);
    }

    public function templateExcel()
    {
        return $this->laporanService->templateImportSiswa();
    }
}
