<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\EventFieldModel;
use App\Models\EventModel;

class EventFieldsController extends BaseController
{
    public function new(int $eventId)
    {
        $event = (new EventModel())->find($eventId);
        if (!$event) {
            return redirect()->route('admin.events.index')->with('error', 'Event not found.');
        }

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

    public function create(int $eventId)
    {
        if (!$this->validate($this->getValidationRules())) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $options = null;
        if ($this->request->getPost('type') === 'select') {
            $optionsArray = array_filter(array_map('trim', explode("\n", $this->request->getPost('options'))));
            $options = json_encode(array_values($optionsArray));
        }

        (new EventFieldModel())->save([
            'event_id'    => $eventId,
            'field_key'   => strtolower($this->request->getPost('field_key')),
            'label'       => $this->request->getPost('label'),
            'type'        => $this->request->getPost('type'),
            'is_multiple' => ($this->request->getPost('type') === 'select') ? (int)$this->request->getPost('is_multiple') : 0,
            'is_required' => (int)$this->request->getPost('is_required') ?? 0,
            'options'     => $options,
            'sort_order'  => (int)$this->request->getPost('sort_order'),
        ]);

        return redirect()->to(route_to('admin.events.show', $eventId))->with('success', lang('Admin/Events.fieldCreateSuccess'));
    }
    
    public function edit(int $eventId, int $fieldId)
    {
        $fieldModel = new EventFieldModel();
        $field = $fieldModel->find($fieldId);
        if (!$field || $field->event_id != $eventId) {
            return redirect()->back()->with('error', lang('Admin/Events.errorFieldNotFound'));
        }

        $data = [
            'event' => (new EventModel())->find($eventId),
            'field' => $field,
            'pageTitle' => lang('Admin/Events.editField'),
        ];
        return view('backend/events/fields/edit', $data);
    }
    
    public function update(int $eventId, int $fieldId)
    {
        if (!$this->validate($this->getValidationRules($fieldId))) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $options = null;
        if ($this->request->getPost('type') === 'select') {
            $optionsArray = array_filter(array_map('trim', explode("\n", $this->request->getPost('options'))));
            $options = json_encode(array_values($optionsArray));
        }
        
        (new EventFieldModel())->save([
            'id'          => $fieldId,
            'event_id'    => $eventId,
            'field_key'   => strtolower($this->request->getPost('field_key')),
            'label'       => $this->request->getPost('label'),
            'type'        => $this->request->getPost('type'),
            'is_multiple' => ($this->request->getPost('type') === 'select') ? (int)$this->request->getPost('is_multiple') : 0,
            'is_required' => (int)$this->request->getPost('is_required') ?? 0,
            'options'     => $options,
            'sort_order'  => (int)$this->request->getPost('sort_order'),
        ]);

        
        return redirect()->to(route_to('admin.events.show', $eventId))->with('success', lang('Admin/Events.fieldUpdateSuccess'));
    }
    
    public function delete(int $eventId, int $fieldId)
    {
        (new EventFieldModel())->delete($fieldId);
        return redirect()->to(route_to('admin.events.show', $eventId))->with('success', lang('Admin/Events.fieldDeleteSuccess'));
    }

    private function getValidationRules(int $ignoreId = null): array
    {
        $rules = [
            'field_key'   => "required|alpha_dash|is_unique[event_fields.field_key,id,{$ignoreId}]",
            'label'       => 'required|string',
            'type'        => 'required|in_list[text,number,date,email,select]',
            'sort_order'  => 'required|is_natural',
        ];

        if ($this->request->getPost('type') === 'select') {
            $rules['options'] = 'required';
        }
        return $rules;
    }
}