<?php

namespace App\Models;

use CodeIgniter\Model;

class UnitModel extends Model
{
    protected $table            = 'units';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'company_id',
        'unit_name',
        'unit_location',
        'unit_manager_name',
        'unit_manager_number',
        'unit_hr_name',
        'unit_hr_number',
        'total_workers',
        'contractual_workers',
        'status',
        'deleted_at'
    ];

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

    // Validation
    protected $validationRules      = [
        'company_id'           => 'required|is_natural_no_zero',
        'unit_name'            => 'required|max_length[255]',
        'unit_location'        => 'required',
        'unit_manager_name'    => 'permit_empty|max_length[255]',
        'unit_manager_number'  => 'permit_empty|regex_match[/^(\+91)?[6-9]\d{9}$/]',
        'unit_hr_name'         => 'permit_empty|max_length[255]',
        'unit_hr_number'       => 'permit_empty|regex_match[/^(\+91)?[6-9]\d{9}$/]',
        'total_workers'        => 'required|integer|greater_than_equal_to[0]',
        'contractual_workers'  => 'required|integer|greater_than_equal_to[0]',
        'status'               => 'required|in_list[Active,Inactive]',
    ];
    protected $validationMessages   = [
        'company_id' => [
            'required' => 'Company ID is required.',
            'is_natural_no_zero' => 'Please select a valid company.'
        ],
        'unit_name' => [
            'required' => 'Unit name is required.',
            'max_length' => 'Unit name cannot exceed 255 characters.'
        ],
        'unit_location' => [
            'required' => 'Unit location is required.'
        ],
        'unit_manager_number' => [
            'regex_match' => 'Please enter a valid Indian phone number (10 digits starting with 6-9, optionally with +91 prefix).'
        ],
        'unit_hr_number' => [
            'regex_match' => 'Please enter a valid Indian phone number (10 digits starting with 6-9, optionally with +91 prefix).'
        ],
        'total_workers' => [
            'required' => 'Total number of workers is required.',
            'integer' => 'Total workers must be a whole number.',
            'greater_than_equal_to' => 'Total workers must be 0 or greater.'
        ],
        'contractual_workers' => [
            'required' => 'Number of contractual workers is required.',
            'integer' => 'Contractual workers must be a whole number.',
            'greater_than_equal_to' => 'Contractual workers must be 0 or greater.'
        ],
        'status' => [
            'required' => 'Status is required.',
            'in_list' => 'Please select a valid status.'
        ]
    ];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $beforeUpdate   = [];

    /**
     * Get units with pagination and search
     *
     * @param int $perPage
     * @param string|null $search
     * @param int|null $companyId
     * @param string|null $status
     * @return array
     */
    public function getUnits($perPage = 10, $search = null, $companyId = null, $status = null)
    {
        $this->select('units.*, companies.company_name');
        $this->join('companies', 'companies.id = units.company_id');

        // Apply search filter
        if ($search) {
            $this->groupStart()
                 ->like('units.unit_name', $search)
                 ->orLike('units.unit_manager_name', $search)
                 ->orLike('companies.company_name', $search)
                 ->groupEnd();
        }

        // Apply company filter
        if ($companyId) {
            $this->where('units.company_id', $companyId);
        }

        // Apply status filter
        if ($status) {
            $this->where('units.status', $status);
        }

        // Exclude soft deleted records
        $this->where('units.deleted_at', null);

        // Order by created_at descending
        $this->orderBy('units.created_at', 'DESC');

        // Return paginated results
        return $this->paginate($perPage);
    }

    /**
     * Get units by company ID
     *
     * @param int $companyId
     * @return array
     */
    public function getUnitsByCompany($companyId)
    {
        return $this->where('company_id', $companyId)
                    ->where('deleted_at', null)
                    ->where('status', 'Active')
                    ->findAll();
    }

    /**
     * Get units for export
     *
     * @param string|null $search
     * @param int|null $companyId
     * @param string|null $status
     * @return array
     */
    public function getUnitsForExport($search = null, $companyId = null, $status = null)
    {
        $builder = $this->builder();
        $builder->select('units.*, companies.company_name');
        $builder->join('companies', 'companies.id = units.company_id');

        // Apply search filter
        if ($search) {
            $builder->groupStart()
                    ->like('units.unit_name', $search)
                    ->orLike('units.unit_manager_name', $search)
                    ->orLike('companies.company_name', $search)
                    ->groupEnd();
        }

        // Apply company filter
        if ($companyId) {
            $builder->where('units.company_id', $companyId);
        }

        // Apply status filter
        if ($status) {
            $builder->where('units.status', $status);
        }

        // Exclude soft deleted records
        $builder->where('units.deleted_at', null);

        // Order by created_at descending
        $builder->orderBy('units.created_at', 'DESC');

        return $builder->get()->getResultArray();
    }
}