<?php

namespace App\Models;

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

class PettyCashBalance extends Model
{
    use HasFactory;

    protected $fillable = [
        'restaurant_id',
        'branch_id',
        'current_balance',
        'daily_limit',
        'transaction_limit',
        'is_active',
        'last_transaction_at',
    ];

    protected $casts = [
        'current_balance' => 'decimal:2',
        'daily_limit' => 'decimal:2',
        'transaction_limit' => 'decimal:2',
        'is_active' => 'boolean',
        'last_transaction_at' => 'datetime',
    ];

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

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

    public function transactions(): HasMany
    {
        return $this->hasMany(PettyCashTransaction::class, 'branch_id', 'branch_id')
            ->where('restaurant_id', $this->restaurant_id);
    }

    // Scopes
    public function scopeForRestaurant($query, $restaurantId)
    {
        return $query->where('restaurant_id', $restaurantId);
    }

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

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

    // Helper methods
    public function canWithdraw(float $amount): bool
    {
        return $this->is_active; // Only check if active, ignore balance
    }

    public function hasReachedDailyLimit(float $todayWithdrawals): bool
    {
        return $todayWithdrawals >= $this->daily_limit;
    }

    public function deposit(float $amount, User $user, string $description, ?string $notes = null): PettyCashTransaction
    {
        $balanceBefore = $this->current_balance;
        $balanceAfter = $balanceBefore + $amount;

        $transaction = PettyCashTransaction::create([
            'restaurant_id' => $this->restaurant_id,
            'branch_id' => $this->branch_id,
            'user_id' => $user->id,
            'type' => 'deposit',
            'amount' => $amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'description' => $description,
            'notes' => $notes,
        ]);

        $this->update([
            'current_balance' => $balanceAfter,
            'last_transaction_at' => now(),
        ]);

        return $transaction;
    }

    public function withdraw(float $amount, User $user, string $description, ?Expense $expense = null, ?string $notes = null): PettyCashTransaction
    {
        if (!$this->is_active) {
            throw new \Exception('Petty cash is not active');
        }

        // Allow withdrawal regardless of current balance
        $balanceBefore = $this->current_balance;
        $balanceAfter = $balanceBefore - $amount; // Can go negative

        $transaction = PettyCashTransaction::create([
            'restaurant_id' => $this->restaurant_id,
            'branch_id' => $this->branch_id,
            'user_id' => $user->id,
            'expense_id' => $expense?->id,
            'type' => 'withdrawal',
            'amount' => $amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'description' => $description,
            'notes' => $notes,
            // transaction_number will be auto-generated by the model
        ]);

        $this->update([
            'current_balance' => $balanceAfter,
            'last_transaction_at' => now(),
        ]);

        return $transaction;
    }

    public function adjust(float $amount, User $user, string $description, ?string $notes = null): PettyCashTransaction
    {
        $balanceBefore = $this->current_balance;
        $balanceAfter = $amount; // Adjustment sets the balance to the specified amount

        $transaction = PettyCashTransaction::create([
            'restaurant_id' => $this->restaurant_id,
            'branch_id' => $this->branch_id,
            'user_id' => $user->id,
            'type' => 'adjustment',
            'amount' => $balanceAfter - $balanceBefore, // The difference
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'description' => $description,
            'notes' => $notes,
        ]);

        $this->update([
            'current_balance' => $balanceAfter,
            'last_transaction_at' => now(),
        ]);

        return $transaction;
    }

    public function getTodayWithdrawals(): float
    {
        return $this->transactions()
            ->where('type', 'withdrawal')
            ->whereDate('created_at', today())
            ->sum('amount');
    }

    public function getFormattedBalanceAttribute(): string
    {
        return 'KES ' . number_format($this->current_balance, 2);
    }

    public function getFormattedDailyLimitAttribute(): string
    {
        return 'KES ' . number_format($this->daily_limit, 2);
    }

    public function getFormattedTransactionLimitAttribute(): string
    {
        return 'KES ' . number_format($this->transaction_limit, 2);
    }

    public function getStatusColorAttribute(): string
    {
        if (!$this->is_active) return 'gray';
        
        if ($this->current_balance <= 0) return 'red';
        if ($this->current_balance < 1000) return 'yellow';
        return 'green';
    }

    public function getStatusLabelAttribute(): string
    {
        if (!$this->is_active) return 'Inactive';
        
        if ($this->current_balance <= 0) return 'Empty';
        if ($this->current_balance < 1000) return 'Low Balance';
        return 'Active';
    }
}