<?php

namespace App\Models;

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

class DailyClosingReport extends Model
{
    use HasFactory;

    protected $fillable = [
        'restaurant_id',
        'branch_id',
        'closing_date',
        'start_date',
        'start_time',
        'end_date',
        'end_time',
        'available_cash',
        'gross_sales',
        'online_card_payments',
        'food_bills_total',
        'advance_payments',
        'expenses_paid',
        'daily_wages',
        'total_deductions',
        'remaining_cash',
        'difference',
        'has_difference',
        'comments',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'closing_date' => 'date',
        'start_date' => 'date',
        'end_date' => 'date',
        'available_cash' => 'decimal:2',
        'gross_sales' => 'decimal:2',
        'online_card_payments' => 'decimal:2',
        'food_bills_total' => 'decimal:2',
        'advance_payments' => 'decimal:2',
        'expenses_paid' => 'decimal:2',
        'daily_wages' => 'decimal:2',
        'total_deductions' => 'decimal:2',
        'remaining_cash' => 'decimal:2',
        'difference' => 'decimal:2',
        'has_difference' => 'boolean',
    ];

    // Relationships
    public function restaurant()
    {
        return $this->belongsTo(Restaurant::class, 'restaurant_id');
    }

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

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

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    // 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 scopeForDate($query, $date)
    {
        return $query->whereDate('closing_date', $date);
    }

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

    public function scopeDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('closing_date', [$startDate, $endDate]);
    }

    // Accessor for formatted difference
    public function getFormattedDifferenceAttribute()
    {
        return number_format(abs($this->difference), 2);
    }
}
