<?php

namespace App\Models;

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

class CashBook extends Model
{
    use HasFactory;

    protected $fillable = ['uuid', 'opening_amount', 'closed', 'user_id'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'closed' => 'boolean',
    ];

    /**
     * Setting default route key
     *
     * @return string
     */
    public function getRouteKeyName(): string
    {
        return 'uuid';
    }

    /**
     * Sale under customer
     *
     * @return     HasMany  The has many.
     */
    public function sales(): HasMany
    {
        return $this->hasMany(Sale::class, 'cash_book_id');
    }
    public function getInProgress()
    {
        return $this->sales()->where('is_cancelled', false)->whereNull('completed_at')->count();
    }
    public function getInCompleted()
    {
        return $this->sales()->whereNotNull('prepared_at')->whereNotNull('completed_at')->count();
    }
    public function getInCancelled()
    {
        return $this->sales()->where('is_cancelled', true)->count();
    }
    public function canBeClosed()
    {
        // Calculate the total count of completed and cancelled sales
        $completedOrCancelled = $this->getInCompleted() + $this->getInCancelled();
        // Check if the total count of completed and cancelled sales matches the total count of sales
        return $completedOrCancelled === $this->sales()->count();
    }

    public function getSalesTotalAmount()
    {
        return $this->sales()->sum('payable_after_all');
    }

    public function getSalesTotalTaxAmount()
    {
        return $this->sales()->sum('tax_amount');
    }

    public function getSalesTotalProfitAmount()
    {
        return $this->sales()->sum('profit_after_all');
    }

    public function getSalesTotalDiscountAmount()
    {
        return $this->sales()->sum('discount_amount');
    }

    public function getSalesTotalItems()
    {
        return $this->sales()->sum('cart_total_items');
    }

    public function getSalesTotalOrders()
    {
        return $this->sales()->count();
    }

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