<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AcaraModel;

class Acara extends BaseController
{
    public function index()
    {
        return view('admin/acara', $this->data + [
            'title' => 'Kelola Acara',
            'acara' => (new AcaraModel())->first(),
        ]);
    }

    public function update()
    {
        $rules = [
            'nama_acara' => 'required|min_length[3]|max_length[150]',
            'nama_anak' => 'required|min_length[3]|max_length[150]',
            'tanggal' => 'required|valid_date[Y-m-d]',
            'waktu_mulai' => 'required',
            'waktu_selesai' => 'required',
            'lokasi' => 'required|min_length[10]',
            'google_maps_url' => 'required|valid_url_strict',
            'google_maps_embed' => 'permit_empty|valid_url_strict',
            'doa' => 'required|min_length[10]',
            'nama_orang_tua' => 'required|max_length[200]',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('error', implode(' ', $this->validator->getErrors()));
        }

        $model = new AcaraModel();
        $current = $model->first();
        $data = $this->request->getPost([
            'nama_acara', 'nama_anak', 'tanggal', 'waktu_mulai', 'waktu_selesai',
            'lokasi', 'google_maps_url', 'google_maps_embed', 'doa', 'nama_orang_tua',
        ]);
        $photo = $this->request->getFile('foto_anak');

        if ($photo && $photo->getError() !== UPLOAD_ERR_NO_FILE) {
            if (! $this->validate(['foto_anak' => 'uploaded[foto_anak]|is_image[foto_anak]|mime_in[foto_anak,image/jpg,image/jpeg,image/png,image/webp]|max_size[foto_anak,5120]'])) {
                return redirect()->back()->withInput()->with('error', implode(' ', $this->validator->getErrors()));
            }
            $this->ensureDirectory(FCPATH . 'uploads');
            $name = $photo->getRandomName();
            $photo->move(FCPATH . 'uploads', $name);
            $data['foto_anak'] = 'uploads/' . $name;
            $this->deleteUpload($current['foto_anak'] ?? null);
        }

        $current ? $model->update($current['id'], $data) : $model->insert($data);

        return redirect()->back()->with('success', 'Data acara berhasil diperbarui.');
    }

    private function ensureDirectory(string $path): void
    {
        if (! is_dir($path)) {
            mkdir($path, 0755, true);
        }
    }

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