<?php

namespace App\Models;

use CodeIgniter\Model;

class ContractorModel extends Model
{
    protected $table            = 'contractors';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'company_id',
        'registration_number',
        'contractor_name',
        'contractor_contact_no',
        'contractor_address',
        'validity_date',
        'number_of_employees',
        'sr_no_contractor',
        'nature_of_work',
        'no_of_contract_labours',
        'less_than_20',
        'twenty_and_above',
        'remarks',
        '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',
        'registration_number'   => 'permit_empty|max_length[100]',
        'contractor_name'       => 'required|max_length[255]',
        'contractor_contact_no' => 'permit_empty|max_length[20]',
        'contractor_address'    => 'permit_empty',
        'validity_date'         => 'permit_empty|valid_date',
        'number_of_employees'   => 'permit_empty|is_natural',
        'sr_no_contractor'      => 'permit_empty|max_length[50]',
        'nature_of_work'        => 'permit_empty',
        'no_of_contract_labours' => 'permit_empty|is_natural',
        'less_than_20'          => 'permit_empty|is_natural',
        'twenty_and_above'      => 'permit_empty|is_natural',
        'remarks'               => 'permit_empty',
    ];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

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

    /**
     * Get contractors by company ID
     *
     * @param int $companyId
     * @return array
     */
    public function getContractorsByCompany(int $companyId)
    {
        return $this->where('company_id', $companyId)
                    ->where('deleted_at', null)
                    ->orderBy('created_at', 'DESC')
                    ->findAll();
    }

    /**
     * Get contractor with company details
     *
     * @param int $contractorId
     * @return array|null
     */
    public function getContractorWithCompany(int $contractorId)
    {
        return $this->select('contractors.*, companies.company_name')
                    ->join('companies', 'companies.id = contractors.company_id')
                    ->where('contractors.id', $contractorId)
                    ->where('contractors.deleted_at', null)
                    ->first();
    }

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

        // Apply search filter
        if ($search) {
            $this->groupStart()
                 ->like('contractors.contractor_name', $search)
                 ->orLike('contractors.registration_number', $search)
                 ->orLike('companies.company_name', $search)
                 ->groupEnd();
        }

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

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

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

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

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

        // Apply search filter
        if ($search) {
            $builder->groupStart()
                    ->like('contractors.contractor_name', $search)
                    ->orLike('contractors.registration_number', $search)
                    ->orLike('companies.company_name', $search)
                    ->groupEnd();
        }

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

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

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

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

    /**
     * Get total contractors count
     *
     * @return int
     */
    public function getTotalContractors()
    {
        return $this->where('deleted_at', null)->countAllResults();
    }
}