<?php

namespace App\Models;

class InvoiceModel extends BaseCompanyModel
{
    protected $table = 'invoices';
    protected $primaryKey = 'id';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'company_id', 'client_id', 'created_by', 'invoice_number', 'amount', 'currency',
        'exchange_rate_at_creation', 'issue_date', 'due_date', 'status',
        'sent_at', 'paid_at', 'notes',
    ];

    public function generateNumber(?int $companyId): string
    {
        $companyId = $companyId ?? 0;
        $year = date('Y');
        $count = $this->where('company_id', $companyId)
            ->where('YEAR(created_at)', $year)
            ->countAllResults() + 1;

        return sprintf('INV-%d-%s-%04d', $companyId, $year, $count);
    }

    public function dueIn(int $companyId, int $days)
    {
        $target = date('Y-m-d', strtotime("+{$days} days"));
        return $this->where('company_id', $companyId)
            ->where('due_date', $target)
            ->whereIn('status', ['sent', 'draft'])
            ->findAll();
    }

    /** فرق سعر الصرف بين وقت الإصدار والسعر الحالي */
    public function currencyDifference(array $invoice, string $baseCurrency): float
    {
        if ($invoice['currency'] === $baseCurrency) {
            return 0;
        }

        $rateModel = new ExchangeRateModel();
        $currentRate = $rateModel->latestRate($invoice['currency'], $baseCurrency) ?? $invoice['exchange_rate_at_creation'];

        return round(($currentRate - $invoice['exchange_rate_at_creation']) * $invoice['amount'], 2);
    }
}
