<?php

namespace App\Models;

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

class Booking extends Model
{
    use HasFactory;

    protected $fillable = [
        'kode_booking', 'user_id', 'lapangan_id',
        'tanggal', 'jam_mulai', 'jam_selesai',
        'durasi_jam', 'total_harga', 'status',
        'catatan', 'alasan_penolakan',
    ];

    protected $casts = [
        'tanggal'     => 'date',
        'total_harga' => 'integer',
        'durasi_jam'  => 'integer',
    ];

    /** Auto-generate kode_booking saat membuat booking baru */
    protected static function boot(): void
    {
        parent::boot();
        static::creating(function ($booking) {
            if (empty($booking->kode_booking)) {
                $booking->kode_booking = self::generateKodeBooking();
            }
        });
    }

    /** Generate kode unik format: BK-YYYYMMDD-XXXXX */
    public static function generateKodeBooking(): string
    {
        $tanggal = Carbon::now()->format('Ymd');
        $prefix  = "BK-{$tanggal}-";
        $last    = self::where('kode_booking', 'LIKE', "{$prefix}%")
            ->orderByDesc('kode_booking')->first();
        $number  = $last ? ((int) substr($last->kode_booking, -5)) + 1 : 1;
        return $prefix . str_pad($number, 5, '0', STR_PAD_LEFT);
    }

    public function user()     { return $this->belongsTo(User::class); }
    public function lapangan() { return $this->belongsTo(Lapangan::class); }

    public function scopeHariIni($q)  { return $q->whereDate('tanggal', Carbon::today()); }
    public function scopeBulanIni($q) {
        return $q->whereMonth('tanggal', Carbon::now()->month)
                 ->whereYear('tanggal', Carbon::now()->year);
    }

    public function bisaDibatalkan(): bool  { return $this->status === 'pending'; }
    public function bisaDikonfirmasi(): bool { return $this->status === 'pending'; }
    public function bisaDitolak(): bool     { return in_array($this->status, ['pending', 'confirmed']); }
}
