<?php

namespace App\Models;

use App\Models\AppSetting;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class DriverCashbackWallet extends Model
{
    protected $fillable = [
        'driver_id',
        'balance',
        'first_deposit_at',
        'last_cashback_date',
        'consecutive_days',
    ];

    protected $casts = [
        'balance' => 'decimal:2',
        'first_deposit_at' => 'datetime',
        'last_cashback_date' => 'date',
    ];

    public function driver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'driver_id');
    }

    public function transactions(): HasMany
    {
        return $this->hasMany(DriverCashbackTransaction::class, 'cashback_wallet_id')->orderByDesc('created_at');
    }

    public function canTransfer(): bool
    {
        if (!$this->first_deposit_at) {
            return false;
        }
        $lockDays = (int) (AppSetting::first()->cashback_lock_days ?? 30);
        return now()->gte($this->first_deposit_at->addDays($lockDays));
    }

    public function getAvailableAtAttribute(): ?\Carbon\Carbon
    {
        if (!$this->first_deposit_at) {
            return null;
        }
        $lockDays = (int) (AppSetting::first()->cashback_lock_days ?? 30);
        return $this->first_deposit_at->copy()->addDays($lockDays);
    }
}
