<?php

namespace App\Controllers\Admin;

use App\Core\Slug;
use App\Core\Upload;
use App\Models\HalamanModel;

class HalamanController extends AdminController
{
    public function index(): void
    {
        $this->adminView('halaman/index', [
            'daftarHalaman' => (new HalamanModel())->all('judul ASC'),
        ]);
    }

    public function create(): void
    {
        $this->adminView('halaman/form', ['halaman' => null]);
    }

    public function store(): void
    {
        $this->verifyCsrf();

        $model = new HalamanModel();
        [$data, $uploadError] = $this->prepareData($model);

        if ($uploadError) {
            $this->setFlash('error', $uploadError);
            $this->redirect('admin/halaman/create');
            return;
        }

        $model->insert($data);

        $this->setFlash('success', 'Halaman berhasil ditambahkan.');
        $this->redirect('admin/halaman');
    }

    public function edit(string $id): void
    {
        $halaman = (new HalamanModel())->find((int) $id);

        if (!$halaman) {
            $this->setFlash('error', 'Halaman tidak ditemukan.');
            $this->redirect('admin/halaman');
            return;
        }

        $this->adminView('halaman/form', ['halaman' => $halaman]);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();

        $model = new HalamanModel();
        $existing = $model->find((int) $id);

        if (!$existing) {
            $this->setFlash('error', 'Halaman tidak ditemukan.');
            $this->redirect('admin/halaman');
            return;
        }

        [$data, $uploadError] = $this->prepareData($model, (int) $id);

        if ($uploadError) {
            $this->setFlash('error', $uploadError);
            $this->redirect('admin/halaman/' . $id . '/edit');
            return;
        }

        if (!empty($data['gambar']) && !empty($existing['gambar'])) {
            Upload::delete('halaman', $existing['gambar']);
        }

        $model->update((int) $id, $data);

        $this->setFlash('success', 'Halaman berhasil diperbarui.');
        $this->redirect('admin/halaman');
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();

        $model = new HalamanModel();
        $halaman = $model->find((int) $id);

        if ($halaman) {
            Upload::delete('halaman', $halaman['gambar'] ?? null);
            $model->delete((int) $id);
        }

        $this->setFlash('success', 'Halaman berhasil dihapus.');
        $this->redirect('admin/halaman');
    }

    private function prepareData(HalamanModel $model, ?int $excludeId = null): array
    {
        $judul = trim($_POST['judul'] ?? '');

        $slug = !empty($_POST['slug'])
            ? Slug::make($_POST['slug'])
            : Slug::unique($judul, fn ($s) => $model->slugExists($s, $excludeId));

        if (!empty($_POST['slug']) && $model->slugExists($slug, $excludeId)) {
            $slug = Slug::unique($judul, fn ($s) => $model->slugExists($s, $excludeId));
        }

        $uploadError = null;
        $gambar = Upload::image($_FILES['gambar'] ?? [], 'halaman', $uploadError);

        $data = [
            'judul'     => $judul,
            'slug'      => $slug,
            'konten'    => $_POST['konten'] ?? '',
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        ];

        if ($gambar) {
            $data['gambar'] = $gambar;
        }

        return [$data, $uploadError];
    }
}
