<?php

namespace App\Models\Rental;

use App\Models\Car;
use App\Models\Customer;
use App\Models\User;
use App\Models\Branch;
use App\Traits\BranchScoped;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Invoice extends Model
{
    use BranchScoped;

    protected $fillable = [
        'branch_id',
        'invoice_number',
        'invoice_date',
        'due_date',
        'rental_id',
        'car_id',
        'customer_id',
        'type', // rental, sale, service, etc.
        'description',
        'subtotal',
        'tax_amount',
        'tax_percentage',
        'total_amount',
        'paid_amount',
        'remaining_amount',
        'status', // draft, issued, partially_paid, paid, cancelled
        'payment_method',
        'qr_code_data',
        'notes',
        'created_by',
    ];

    protected $casts = [
        'invoice_date' => 'datetime',
        'due_date' => 'datetime',
        'subtotal' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'tax_percentage' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'paid_amount' => 'decimal:2',
        'remaining_amount' => 'decimal:2',
    ];

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function rental(): BelongsTo
    {
        return $this->belongsTo(Rental::class);
    }

    public function car(): BelongsTo
    {
        return $this->belongsTo(Car::class);
    }

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function receipts(): HasMany
    {
        return $this->hasMany(Receipt::class);
    }

    public function paymentVouchers(): HasMany
    {
        return $this->hasMany(PaymentVoucher::class);
    }

    public function items(): HasMany
    {
        return $this->hasMany(InvoiceItem::class);
    }

    public function generateInvoiceNumber()
    {
        $prefix = 'INV';
        $year = date('Y');
        $month = date('m');
        $count = static::whereYear('created_at', now()->year)
            ->whereMonth('created_at', now()->month)
            ->count() + 1;

        return sprintf('%s-%s-%s-%05d', $prefix, $year, $month, $count);
    }

    public function calculateTax()
    {
        return round($this->subtotal * ($this->tax_percentage / 100), 2);
    }

    public function generateQRCodeData()
    {
        return json_encode([
            'invoice_number' => $this->invoice_number,
            'amount' => $this->total_amount,
            'date' => $this->invoice_date->format('Y-m-d'),
            'seller' => $this->branch->name ?? 'Company',
        ]);
    }

    public function markAsPaid()
    {
        $this->update([
            'status' => 'paid',
            'paid_amount' => $this->total_amount,
            'remaining_amount' => 0,
        ]);
    }

    public function recordPayment($amount)
    {
        $newPaidAmount = min($this->paid_amount + $amount, $this->total_amount);
        $remaining = $this->total_amount - $newPaidAmount;

        $this->update([
            'paid_amount' => $newPaidAmount,
            'remaining_amount' => $remaining,
            'status' => $remaining > 0 ? 'partially_paid' : 'paid',
        ]);
    }
}
