<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'sales_rep_id', 'territory_id', 'period_start', 'period_end',
        'target_amount', 'achieved_amount', 'status', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'sales_rep_id'  => 'required|is_natural_no_zero',
        'period_start'  => 'required|valid_date',
        'period_end'    => 'required|valid_date',
        'target_amount' => 'required|decimal',
        'status'        => 'permit_empty|in_list[active,completed,cancelled]',
    ];

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

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

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

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

        return $this;
    }
}
