<?php

namespace App\Models;

use CodeIgniter\Model;

class SalesCommissionModel extends Model
{
    protected $table         = 'sales_commissions';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'sales_rep_id', 'period_start', 'period_end', 'base_amount', 'rate_percent',
        'commission_amount', 'status', 'notes', 'approved_at', 'paid_at',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'sales_rep_id'  => 'required|is_natural_no_zero',
        'period_start'  => 'required|valid_date',
        'period_end'    => 'required|valid_date',
        'base_amount'   => 'required|decimal',
        'rate_percent'  => 'required|decimal',
        'status'        => 'permit_empty|in_list[draft,approved,paid,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $repId = null): self
    {
        $this->select('sales_commissions.*, sales_representatives.name as rep_name')
            ->join('sales_representatives', 'sales_representatives.id = sales_commissions.sales_rep_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('sales_representatives.name', $search)
                ->orLike('sales_commissions.notes', $search)
                ->groupEnd();
        }

        if ($status) {
            $this->where('sales_commissions.status', $status);
        }

        if ($repId) {
            $this->where('sales_commissions.sales_rep_id', $repId);
        }

        return $this;
    }
}
