<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'title', 'company_id', 'contract_type', 'status',
        'start_date', 'end_date', 'value',
        'total_hours', 'hourly_rate', 'location',
        'project_name', 'project_description', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'title'         => 'required|min_length[2]|max_length[200]',
        'company_id'    => 'required|is_natural_no_zero',
        'contract_type' => 'required|in_list[product,service,project]',
        'status'        => 'permit_empty|in_list[draft,active,expired,terminated,cancelled]',
    ];

    public function scopeForList(
        ?string $search = null,
        ?string $status = null,
        ?string $type = null,
        ?int $companyId = null
    ): self {
        $this->select('contracts.*, companies.name AS company_name')
            ->join('companies', 'companies.id = contracts.company_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('contracts.number', $search)
                ->orLike('contracts.title', $search)
                ->orLike('companies.name', $search)
                ->orLike('contracts.project_name', $search)
                ->groupEnd();
        }

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

        if ($type) {
            $this->where('contracts.contract_type', $type);
        }

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

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'CTR-' . date('Ymd') . '-';
        $row = $this->like('number', $prefix, 'after')
            ->orderBy('id', 'DESC')
            ->first();

        $seq = 1;
        if ($row && preg_match('/-(\d+)$/', $row['number'], $m)) {
            $seq = (int) $m[1] + 1;
        }

        return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
    }

    public function isNumberTaken(string $number, ?int $excludeId = null): bool
    {
        if ($number === '') {
            return false;
        }

        $builder = $this->where('number', $number);
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }

    public function countByStatus(): array
    {
        $rows = $this->select('status, COUNT(*) AS total')
            ->groupBy('status')
            ->findAll();

        $map = [];
        foreach ($rows as $row) {
            $map[$row['status']] = (int) $row['total'];
        }

        return $map;
    }

    /**
     * Active contracts with an end date in the renewal window (default 90 days).
     */
    public function scopeForRenewals(?string $search = null, int $withinDays = 90, ?string $today = null): self
    {
        $today = $today ?: date('Y-m-d');
        $until = date('Y-m-d', strtotime($today . ' +' . max(1, $withinDays) . ' days'));

        $this->scopeForList($search, 'active')
            ->where('contracts.end_date IS NOT NULL')
            ->where('contracts.end_date >=', $today)
            ->where('contracts.end_date <=', $until);

        return $this;
    }

    /**
     * Expiry alerts: expired contracts or those ending within the selected window.
     *
     * @param string $filter expired|7|30|90
     */
    public function scopeForExpiryAlerts(?string $search = null, string $filter = '30', ?string $today = null): self
    {
        $today = $today ?: date('Y-m-d');

        $this->scopeForList($search)
            ->where('contracts.end_date IS NOT NULL')
            ->whereIn('contracts.status', ['active', 'expired']);

        if ($filter === 'expired') {
            $this->groupStart()
                ->where('contracts.status', 'expired')
                ->orWhere('contracts.end_date <', $today)
                ->groupEnd();
        } else {
            $days = in_array($filter, ['7', '30', '90'], true) ? (int) $filter : 30;
            $until = date('Y-m-d', strtotime($today . ' +' . $days . ' days'));
            $this->where('contracts.end_date >=', $today)
                ->where('contracts.end_date <=', $until)
                ->where('contracts.status', 'active');
        }

        return $this;
    }

    public function expiryAlertSummary(?string $today = null): array
    {
        $today = $today ?: date('Y-m-d');

        return [
            'expired'     => (new self())->scopeForExpiryAlerts(null, 'expired', $today)->countAllResults(),
            'expiring_7'  => (new self())->scopeForExpiryAlerts(null, '7', $today)->countAllResults(),
            'expiring_30' => (new self())->scopeForExpiryAlerts(null, '30', $today)->countAllResults(),
            'expiring_90' => (new self())->scopeForExpiryAlerts(null, '90', $today)->countAllResults(),
        ];
    }
}
