<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class InvoiceNumberingSetting extends Model
{
    protected $fillable = [
        'prefix',
        'next_number',
        'number_length',
        'format',
        'reset_yearly',
        'terms',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'reset_yearly' => 'boolean',
        ];
    }

    /**
     * Get invoice numbering settings (singleton)
     */
    public static function getSettings(): self
    {
        return static::firstOrCreate([], [
            'prefix' => 'INV',
            'next_number' => 1,
            'number_length' => 6,
            'format' => '{prefix}-{number}',
            'reset_yearly' => false,
        ]);
    }

    /**
     * Generate next invoice number
     */
    public function generateNextNumber(): string
    {
        // Check if we need to reset yearly
        if ($this->reset_yearly) {
            $currentYear = now()->year;

            // Check if there are any invoices from this year
            $hasInvoiceThisYear = Invoice::whereYear('created_at', $currentYear)->exists();

            // If no invoices this year and we're in a new year, reset to 1
            if (! $hasInvoiceThisYear) {
                // Check if we had invoices in previous years
                $lastInvoice = Invoice::orderBy('created_at', 'desc')->first();
                if ($lastInvoice && $lastInvoice->created_at->year < $currentYear) {
                    $this->next_number = 1;
                    $this->save();
                }
            }
        }

        $number = str_pad($this->next_number, $this->number_length, '0', STR_PAD_LEFT);
        $year = now()->year;

        // Replace placeholders: {prefix}, {number}, {year}
        $invoiceNumber = str_replace(
            ['{prefix}', '{number}', '{year}'],
            [$this->prefix, $number, $year],
            $this->format ?? '{prefix}-{number}'
        );

        // Increment next number
        $this->increment('next_number');

        return $invoiceNumber;
    }

    /**
     * Get preview of next invoice number (without incrementing)
     */
    public function getPreviewNumber(): string
    {
        $number = str_pad($this->next_number, $this->number_length, '0', STR_PAD_LEFT);
        $year = now()->year;

        // Replace placeholders: {prefix}, {number}, {year}
        $invoiceNumber = str_replace(
            ['{prefix}', '{number}', '{year}'],
            [$this->prefix, $number, $year],
            $this->format ?? '{prefix}-{number}'
        );

        return $invoiceNumber;
    }
}
