<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\EventModel;
use App\Models\EventPackageModel;
use App\Models\TransactionModel;

class EventPackagesController extends BaseController
{
    /**
     * Menampilkan form untuk membuat paket baru.
     */
    public function new($eventId)
    {
        $event = (new EventModel())->find($eventId);
        if (!$event) { return redirect()->back()->with('error', lang('Admin/Events.errorNotFound')); }

        $data = [
            'event' => $event,
            'pageTitle' => lang('Admin/Events.newPackage'),
        ];
        return view('backend/events/packages/new', $data);
    }

    /**
     * Menyimpan paket baru.
     */
    public function create($eventId)
    {
        $event = (new EventModel())->find($eventId);
        if (!$event) { return redirect()->route('admin.events.index')->with('error', lang('Admin/Events.errorNotFound')); }
        
        if (!$this->validate($this->getValidationRules($event))) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $packageModel = new EventPackageModel();
        $packageModel->insert([
            'event_id'      => $eventId,
            'name'          => $this->request->getPost('name'),
            'start_date'    => $this->request->getPost('start_date'),
            'end_date'      => $this->request->getPost('end_date'),
            'price'         => $this->request->getPost('price'),
            'quota'         => (int)$this->request->getPost('quota'),
            'require_kta'   => $this->request->getPost('require_kta'),
            'include_meal'  => $this->request->getPost('include_meal'),
            'gender_rule'   => $this->request->getPost('gender_rule'),
        ]);

        return redirect()->to(route_to('admin.events.show', $eventId))->with('success', lang('Admin/Events.packageCreateSuccess'));
    }

    /**
     * Menampilkan form untuk mengedit paket.
     */
    public function edit($eventId, $packageId)
    {
        $event = (new EventModel())->find($eventId);
        $package = (new EventPackageModel())->find($packageId);
        if (!$event || !$package) { return redirect()->back()->with('error', 'Data not found.'); }
        
        $data = [
            'event' => $event,
            'package' => $package,
            'pageTitle' => lang('Admin/Events.editPackage'),
        ];
        return view('backend/events/packages/edit', $data);
    }

    /**
     * Mengupdate paket.
     */
    public function update($eventId, $packageId)
    {
        $event = (new EventModel())->find($eventId);
        if (!$event) { return redirect()->route('admin.events.index')->with('error', lang('Admin/Events.errorNotFound')); }

        if (!$this->validate($this->getValidationRules($event))) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        (new EventPackageModel())->update($packageId, [
            'name'          => $this->request->getPost('name'),
            'start_date'    => $this->request->getPost('start_date'),
            'end_date'      => $this->request->getPost('end_date'),
            'price'         => $this->request->getPost('price'),
            'quota'         => (int)$this->request->getPost('quota'),
            'require_kta'   => $this->request->getPost('require_kta'),
            'include_meal'  => $this->request->getPost('include_meal'),
            'gender_rule'   => $this->request->getPost('gender_rule'),
        ]);

        return redirect()->to(route_to('admin.events.show', $eventId))->with('success', lang('Admin/Events.packageUpdateSuccess'));
    }

    /**
     * Menghapus paket (soft delete).
     */
    public function delete($eventId, $packageId)
    {
        // Cek apakah paket sudah digunakan
        $participantCount = (new \App\Models\ParticipantModel())->where('event_package_id', $packageId)->countAllResults();
        if ($participantCount > 0) {
            return redirect()->back()->with('error', 'This package cannot be deleted because it has been used by participants.');
        }

        (new EventPackageModel())->delete($packageId);
        
        return redirect()->to(route_to('admin.events.show', $eventId))->with('success', lang('Admin/Events.packageDeleteSuccess'));
    }

    /**
     * Helper untuk aturan validasi.
     */
    private function getValidationRules($event)
    {
        $eventStartDate = $event->start_date;
        $eventEndDate = $event->end_date;
        $eventQuota = (int)($event->quota ?? 0);
        
        $rules = [
            'name' => 'required|string|max_length[100]',
            
            // Terapkan aturan baru kita ke kedua field tanggal
            'start_date' => "required|valid_date|after_or_equal_to_field[{$eventEndDate}]",
            'end_date' => "required|valid_date|after_or_equal_to_field[start_date]",

            'price' => 'required|is_natural',
            'quota' => 'permit_empty|is_natural',
            'require_kta' => 'required|in_list[0,1]',
            'include_meal' => 'required|in_list[0,1]',
            'gender_rule' => 'required|in_list[All,Male,Female]',
        ];
        
        // Hanya validasi kuota paket jika kuota event > 0
        if ($eventQuota > 0) {
            $rules['quota'] .= '|less_than_equal_to['.$eventQuota.']';
        }

        return $rules;
    }
}