<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\GaleriModel;
use CodeIgniter\HTTP\Files\UploadedFile;

class Galeri extends BaseController
{
    public function index()
    {
        return view('admin/galeri', $this->data + [
            'title' => 'Kelola Galeri',
            'items' => (new GaleriModel())->orderBy('urutan')->orderBy('id', 'DESC')->findAll(),
        ]);
    }

    public function new()
    {
        return redirect()->to('/admin/galeri');
    }

    public function create()
    {
        $files = $this->request->getFileMultiple('foto');
        if (! $files) {
            return redirect()->back()->with('error', 'Pilih minimal satu foto.');
        }

        $validFiles = [];
        foreach ($files as $file) {
            if ($file->getError() === UPLOAD_ERR_NO_FILE) {
                continue;
            }
            if (! $this->isValidImage($file)) {
                return redirect()->back()->with('error', 'Foto harus JPG, PNG, atau WebP dengan ukuran maksimal 5 MB.');
            }
            $validFiles[] = $file;
        }
        if ($validFiles === []) {
            return redirect()->back()->with('error', 'Pilih minimal satu foto yang valid.');
        }

        $this->ensureDirectory();
        $model = new GaleriModel();
        foreach ($validFiles as $file) {
            $name = $file->getRandomName();
            $file->move(FCPATH . 'uploads/gallery', $name);
            $model->insert([
                'foto' => 'uploads/gallery/' . $name,
                'caption' => trim((string) $this->request->getPost('caption')),
                'urutan' => (int) $this->request->getPost('urutan'),
            ]);
        }

        return redirect()->back()->with('success', count($validFiles) . ' foto berhasil diunggah.');
    }

    public function edit($id = null)
    {
        $item = (new GaleriModel())->find($id);
        if (! $item) {
            return redirect()->to('/admin/galeri')->with('error', 'Foto galeri tidak ditemukan.');
        }
        return view('admin/galeri_form', $this->data + ['title' => 'Edit Galeri', 'item' => $item]);
    }

    public function update($id = null)
    {
        $model = new GaleriModel();
        $item = $model->find($id);
        if (! $item) {
            return redirect()->to('/admin/galeri')->with('error', 'Foto galeri tidak ditemukan.');
        }

        $data = [
            'caption' => trim((string) $this->request->getPost('caption')),
            'urutan' => (int) $this->request->getPost('urutan'),
        ];
        $file = $this->request->getFile('foto');
        if ($file && $file->getError() !== UPLOAD_ERR_NO_FILE) {
            if (! $this->isValidImage($file)) {
                return redirect()->back()->withInput()->with('error', 'Foto harus JPG, PNG, atau WebP dengan ukuran maksimal 5 MB.');
            }
            $this->ensureDirectory();
            $name = $file->getRandomName();
            $file->move(FCPATH . 'uploads/gallery', $name);
            $data['foto'] = 'uploads/gallery/' . $name;
            $this->deleteFile($item['foto']);
        }
        $model->update($id, $data);

        return redirect()->to('/admin/galeri')->with('success', 'Galeri berhasil diperbarui.');
    }

    public function delete($id = null)
    {
        $model = new GaleriModel();
        $item = $model->find($id);
        if (! $item) {
            return redirect()->back()->with('error', 'Foto galeri tidak ditemukan.');
        }
        $this->deleteFile($item['foto']);
        $model->delete($id);

        return redirect()->back()->with('success', 'Foto dihapus.');
    }

    private function isValidImage(UploadedFile $file): bool
    {
        return $file->isValid()
            && ! $file->hasMoved()
            && $file->getSize() <= 5 * 1024 * 1024
            && in_array($file->getMimeType(), ['image/jpeg', 'image/png', 'image/webp'], true);
    }

    private function ensureDirectory(): void
    {
        if (! is_dir(FCPATH . 'uploads/gallery')) {
            mkdir(FCPATH . 'uploads/gallery', 0755, true);
        }
    }

    private function deleteFile(string $relativePath): void
    {
        if (! str_starts_with($relativePath, 'uploads/gallery/')) {
            return;
        }
        $path = FCPATH . str_replace('/', DIRECTORY_SEPARATOR, $relativePath);
        if (is_file($path)) {
            unlink($path);
        }
    }
}
