<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\GaleriGuruStafModel;

class GaleriGuruStaf extends BaseController
{
    protected GaleriGuruStafModel $model;

    public function __construct()
    {
        $this->model = new GaleriGuruStafModel();
    }

    public function index()
    {
        return view('admin/galeri/index', [
            'title'  => 'Galeri Guru & Staf',
            'items'  => $this->model->orderBy('urutan', 'ASC')->orderBy('nama', 'ASC')->findAll(),
            'errors' => session()->getFlashdata('errors'),
            'msg'    => session()->getFlashdata('msg'),
        ]);
    }

    public function create()
    {
        return view('admin/galeri/create', [
            'title'  => 'Tambah Guru & Staf',
            'errors' => session()->getFlashdata('errors'),
        ]);
    }

    // =============================
    // ✅ STORE (TAMBAH DATA)
    // =============================
    public function store()
    {
        $rules = [
            'nama'             => 'required|min_length[3]',
            'nip'              => 'permit_empty|min_length[5]',
            'jabatan_utama'    => 'permit_empty|min_length[2]',
            'jabatan_tambahan' => 'permit_empty|min_length[2]',
            'mapel'            => 'permit_empty|min_length[2]',
            'urutan'           => 'required|integer',

            // 🔒 FOTO WAJIB + MAX 2 MB
            'foto' => [
                'label' => 'Foto',
                'rules' => [
                    'uploaded[foto]',
                    'is_image[foto]',
                    'mime_in[foto,image/jpg,image/jpeg,image/png,image/webp]',
                    'max_size[foto,2048]',
                ],
                'errors' => [
                    'uploaded' => 'Foto wajib diupload.',
                    'is_image' => 'File harus berupa gambar.',
                    'mime_in'  => 'Format foto harus JPG, PNG, atau WEBP.',
                    'max_size' => 'Ukuran foto maksimal 2 MB.',
                ]
            ],
        ];

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

        // upload foto
        $file = $this->request->getFile('foto');
        $fotoName = $file->getRandomName();
        $file->move(FCPATH . 'uploads/guru-staf', $fotoName);

        // fallback jabatan lama
        $jabatanUtama = trim((string) $this->request->getPost('jabatan_utama'));
        $jabatanLama  = trim((string) $this->request->getPost('jabatan'));
        if ($jabatanUtama === '' && $jabatanLama !== '') {
            $jabatanUtama = $jabatanLama;
        }

        $this->model->insert([
            'nama'             => $this->request->getPost('nama'),
            'nip'              => $this->request->getPost('nip'),
            'jabatan_utama'    => $jabatanUtama,
            'jabatan_tambahan' => $this->request->getPost('jabatan_tambahan'),
            'mapel'            => $this->request->getPost('mapel'),
            'urutan'           => (int) $this->request->getPost('urutan'),
            'foto'             => $fotoName,
        ]);

        return redirect()->to(base_url('admin/guru-staf'))
            ->with('msg', 'Data berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $item = $this->model->find($id);
        if (! $item) {
            return redirect()->to(base_url('admin/guru-staf'))
                ->with('msg', 'Data tidak ditemukan.');
        }

        return view('admin/galeri/edit', [
            'title'  => 'Edit Guru/Staf',
            'item'   => $item,
            'errors' => session()->getFlashdata('errors'),
        ]);
    }

    // =============================
    // UPDATE (TIDAK DIUBAH)
    // =============================
    public function update($id)
    {
        $item = $this->model->find($id);
        if (! $item) {
            return redirect()->to(base_url('admin/guru-staf'))
                ->with('msg', 'Data tidak ditemukan.');
        }

        $rules = [
            'nama'             => 'required|min_length[3]',
            'nip'              => 'permit_empty|min_length[5]',
            'jabatan_utama'    => 'permit_empty|min_length[2]',
            'jabatan_tambahan' => 'permit_empty|min_length[2]',
            'mapel'            => 'permit_empty|min_length[2]',
            'urutan'           => 'required|integer',
            'foto'             => 'permit_empty|is_image[foto]|mime_in[foto,image/jpg,image/jpeg,image/png,image/webp]|max_size[foto,2048]',
        ];

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

        $fotoName = $item['foto'];
        $file = $this->request->getFile('foto');

        if ($file && $file->isValid() && ! $file->hasMoved()) {
            $fotoName = $file->getRandomName();
            $file->move(FCPATH . 'uploads/guru-staf', $fotoName);

            if (!empty($item['foto'])) {
                $old = FCPATH . 'uploads/guru-staf/' . $item['foto'];
                if (is_file($old)) unlink($old);
            }
        }

        $jabatanUtama = trim((string) $this->request->getPost('jabatan_utama'));
        $jabatanLama  = trim((string) $this->request->getPost('jabatan'));
        if ($jabatanUtama === '' && $jabatanLama !== '') {
            $jabatanUtama = $jabatanLama;
        }

        $this->model->update($id, [
            'nama'             => $this->request->getPost('nama'),
            'nip'              => $this->request->getPost('nip'),
            'jabatan_utama'    => $jabatanUtama,
            'jabatan_tambahan' => $this->request->getPost('jabatan_tambahan'),
            'mapel'            => $this->request->getPost('mapel'),
            'urutan'           => (int) $this->request->getPost('urutan'),
            'foto'             => $fotoName,
        ]);

        return redirect()->to(base_url('admin/guru-staf'))
            ->with('msg', 'Data berhasil diupdate.');
    }

    public function delete($id)
    {
        $item = $this->model->find($id);
        if (! $item) {
            return redirect()->to(base_url('admin/guru-staf'))
                ->with('msg', 'Data tidak ditemukan.');
        }

        if (!empty($item['foto'])) {
            $path = FCPATH . 'uploads/guru-staf/' . $item['foto'];
            if (is_file($path)) unlink($path);
        }

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

        return redirect()->to(base_url('admin/guru-staf'))
            ->with('msg', 'Data berhasil dihapus.');
    }
}
