<?php

namespace App\Models;

use CodeIgniter\Model;

class EventModel extends Model
{
    protected $table            = 'events';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useSoftDeletes   = true;

    protected $allowedFields    = [
        'church_id',
        'name',
        'event_code',
        'slug',
        'thumbnail',
        'description',
        'start_date',
        'end_date',
        'is_active',
        'invoice_format',
        'terms_conditions',
        'quota',
        'used_quota'
    ];

    // Dates
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Callbacks untuk membuat slug otomatis
    protected $beforeInsert = ['generateSlug'];
    protected $beforeUpdate = ['generateSlug'];

    // Validation
    protected $validationRules = [
        'name'           => 'required|max_length[150]',
        'event_code'     => 'permit_empty|max_length[50]|is_unique[events.event_code,id,{id}]',
        'slug'           => 'permit_empty|max_length[200]|is_unique[events.slug,id,{id}]',
        'start_date'     => 'required|valid_date',
        'end_date'       => 'required|valid_date',
        'is_active'      => 'in_list[0,1]',
        'invoice_format' => 'permit_empty|max_length[100]',
    ];


    protected function generateSlug(array $data): array
    {
        if (isset($data['data']['slug']) && !empty($data['data']['slug'])) {
            $data['data']['slug'] = url_title($data['data']['slug'], '-', true);
            return $data;
        }

        if (isset($data['data']['name'])) {
            $slug = url_title($data['data']['name'], '-', true); 

            $existing = $this->where('slug', $slug)->first();
            if ($existing) {
                $currentId = $data['id'][0] ?? null;
                if (!$currentId || $currentId != $existing->id) {
                     $slug = $slug . '-' . time();
                }
            }
            $data['data']['slug'] = $slug;
        }

        return $data;
    }
}