<?php

namespace App\Modules\Geo\Models;

use App\Modules\Geo\Entities\Zone;
use CodeIgniter\Model;

/**
 * Zone Model
 * 
 * Handles database operations for zones.
 */
class ZoneModel extends Model
{
    protected $table            = 'zones';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = Zone::class;
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'zone_code',
        'zone_name',
        'latitude',
        'longitude',
        'radius_meters',
        'is_active',
    ];

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

    // Validation
    protected $validationRules = [
        'zone_code'     => 'required|max_length[100]|is_unique[zones.zone_code,id,{id}]',
        'zone_name'     => 'required|max_length[255]',
        'latitude'      => 'required|decimal',
        'longitude'     => 'required|decimal',
        'radius_meters' => 'required|integer|greater_than[0]',
        'is_active'     => 'permit_empty|in_list[0,1]',
    ];

    protected $validationMessages = [];
    protected $skipValidation     = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    /**
     * Find zone by zone_code
     * 
     * @param string $zoneCode
     * @return Zone|null
     */
    public function findByZoneCode(string $zoneCode): ?Zone
    {
        return $this->where('zone_code', $zoneCode)->first();
    }

    /**
     * Find active zone by zone_code
     * 
     * @param string $zoneCode
     * @return Zone|null
     */
    public function findActiveByZoneCode(string $zoneCode): ?Zone
    {
        return $this->where('zone_code', $zoneCode)
            ->where('is_active', 1)
            ->first();
    }

    /**
     * Get all active zones
     * 
     * @return array
     */
    public function findAllActive(): array
    {
        return $this->where('is_active', 1)->findAll();
    }
}
