<?php

namespace App\Controllers\Admin;

use App\Core\Upload;
use App\Models\WidgetModel;

class WidgetController extends AdminController
{
    public function index(): void
    {
        $this->adminView('widget/index', [
            'daftarWidget' => (new WidgetModel())->all('posisi ASC, urutan ASC'),
        ]);
    }

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

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

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

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

        (new WidgetModel())->insert($data);

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

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

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

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

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

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

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

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

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

        if (!empty($data['gambar'])) {
            Upload::delete('widget', $existing['gambar'] ?? null);
        }

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

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

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

        $model = new WidgetModel();
        $widget = $model->find((int) $id);

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

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

    private function prepareData(): array
    {
        $uploadError = null;
        $gambar = Upload::image($_FILES['gambar'] ?? [], 'widget', $uploadError);

        $data = [
            'judul'     => trim($_POST['judul'] ?? ''),
            'tipe'      => in_array($_POST['tipe'] ?? '', ['gambar', 'teks', 'html', 'tautan'], true) ? $_POST['tipe'] : 'teks',
            'konten'    => trim($_POST['konten'] ?? ''),
            'url'       => trim($_POST['url'] ?? ''),
            'posisi'    => in_array($_POST['posisi'] ?? '', ['sidebar', 'footer'], true) ? $_POST['posisi'] : 'sidebar',
            'urutan'    => (int) ($_POST['urutan'] ?? 0),
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        ];

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

        return [$data, $uploadError];
    }
}
