<?php

namespace App\Models;

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

class CommissionEarning extends Model
{
    use HasFactory;

    protected $primaryKey = 'earning_id';

    protected $fillable = [
        'booking_id',
        'commission_rate',
        'commission_amount',
        'earning_status',
        'processed_at',
        'paid_out_at'
    ];

    protected $casts = [
        'commission_rate' => 'decimal:2',
        'commission_amount' => 'decimal:2',
        'processed_at' => 'datetime',
        'paid_out_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    // Relationships
    public function booking()
    {
        return $this->belongsTo(Booking::class, 'booking_id', 'booking_id');
    }

    // Scopes
    public function scopePending($query)
    {
        return $query->where('earning_status', 'pending');
    }

    public function scopeProcessed($query)
    {
        return $query->where('earning_status', 'processed');
    }

    public function scopePaidOut($query)
    {
        return $query->where('earning_status', 'paid_out');
    }

    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereHas('booking', function($q) use ($startDate, $endDate) {
            $q->whereBetween('created_at', [$startDate, $endDate]);
        });
    }

    // Methods
    public function markAsProcessed()
    {
        $this->update([
            'earning_status' => 'processed',
            'processed_at' => now()
        ]);
    }

    public function markAsPaidOut()
    {
        $this->update([
            'earning_status' => 'paid_out',
            'paid_out_at' => now()
        ]);
    }

    public function isProcessed()
    {
        return $this->earning_status === 'processed';
    }

    public function isPaidOut()
    {
        return $this->earning_status === 'paid_out';
    }
}
