<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\KepsekModel;

class Kepsek extends BaseController
{
    protected $kepsekModel;
    protected $session;
    protected $validation;

    public function __construct()
    {
        $this->kepsekModel = new KepsekModel();
        $this->session     = \Config\Services::session();
        $this->validation  = \Config\Services::validation();
    }

    public function index()
    {
        if ($this->session->logged_in == true && $this->session->roles == 2) {
            return redirect()->to('/admin/dashboard');
        }

        return view('admin/kepsek/index', [
            'title'      => 'Kepala Sekolah',
            'kepsek'     => $this->kepsekModel->find(1),
            'validation' => $this->validation,
        ]);
    }

    public function update($id)
    {
        $rules = [
            'nama_kepsek' => [
                'rules'  => 'required',
                'errors' => [
                    'required' => 'Nama kepala sekolah wajib diisi'
                ]
            ],
            'kata_sambutan' => [
                'rules'  => 'required',
                'errors' => [
                    'required' => 'Kata sambutan wajib diisi'
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput();
        }

        // default pakai foto lama
        $newName = $this->request->getPost('foto_kepsek_lama');

        $foto = $this->request->getFile('foto_kepsek');
        if ($foto && $foto->isValid() && !$foto->hasMoved()) {
            $newName = $foto->getRandomName();
            $foto->move('img/kepsek', $newName);

            // hapus foto lama (kecuali default.jpg)
            $oldFile = 'img/kepsek/' . $this->request->getPost('foto_kepsek_lama');
            if (
                $this->request->getPost('foto_kepsek_lama') &&
                $this->request->getPost('foto_kepsek_lama') != 'default.jpg' &&
                file_exists($oldFile)
            ) {
                unlink($oldFile);
            }
        }

        $data = [
            'nama_kepsek'   => $this->request->getPost('nama_kepsek'),
            'kata_sambutan' => $this->request->getPost('kata_sambutan'),
            'foto_kepsek'   => $newName,
        ];

        $this->kepsekModel->update($id, $data);
        $this->session->setFlashdata('success', 'Data Kepsek Berhasil Diubah.');
        return redirect()->to('/admin/kepsek');
    }
}
