<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'activity_type', 'subject', 'opportunity_id', 'company_id', 'contact_id',
        'status', 'priority', 'scheduled_at', 'completed_at', 'due_at',
        'duration_minutes', 'description', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'subject'       => 'required|min_length[2]|max_length[200]',
        'activity_type' => 'required|in_list[call,email,meeting,task,follow_up]',
        'status'        => 'permit_empty|in_list[planned,completed,cancelled]',
    ];

    public function scopeForList(
        ?string $search = null,
        ?string $type = null,
        ?string $status = null,
        ?int $companyId = null
    ): self {
        if ($search) {
            $this->groupStart()
                ->like('subject', $search)
                ->orLike('description', $search)
                ->groupEnd();
        }

        if ($type) {
            $this->where('activity_type', $type);
        }

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

        if ($companyId) {
            $this->where('company_id', $companyId);
        }

        return $this;
    }
}
