<?php

namespace App\Controllers\Admin;

use App\Core\Upload;
use App\Models\FooterLinkModel;
use App\Models\FooterModel;
use App\Models\IdentitasModel;

class FooterController extends AdminController
{
    public function index(): void
    {
        $this->adminView('footer/index', [
            'daftarKolom' => (new FooterModel())->getKolom(),
            'identitas'   => (new IdentitasModel())->getIdentitas(),
        ]);
    }

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

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

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

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

        $id = (new FooterModel())->insert($data);

        $this->setFlash('success', 'Kolom footer berhasil ditambahkan.');
        $this->redirect($data['tipe'] === 'tautan' ? 'admin/footer/' . $id . '/tautan' : 'admin/footer');
    }

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

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

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

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

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

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

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

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

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

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

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

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

        $model = new FooterModel();
        $kolom = $model->find((int) $id);

        if ($kolom) {
            Upload::delete('footer', $kolom['gambar'] ?? null);
            $model->delete((int) $id); // tautan di dalamnya ikut terhapus via FK ON DELETE CASCADE
        }

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

    /**
     * Kelola daftar tautan di dalam kolom bertipe "tautan".
     */
    public function tautan(string $id): void
    {
        $kolom = (new FooterModel())->find((int) $id);

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

        $this->adminView('footer/tautan', [
            'kolom'        => $kolom,
            'daftarTautan' => (new FooterLinkModel())->getByColumnId((int) $id),
        ]);
    }

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

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

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

        (new FooterLinkModel())->insert([
            'footer_column_id' => (int) $id,
            'label'            => trim($_POST['label'] ?? ''),
            'url'              => trim($_POST['url'] ?? '#'),
            'gambar'           => $gambar,
            'urutan'           => (int) ($_POST['urutan'] ?? 0),
        ]);

        $this->setFlash('success', 'Tautan berhasil ditambahkan.');
        $this->redirect('admin/footer/' . $id . '/tautan');
    }

    public function hapusTautan(string $id, string $linkId): void
    {
        $this->verifyCsrf();

        $linkModel = new FooterLinkModel();
        $link = $linkModel->find((int) $linkId);

        if ($link) {
            Upload::delete('footer', $link['gambar'] ?? null);
            $linkModel->delete((int) $linkId);
        }

        $this->setFlash('success', 'Tautan berhasil dihapus.');
        $this->redirect('admin/footer/' . $id . '/tautan');
    }

    /**
     * Simpan warna latar footer (disimpan di tabel identitas_kampus).
     */
    public function updateWarnaLatar(): void
    {
        $this->verifyCsrf();

        $identitasModel = new IdentitasModel();

        if (!$identitasModel->getIdentitas()) {
            $this->setFlash('error', 'Isi dulu data di menu "Identitas Kampus" sebelum mengatur warna latar footer.');
            $this->redirect('admin/footer');
            return;
        }

        $identitasModel->save([
            'footer_bg_color' => trim($_POST['footer_bg_color'] ?? '') ?: null,
        ]);

        $this->setFlash('success', 'Warna latar footer berhasil disimpan.');
        $this->redirect('admin/footer');
    }

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

        $tipe = in_array($_POST['tipe'] ?? '', ['tautan', 'teks', 'gambar', 'html', 'iframe'], true) ? $_POST['tipe'] : 'tautan';
        $konten = $tipe === 'iframe' ? ($_POST['konten_iframe'] ?? '') : ($_POST['konten'] ?? '');

        $data = [
            'judul'  => trim($_POST['judul'] ?? ''),
            'tipe'   => $tipe,
            'konten' => trim($konten),
            'warna'  => trim($_POST['warna'] ?? '') ?: null,
            'urutan' => (int) ($_POST['urutan'] ?? 0),
        ];

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

        return [$data, $uploadError];
    }
}
