<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Branch extends Model
{
    protected $fillable = [
        'name',
        'code',
        'phone',
        'email',
        'address',
        'city',
        'region',
        'latitude',
        'longitude',
        'status',
        'description',
        'manager_id',
    ];

    protected $casts = [
        'latitude' => 'decimal:8',
        'longitude' => 'decimal:8',
    ];

    public function manager()
    {
        return $this->belongsTo(\App\Models\User::class, 'manager_id');
    }

    public function employees()
    {
        return $this->hasMany(Employee::class);
    }

    public function cars()
    {
        return $this->hasMany(Car::class);
    }

    public function rentals()
    {
        return $this->hasMany(\App\Models\Rental\Rental::class);
    }

    public function expenses()
    {
        return $this->hasMany(\App\Models\Rental\Expense::class);
    }

    public function maintenanceRecords()
    {
        return $this->hasMany(\App\Models\Rental\MaintenanceRecord::class);
    }

    public function getTotalCarsAttribute()
    {
        return $this->cars()->count();
    }

    public function getAvailableCarsAttribute()
    {
        return $this->cars()->where('rental_status', 'available')->count();
    }

    public function getRentedCarsAttribute()
    {
        return $this->cars()->where('rental_status', 'rented')->count();
    }

    public function getMaintenanceCarsAttribute()
    {
        return $this->cars()->where('rental_status', 'maintenance')->count();
    }

    public function getDailyRevenueAttribute()
    {
        return $this->rentals()
            ->where('status', 'closed')
            ->whereDate('end_date', today())
            ->sum('total_amount');
    }

    public function getTodayRentalsAttribute()
    {
        return $this->rentals()
            ->where('status', 'open')
            ->whereDate('start_date', '<=', today())
            ->whereDate('end_date', '>=', today())
            ->count();
    }
}
