<?php

namespace App\Controllers\Admin;

use App\Core\Slug;
use App\Core\Upload;
use App\Models\BeritaModel;
use App\Models\KategoriBeritaModel;

class BeritaController extends AdminController
{
    public function index(): void
    {
        $this->adminView('berita/index', [
            'daftarBerita' => (new BeritaModel())->getAllAdmin(),
        ]);
    }

    public function create(): void
    {
        $this->adminView('berita/form', [
            'berita'    => null,
            'kategori'  => (new KategoriBeritaModel())->all(),
        ]);
    }

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

        $beritaModel = new BeritaModel();
        [$data, $uploadError] = $this->prepareData($beritaModel);

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

        $beritaModel->insert($data);

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

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

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

        $this->adminView('berita/form', [
            'berita'   => $berita,
            'kategori' => (new KategoriBeritaModel())->all(),
        ]);
    }

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

        $beritaModel = new BeritaModel();
        $existing = $beritaModel->find((int) $id);

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

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

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

        // Kalau ada thumbnail baru, hapus thumbnail lama
        if (!empty($data['thumbnail']) && !empty($existing['thumbnail'])) {
            Upload::delete('berita', $existing['thumbnail']);
        }

        // Kalau tidak upload thumbnail baru, pertahankan yang lama
        if (empty($data['thumbnail'])) {
            unset($data['thumbnail']);
        }

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

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

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

        $beritaModel = new BeritaModel();
        $berita = $beritaModel->find((int) $id);

        if ($berita) {
            Upload::delete('berita', $berita['thumbnail'] ?? null);
            $beritaModel->delete((int) $id);
        }

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

    /**
     * Ambil & bersihkan input form, generate slug otomatis, proses upload thumbnail.
     * Mengembalikan [data, pesanErrorUpload|null]
     */
    private function prepareData(BeritaModel $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));

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

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

        $data = [
            'judul'       => $judul,
            'slug'        => $slug,
            'kategori_id' => !empty($_POST['kategori_id']) ? (int) $_POST['kategori_id'] : null,
            'ringkasan'   => trim($_POST['ringkasan'] ?? ''),
            'konten'      => $_POST['konten'] ?? '',
            'penulis'     => trim($_POST['penulis'] ?? ''),
            'status'      => in_array($_POST['status'] ?? '', ['draft', 'terbit'], true) ? $_POST['status'] : 'draft',
            'tanggal'     => !empty($_POST['tanggal']) ? str_replace('T', ' ', $_POST['tanggal']) . ':00' : date('Y-m-d H:i:s'),
        ];

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

        return [$data, $uploadError];
    }
}
