<?php

namespace App\Controllers;

use App\Models\JasaModel;

class JasaController extends BaseController
{
    private JasaModel $jasaModel;

    public function __construct()
    {
        $this->jasaModel = new JasaModel();
    }

    public function index()
    {
        if (! $this->isLoggedIn()) {
            return redirect()->to('/login')->with('error', 'Silakan login terlebih dahulu.');
        }

        if ($redirect = $this->requireAdministrator('/admin/dashboard', 'Akses ditolak. Data jasa hanya dapat diakses oleh administrator.')) {
            return $redirect;
        }

        return view('admin/jasa/index', [
            'jasa'      => $this->jasaModel->orderBy('id', 'DESC')->findAll(),
            'userName'  => session()->get('userName'),
            'userEmail' => session()->get('userEmail'),
            'userRole'  => session()->get('userRole'),
        ]);
    }

    public function create()
    {
        if (! $this->isLoggedIn()) {
            return redirect()->to('/login')->with('error', 'Silakan login terlebih dahulu.');
        }

        if ($redirect = $this->requireAdministrator('/admin/jasa')) {
            return $redirect;
        }

        return view('admin/jasa/create', [
            'userName'  => session()->get('userName'),
            'userEmail' => session()->get('userEmail'),
            'userRole'  => session()->get('userRole'),
        ]);
    }

    public function store()
    {
        if (! $this->isLoggedIn()) {
            return redirect()->to('/login')->with('error', 'Silakan login terlebih dahulu.');
        }

        if ($redirect = $this->requireAdministrator('/admin/jasa')) {
            return $redirect;
        }

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

        $this->jasaModel->insert($this->formData());

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

    public function edit(int $id)
    {
        if (! $this->isLoggedIn()) {
            return redirect()->to('/login')->with('error', 'Silakan login terlebih dahulu.');
        }

        if ($redirect = $this->requireAdministrator('/admin/jasa')) {
            return $redirect;
        }

        $jasa = $this->jasaModel->find($id);

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

        return view('admin/jasa/edit', [
            'jasa'      => $jasa,
            'userName'  => session()->get('userName'),
            'userEmail' => session()->get('userEmail'),
            'userRole'  => session()->get('userRole'),
        ]);
    }

    public function update(int $id)
    {
        if (! $this->isLoggedIn()) {
            return redirect()->to('/login')->with('error', 'Silakan login terlebih dahulu.');
        }

        if ($redirect = $this->requireAdministrator('/admin/jasa')) {
            return $redirect;
        }

        $jasa = $this->jasaModel->find($id);

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

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

        $this->jasaModel->update($id, $this->formData());

        return redirect()->to('/admin/jasa')->with('success', 'Data jasa berhasil diperbarui.');
    }

    public function delete(int $id)
    {
        if (! $this->isLoggedIn()) {
            return redirect()->to('/login')->with('error', 'Silakan login terlebih dahulu.');
        }

        if ($redirect = $this->requireAdministrator('/admin/jasa')) {
            return $redirect;
        }

        $jasa = $this->jasaModel->find($id);

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

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

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

    private function validationRules(?int $id = null): array
    {
        $uniqueRule = $id === null
            ? 'is_unique[jasa.nama_jasa]'
            : 'is_unique[jasa.nama_jasa,id,' . $id . ']';

        return [
            'nama_jasa' => 'required|min_length[2]|max_length[150]|' . $uniqueRule,
            'biaya'     => 'required|max_length[30]',
        ];
    }

    private function formData(): array
    {
        return [
            'nama_jasa' => trim((string) $this->request->getPost('nama_jasa')),
            'biaya'     => $this->biayaFromPost(),
        ];
    }

    private function biayaFromPost(): int
    {
        $digits = preg_replace('/\D/', '', (string) $this->request->getPost('biaya')) ?: '0';

        return max(0, (int) $digits);
    }

    private function isLoggedIn(): bool
    {
        return (bool) session()->get('isLoggedIn') && $this->isUserAccount();
    }
}
