<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Branch extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'description',
        'address',
        'contact_number',
        'wallet',
        'total_deposit',
        'active',
        'created_by',
        'updated_by',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'active' => 'boolean',
        'created_by' => 'integer',
        'updated_by' => 'integer',
        'wallet' => 'decimal:2',
        'total_deposit' => 'decimal:2',
    ];

    /**
     * The attributes that should be appended to the model's array form.
     *
     * @var array<string>
     */
    protected $appends = [
        'credit_balance',
    ];

    /**
     * Get users that belong to this branch
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_branch')
            ->withTimestamps()
            ->withPivot('role');
    }

    /**
     * Get credits for this branch
     */
    public function credits(): HasMany
    {
        return $this->hasMany(Credit::class);
    }

    /**
     * Calculate the credit balance for this branch
     * 
     * @return float
     */
    public function getCreditBalanceAttribute(): float
    {
        $deposits = $this->credits()
            ->where('type', 'deposit')
            ->where('status', 'approved')
            ->where('active', true)
            ->sum('amount');

        $withdrawals = $this->credits()
            ->where('type', 'withdrawal')
            ->where('status', 'approved')
            ->where('active', true)
            ->sum('amount');

        return (float) ($deposits - $withdrawals);
    }
}
