<?php

namespace App\Controllers;

use App\Models\AcaraModel;
use App\Models\GaleriModel;
use App\Models\PengunjungModel;
use App\Models\RsvpModel;
use App\Models\TamuModel;
use App\Models\UcapanModel;

class Invitation extends BaseController
{
    public function index()
    {
        return $this->renderInvitation(null);
    }

    public function guest(string $slug)
    {
        $guest = (new TamuModel())->where('slug', $slug)->first();
        if (! $guest) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        return $this->renderInvitation($guest);
    }

    private function renderInvitation(?array $guest)
    {
        $event = (new AcaraModel())->first();
        if (! $event) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Data acara belum tersedia.');
        }

        (new PengunjungModel())->insert([
            'tamu_id' => $guest['id'] ?? null,
            'ip_address' => $this->request->getIPAddress(),
            'user_agent' => (string) $this->request->getUserAgent(),
            'visited_at' => date('Y-m-d H:i:s'),
        ]);

        return view('invitation/index', [
            'acara' => $event,
            'tamu' => $guest,
            'galeri' => (new GaleriModel())->orderBy('urutan')->orderBy('id', 'DESC')->findAll(),
            'ucapan' => (new UcapanModel())->where('is_approved', 1)->orderBy('id', 'DESC')->findAll(20),
        ]);
    }

    public function rsvp()
    {
        $rules = [
            'nama' => 'required|min_length[2]|max_length[180]',
            'status' => 'required|in_list[hadir,tidak_hadir]',
            'jumlah_tamu' => 'required|integer|greater_than_equal_to[1]|less_than_equal_to[20]',
            'pesan' => 'permit_empty|max_length[1000]',
        ];
        if (! $this->validate($rules)) {
            return $this->response->setStatusCode(422)->setJSON(['status' => false, 'errors' => $this->validator->getErrors()]);
        }

        $guestModel = new TamuModel();
        $guestId = (int) $this->request->getPost('tamu_id');
        $guest = $guestId > 0 ? $guestModel->find($guestId) : null;
        $guestId = $guest['id'] ?? null;
        $rsvpModel = new RsvpModel();
        $data = [
            'tamu_id' => $guestId,
            'nama' => trim((string) $this->request->getPost('nama')),
            'status' => $this->request->getPost('status'),
            'jumlah_tamu' => (int) $this->request->getPost('jumlah_tamu'),
            'pesan' => trim((string) $this->request->getPost('pesan')),
        ];
        $existingRsvp = $guestId ? $rsvpModel->where('tamu_id', $guestId)->first() : null;
        $existingRsvp ? $rsvpModel->update($existingRsvp['id'], $data) : $rsvpModel->insert($data);
        if ($guestId) {
            $guestModel->update($guestId, ['status_kehadiran' => $this->request->getPost('status')]);
        }

        return $this->response->setJSON(['status' => true, 'message' => 'Konfirmasi kehadiran berhasil disimpan.']);
    }

    public function ucapan()
    {
        if (! $this->validate([
            'nama_pengirim' => 'required|min_length[2]|max_length[180]',
            'ucapan' => 'required|min_length[3]|max_length[1500]',
        ])) {
            return $this->response->setStatusCode(422)->setJSON(['status' => false, 'errors' => $this->validator->getErrors()]);
        }

        (new UcapanModel())->insert([
            'nama_pengirim' => trim((string) $this->request->getPost('nama_pengirim')),
            'ucapan' => trim((string) $this->request->getPost('ucapan')),
            'is_approved' => 0,
        ]);

        return $this->response->setJSON(['status' => true, 'message' => 'Ucapan terkirim dan menunggu persetujuan admin.']);
    }

    public function latestWishes()
    {
        $items = (new UcapanModel())->where('is_approved', 1)->orderBy('id', 'DESC')->findAll(20);
        return $this->response->setJSON(array_map(static fn (array $item): array => [
            'id' => (int) $item['id'],
            'nama_pengirim' => $item['nama_pengirim'],
            'ucapan' => $item['ucapan'],
            'tanggal' => date('d M Y', strtotime($item['created_at'])),
        ], $items));
    }
}
