121 lines
3.0 KiB
PHP
121 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\Schema;
|
|
|
|
class Category extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
public const RESERVATION_MINUTES = 10;
|
|
|
|
protected $table = 'categories';
|
|
|
|
protected $fillable = [
|
|
'name',
|
|
'description',
|
|
'merk',
|
|
'model',
|
|
'kategori',
|
|
'price',
|
|
'year',
|
|
'mesin_cc',
|
|
'transmisi',
|
|
'bahan_bakar',
|
|
'image',
|
|
'status',
|
|
];
|
|
|
|
protected $appends = [
|
|
'image_url',
|
|
];
|
|
|
|
public function getImageUrlAttribute()
|
|
{
|
|
if ($this->image) {
|
|
return asset('storage/' . $this->image);
|
|
}
|
|
|
|
return asset('images/default-car.svg');
|
|
}
|
|
|
|
public function getStatusLabelAttribute()
|
|
{
|
|
return [
|
|
'available' => 'Tersedia',
|
|
'reserved' => 'Sedang Dipesan',
|
|
'sold' => 'Terjual',
|
|
][$this->status] ?? ucfirst($this->status);
|
|
}
|
|
|
|
public static function releaseExpiredReservations(): int
|
|
{
|
|
if (!Schema::hasColumn('transactions', 'expires_at')) {
|
|
return 0;
|
|
}
|
|
|
|
$expiredCategoryIds = Transaction::where('payment_status', 'pending')
|
|
->whereNotNull('expires_at')
|
|
->where('expires_at', '<=', now())
|
|
->pluck('category_id')
|
|
->unique()
|
|
->values();
|
|
|
|
$expiredCount = Transaction::where('payment_status', 'pending')
|
|
->whereNotNull('expires_at')
|
|
->where('expires_at', '<=', now())
|
|
->update(['payment_status' => 'cancelled']);
|
|
|
|
static::where('status', 'reserved')
|
|
->whereIn('id', $expiredCategoryIds)
|
|
->whereDoesntHave('transactions', function ($query) {
|
|
$query->where('payment_status', 'pending')
|
|
->whereNotNull('expires_at')
|
|
->where('expires_at', '>', now());
|
|
})
|
|
->update(['status' => 'available']);
|
|
|
|
return $expiredCount;
|
|
}
|
|
|
|
public function isReserved(): bool
|
|
{
|
|
return $this->status === 'reserved'
|
|
&& (bool) $this->activeReservation();
|
|
}
|
|
|
|
public function activeReservation(): ?Transaction
|
|
{
|
|
return $this->transactions()
|
|
->where('payment_status', 'pending')
|
|
->whereNotNull('expires_at')
|
|
->where('expires_at', '>', now())
|
|
->latest()
|
|
->first();
|
|
}
|
|
|
|
/**
|
|
* Get the users who have favorited this category
|
|
*/
|
|
public function favoritedBy()
|
|
{
|
|
return $this->belongsToMany(User::class, 'favorites', 'category_id', 'username', 'id', 'username');
|
|
}
|
|
|
|
public function transactions()
|
|
{
|
|
return $this->hasMany(Transaction::class);
|
|
}
|
|
|
|
/**
|
|
* Check if the category is favorited by a specific user
|
|
*/
|
|
public function isFavoritedBy($username)
|
|
{
|
|
return $this->favoritedBy()->where('favorites.username', $username)->exists();
|
|
}
|
|
}
|