<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class BranchProduct extends Model
{
    use HasFactory;

    protected $fillable = [
        'branch_id',
        'product_id',
        'is_available',
        'custom_price',
        'track_stock',
        'stock_quantity',
        'minimum_stock',
        'stock_unit',
    ];

    protected $casts = [
        'is_available'   => 'boolean',
        'custom_price'   => 'decimal:2',
        'track_stock'    => 'boolean',
        'stock_quantity' => 'decimal:2',
        'minimum_stock'  => 'decimal:2',
    ];

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

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

    public function scopeAvailable($query)
    {
        return $query->where('is_available', true);
    }

    public function scopeForBranch($query, $branchId)
    {
        return $query->where('branch_id', $branchId);
    }

    public function getEffectivePrice(): float
    {
        return $this->custom_price ?? $this->product->base_price;
    }
}
