<?php

namespace App\Models;

use CodeIgniter\Model;

class ClientModel extends Model
{
    protected $table = 'clients';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'company_id', 'code', 'company_name', 'contact_name', 'email', 'phone',
        'fax', 'address', 'city', 'country', 'tax_id', 'ice', 'payment_terms', 'notes', 'is_active'
    ];
    protected $returnType = 'array';
    protected $useTimestamps = true;
    protected $useSoftDeletes = true;

    protected $validationRules = [
        'company_id' => 'required|integer',
        'code' => 'required|max_length[50]',
        'company_name' => 'required|max_length[255]',
        'email' => 'permit_empty|valid_email',
    ];

    public function getWithStats(int $clientId): ?array
    {
        $client = $this->find($clientId);
        if (!$client) return null;

        $invoiceModel = new InvoiceModel();
        $client['total_invoices'] = $invoiceModel->where('client_id', $clientId)->countAllResults();
        $client['total_paid'] = $invoiceModel->where('client_id', $clientId)->where('status', 'payee')->countAllResults();
        $client['total_unpaid'] = $invoiceModel->where('client_id', $clientId)->whereIn('status', ['envoyee', 'partielle', 'retard'])->countAllResults();
        $client['total_revenue'] = $invoiceModel->where('client_id', $clientId)->selectSum('total_ttc')->first()['total_ttc'] ?? 0;

        return $client;
    }

    public function generateCode(): string
    {
        $last = $this->orderBy('id', 'DESC')->first();
        $num = $last ? ((int) str_replace('CLI-', '', $last['code']) + 1) : 1;
        return 'CLI-' . str_pad($num, 3, '0', STR_PAD_LEFT);
    }
}
