<?php

namespace App\Controllers\Admin;

use App\Core\Upload;
use App\Models\GaleriFotoDetailModel;
use App\Models\GaleriFotoModel;

class GaleriFotoController extends AdminController
{
    public function index(): void
    {
        $this->adminView('galeri/foto/index', [
            'daftarAlbum' => (new GaleriFotoModel())->getAllWithCount(),
        ]);
    }

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

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

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

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

        $model = new GaleriFotoModel();
        $id = $model->insert([
            'judul'     => trim($_POST['judul'] ?? ''),
            'deskripsi' => trim($_POST['deskripsi'] ?? ''),
            'cover'     => $cover,
        ]);

        $this->setFlash('success', 'Album berhasil dibuat. Sekarang tambahkan foto-fotonya.');
        $this->redirect('admin/galeri-foto/' . $id . '/edit');
    }

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

        if (!$album) {
            $this->setFlash('error', 'Album tidak ditemukan.');
            $this->redirect('admin/galeri-foto');
            return;
        }

        $this->adminView('galeri/foto/form', [
            'album' => $album,
            'daftarFoto' => (new GaleriFotoDetailModel())->getByGaleriId((int) $id),
        ]);
    }

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

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

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

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

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

        $data = [
            'judul'     => trim($_POST['judul'] ?? ''),
            'deskripsi' => trim($_POST['deskripsi'] ?? ''),
        ];

        if ($cover) {
            Upload::delete('galeri', $existing['cover'] ?? null);
            $data['cover'] = $cover;
        }

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

        $this->setFlash('success', 'Album berhasil diperbarui.');
        $this->redirect('admin/galeri-foto/' . $id . '/edit');
    }

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

        $model = new GaleriFotoModel();
        $detailModel = new GaleriFotoDetailModel();
        $album = $model->find((int) $id);

        if ($album) {
            foreach ($detailModel->getByGaleriId((int) $id) as $foto) {
                Upload::delete('galeri', $foto['gambar']);
            }
            Upload::delete('galeri', $album['cover'] ?? null);
            $model->delete((int) $id); // foto ikut terhapus via FK ON DELETE CASCADE
        }

        $this->setFlash('success', 'Album beserta seluruh fotonya berhasil dihapus.');
        $this->redirect('admin/galeri-foto');
    }

    /**
     * Tambah beberapa foto sekaligus ke dalam album.
     */
    public function tambahFoto(string $id): void
    {
        $this->verifyCsrf();

        $filenames = Upload::imageMultiple($_FILES['foto'] ?? [], 'galeri');
        $detailModel = new GaleriFotoDetailModel();

        foreach ($filenames as $i => $filename) {
            $detailModel->insert([
                'galeri_id' => (int) $id,
                'gambar'    => $filename,
                'caption'   => null,
                'urutan'    => $i,
            ]);
        }

        $this->setFlash('success', count($filenames) . ' foto berhasil ditambahkan.');
        $this->redirect('admin/galeri-foto/' . $id . '/edit');
    }

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

        $detailModel = new GaleriFotoDetailModel();
        $foto = $detailModel->find((int) $fotoId);

        if ($foto) {
            Upload::delete('galeri', $foto['gambar']);
            $detailModel->delete((int) $fotoId);
        }

        $this->setFlash('success', 'Foto berhasil dihapus.');
        $this->redirect('admin/galeri-foto/' . $id . '/edit');
    }
}
