<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SiswaModel;

class Siswa extends BaseController
{
    protected $siswaModel;

    public function __construct()
    {
        $this->siswaModel = new SiswaModel();
    }

    // =====================
    // PARSE KELAS
    // =====================
    private function parseKelas($kelas)
    {
        $kelas = strtoupper(trim($kelas));

        $romawi = [
            'XII' => 12,
            'XI'  => 11,
            'X'   => 10,
        ];

        $kelasSub = 0;

        if (strpos($kelas, '.') !== false) {
            [$kls, $sub] = explode('.', $kelas);
            $kelasSub = (int) $sub;
        } else {
            $kls = $kelas;
        }

        $kelasAngka = $romawi[$kls] ?? (int) $kls;

        return [$kelasAngka, $kelasSub];
    }

    // =====================
    // UPLOAD FOTO (HARD LIMIT 2MB)
    // =====================
    private function uploadFoto($file, $folder)
    {
        if (! $file || ! $file->isValid()) {
            return null;
        }

        // HARD BLOCK > 2MB
        if ($file->getSize() > 2 * 1024 * 1024) {
            throw new \RuntimeException('Ukuran foto maksimal 2 MB');
        }

        $newName = $file->getRandomName();
        $path = $folder . '/' . $newName;

        \Config\Services::image()
            ->withFile($file)
            ->resize(800, 800, true, 'width')
            ->save($path, 75);

        return $newName;
    }

    // =====================
    // LIST
    // =====================
    public function index()
    {
        return view('admin/siswa/index', [
            'title' => 'Data Siswa',
            'items' => $this->siswaModel
                ->orderBy('kelas_angka', 'DESC')
                ->orderBy('kelas_sub', 'ASC')
                ->orderBy('nama', 'ASC')
                ->findAll(),
        ]);
    }

    // =====================
    // FORM TAMBAH
    // =====================
    public function create()
    {
        return view('admin/siswa/form', [
            'title'  => 'Tambah Siswa',
            'item'   => null,
            'errors' => session()->getFlashdata('errors'),
        ]);
    }

    // =====================
    // SIMPAN
    // =====================
    public function store()
    {
        $rules = [
            'nama'     => 'required|min_length[3]',
            'nisn'     => 'required|min_length[5]',
            'kelas'    => 'required',
            'angkatan' => 'required',
            'foto'     => 'permit_empty|is_image[foto]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->validator->getErrors());
        }

        try {
            [$kelasAngka, $kelasSub] = $this->parseKelas(
                $this->request->getPost('kelas')
            );

            $fotoName = $this->uploadFoto(
                $this->request->getFile('foto'),
                'uploads/siswa'
            );

            $this->siswaModel->insert([
                'nama'        => $this->request->getPost('nama'),
                'nisn'        => $this->request->getPost('nisn'),
                'kelas'       => $this->request->getPost('kelas'),
                'kelas_angka' => $kelasAngka,
                'kelas_sub'   => $kelasSub,
                'angkatan'    => $this->request->getPost('angkatan'),
                'foto'        => $fotoName,
            ]);

        } catch (\RuntimeException $e) {
            return redirect()->back()
                ->withInput()
                ->with('errors', ['foto' => $e->getMessage()]);
        }

        return redirect()->to(base_url('admin/siswa'))
            ->with('success', 'Data siswa berhasil ditambahkan');
    }

    // =====================
    // UPDATE (FOTO LAMA AMAN)
    // =====================
    public function update($id)
    {
        $item = $this->siswaModel->find($id);

        if (! $item) {
            return redirect()->to(base_url('admin/siswa'));
        }

        $rules = [
            'nama'     => 'required|min_length[3]',
            'nisn'     => 'required|min_length[5]',
            'kelas'    => 'required',
            'angkatan' => 'required',
            'foto'     => 'permit_empty|is_image[foto]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->validator->getErrors());
        }

        try {
            [$kelasAngka, $kelasSub] = $this->parseKelas(
                $this->request->getPost('kelas')
            );

            // DEFAULT: pakai foto lama
            $fotoName = $item['foto'];
            $foto = $this->request->getFile('foto');

            // HANYA JIKA UPLOAD FOTO BARU
            if ($foto && $foto->isValid() && $foto->getSize() > 0) {

                // upload dulu foto baru
                $newFoto = $this->uploadFoto($foto, 'uploads/siswa');

                // kalau berhasil → hapus foto lama
                if ($newFoto && $item['foto'] && is_file('uploads/siswa/' . $item['foto'])) {
                    unlink('uploads/siswa/' . $item['foto']);
                }

                $fotoName = $newFoto;
            }

            $this->siswaModel->update($id, [
                'nama'        => $this->request->getPost('nama'),
                'nisn'        => $this->request->getPost('nisn'),
                'kelas'       => $this->request->getPost('kelas'),
                'kelas_angka' => $kelasAngka,
                'kelas_sub'   => $kelasSub,
                'angkatan'    => $this->request->getPost('angkatan'),
                'foto'        => $fotoName,
            ]);

        } catch (\RuntimeException $e) {
            return redirect()->back()
                ->withInput()
                ->with('errors', ['foto' => $e->getMessage()]);
        }

        return redirect()->to(base_url('admin/siswa'))
            ->with('success', 'Data siswa berhasil diperbarui');
    }
  // =====================
    // FORM EDIT (WAJIB ADA)
    // =====================
    public function edit($id)
    {
        $item = $this->siswaModel->find($id);

        if (! $item) {
            return redirect()->to(base_url('admin/siswa'))
                ->with('error', 'Data tidak ditemukan');
        }

        return view('admin/siswa/form', [
            'title'  => 'Edit Siswa',
            'item'   => $item,
            'errors' => session()->getFlashdata('errors'),
        ]);
    }
    // =====================
    // DELETE
    // =====================
    public function delete($id)
    {
        $item = $this->siswaModel->find($id);

        if ($item && $item['foto'] && is_file('uploads/siswa/' . $item['foto'])) {
            unlink('uploads/siswa/' . $item['foto']);
        }

        $this->siswaModel->delete($id);

        return redirect()->to(base_url('admin/siswa'))
            ->with('success', 'Data siswa berhasil dihapus');
    }
}
