<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\EventModel;
use App\Models\ChurchModel;
use App\Models\EventPackageModel;
use App\Models\EventPaymentMethodModel;
use App\Models\EventFieldModel;
use App\Models\TransactionModel;

class EventsController extends BaseController
{
    /**
     * Menampilkan daftar semua event.
     */
    public function index()
    {
        $eventModel = new EventModel();
        $data = [
            'events' => $eventModel->select('events.*, churches.name as church_name')
                                   ->join('churches', 'churches.id = events.church_id', 'left')
                                   ->orderBy('events.start_date', 'DESC')
                                   ->paginate(10),
            'pager' => $eventModel->pager,
            'pageTitle' => lang('Admin/Events.pageTitle'),
        ];
        return view('backend/events/index', $data);
    }

    /**
     * Menampilkan form untuk membuat detail event baru (Step 1).
     */
    public function new()
    {
        $data = [
            'churches' => (new ChurchModel())->where('is_active', 1)->orderBy('sort_order', 'ASC')->findAll(),
            'pageTitle' => lang('Admin/Events.newEvent'),
        ];
        return view('backend/events/new', $data);
    }

    /**
     * Memproses pembuatan detail event utama.
     */
    public function create()
    {
        // Panggil validasi yang sudah disederhanakan
        if (!$this->validate($this->getEventValidationRules())) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $thumbnailName = $this->handleUpload('thumbnail');

        $eventModel = new EventModel();
        $eventId = $eventModel->insert([
            'church_id'        => $this->request->getPost('church_id') ?: null,
            'name'             => $this->request->getPost('name'),
            'event_code'       => $this->request->getPost('event_code'),
            'thumbnail'        => $thumbnailName,
            'description'      => $this->request->getPost('description'),
            'start_date'       => $this->request->getPost('start_date'),
            'end_date'         => $this->request->getPost('end_date'),
            'invoice_format'   => $this->request->getPost('invoice_format'),
            'terms_conditions' => $this->request->getPost('terms_conditions'),
            'quota'            => (int)$this->request->getPost('quota'),
            'is_active'        => $this->request->getPost('is_active') ? 1 : 0,
        ]);

        if ($eventId === false) {
            return redirect()->back()->withInput()->with('error', 'Failed to save event data.');
        }

        // Redirect ke halaman detail (hub) untuk melanjutkan ke step berikutnya
        return redirect()->to(route_to('admin.events.show', $eventId))
                         ->with('success', lang('Admin/Events.createSuccess'));
    }
    
    /**
     * Halaman "hub" untuk mengelola semua bagian dari sebuah event.
     */
    public function show($id = null)
    {
        $event = (new EventModel())->find($id);
        if (!$event) { return redirect()->route('admin.events.index')->with('error', lang('Admin/Events.errorNotFound')); }

        $data = [
            'event'          => $event,
            'packages'       => (new EventPackageModel())->where('event_id', $id)->findAll(),
            'paymentMethods' => (new EventPaymentMethodModel())->where('event_id', $id)->findAll(),
            'customFields'   => (new EventFieldModel())->where('event_id', $id)->orderBy('sort_order', 'ASC')->findAll(),
            'pageTitle'      => lang('Admin/Events.manageEvent', [$event->name]),
        ];
        return view('backend/events/show', $data);
    }
    
    /**
     * Menampilkan form untuk mengedit detail event utama.
     */
    public function edit($id = null)
    {
        $event = (new EventModel())->find($id);
        if (!$event) { return redirect()->route('admin.events.index')->with('error', lang('Admin/Events.errorNotFound')); }

        $data = [
            'event'     => $event,
            'churches'  => (new ChurchModel())->where('is_active', 1)->orderBy('name', 'ASC')->findAll(),
            'pageTitle' => lang('Admin/Events.editEvent'),
        ];
        return view('backend/events/edit', $data);
    }
    
    /**
     * Memproses update detail event utama.
     */
    public function update($id = null)
    {
        $eventModel = new EventModel();
        $event = $eventModel->find($id);
        if (!$event) { return redirect()->route('admin.events.index')->with('error', lang('Admin/Events.errorNotFound')); }

        // Panggil validasi yang sudah disederhanakan
        if (!$this->validate($this->getEventValidationRules($id))) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }
        
        $thumbnailName = $this->handleUpload('thumbnail', $event->thumbnail);

        $eventData = [
            'church_id'        => $this->request->getPost('church_id') ?: null,
            'name'             => $this->request->getPost('name'),
            'event_code'       => $this->request->getPost('event_code'),
            'description'      => $this->request->getPost('description'),
            'start_date'       => $this->request->getPost('start_date'),
            'end_date'         => $this->request->getPost('end_date'),
            'invoice_format'   => $this->request->getPost('invoice_format'),
            'terms_conditions' => $this->request->getPost('terms_conditions'),
            'quota'            => (int)$this->request->getPost('quota'),
            'is_active'        => $this->request->getPost('is_active') ? 1 : 0,
        ];
        if ($thumbnailName) {
            $eventData['thumbnail'] = $thumbnailName;
        }

        $db = \Config\Database::connect();
        $success = $db->table('events')->where('id', $id)->update($eventData);
        
        // Redirect kembali ke halaman detail (hub)
        return redirect()->to(route_to('admin.events.show', $id))->with('success', lang('Admin/Events.updateSuccess'));
    }

    /**
     * Menghapus event (jika belum ada transaksi).
     */
    public function delete($id = null)
    {
        $transactionCount = (new TransactionModel())->where('event_id', $id)->countAllResults();
        if ($transactionCount > 0) {
            return redirect()->back()->with('error', lang('Admin/Events.errorDelete'));
        }

        (new EventModel())->delete($id);
        
        return redirect()->to(route_to('admin.events.index'))->with('success', lang('Admin/Events.deleteSuccess'));
    }

    /**
     * Helper validasi HANYA untuk form detail event utama.
     */
    private function getEventValidationRules(int $eventId = null): array
    {
        return [
            'name'           => 'required|string|max_length[150]',
            'event_code'     => "required|alpha_dash|is_unique[events.event_code,id,{$eventId}]",
            'start_date'     => 'required|valid_date',
            'end_date'       => 'required|valid_date',
            'invoice_format' => 'required',
            'quota'          => 'permit_empty|is_natural',
            'thumbnail'      => "permit_empty|uploaded[thumbnail]|max_size[thumbnail,1024]|is_image[thumbnail]|ext_in[thumbnail,png,jpg,jpeg]",
        ];
    }

    /**
     * Helper untuk menangani upload gambar.
     */
    private function handleUpload(string $fieldName, ?string $oldFile = ''): ?string
    {
        $img = $this->request->getFile($fieldName);
        if ($img && $img->isValid() && !$img->hasMoved()) {
            if ($oldFile && file_exists(WRITEPATH . '../public/uploads/thumbnails/' . $oldFile)) {
                unlink(WRITEPATH . '../public/uploads/thumbnails/' . $oldFile);
            }
            $newName = $img->getRandomName();
            // Pastikan direktori ada
            if (!is_dir(WRITEPATH . '../public/uploads/thumbnails')) {
                mkdir(WRITEPATH . '../public/uploads/thumbnails', 0775, true);
            }
            $img->move(WRITEPATH . '../public/uploads/thumbnails', $newName);
            return $newName;
        }
        return $oldFile;
    }
}