<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use App\Traits\HasRowLevelSecurity;

class Invoice extends Model
{
    use HasFactory, HasRowLevelSecurity;

    /**
     * Apply custom Row-Level Security for Invoices.
     * Restricts access to invoices associated with the authenticated user's orders.
     */
    public static function applyRowLevelSecurity(Builder $builder, $user): void
    {
        $builder->whereHas('order', function ($query) use ($user) {
            $query->where('userid', $user->id);
        });
    }

    protected $fillable = [
        'invoice_number',
        'order_id',
        'customer_name',
        'customer_email',
        'billing_address',
        'invoice_date',
        'subtotal',
        'tax_percentage',
        'tax_amount',
        'shipping_cost',
        'discount_amount',
        'total_amount',
        'status',
        'points_applied',
        'points_used_flag',
    ];

    protected $casts = [
        'invoice_date' => 'date',
    ];

    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id', 'order_id');
    }
}
