<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AbandonedCheckout extends Model
{
    protected $fillable = [
        'user_id',
        'package_id',
        'email',
        'checkout_state',
        'last_step',
        'abandoned_at',
        'reminded_at',
        'reminder_stage',
        'expires_at',
        'converted',
    ];

    protected $casts = [
        'checkout_state' => 'array',
        'abandoned_at' => 'datetime',
        'reminded_at' => 'datetime',
        'expires_at' => 'datetime',
        'converted' => 'boolean',
        'last_step' => 'integer',
    ];

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

    public function package(): BelongsTo
    {
        return $this->belongsTo(Package::class)->withTrashed();
    }

    /**
     * Markiert den Checkout als erfolgreich abgeschlossen
     */
    public function markAsConverted(): void
    {
        $this->update([
            'converted' => true,
            'reminder_stage' => 'converted',
        ]);
    }

    /**
     * Aktualisiert den Reminder-Status
     */
    public function updateReminderStage(string $stage): void
    {
        $this->update([
            'reminder_stage' => $stage,
            'reminded_at' => now(),
        ]);
    }

    /**
     * Prüft ob der Checkout noch gültig ist
     */
    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    /**
     * Scope für Checkouts die erinnert werden sollen
     */
    public function scopeReadyForReminder($query, string $stage, int $hours)
    {
        return $query->where('reminder_stage', '!=', $stage)
                    ->where('reminder_stage', '!=', 'converted')
                    ->where('abandoned_at', '<=', now()->subHours($hours))
                    ->where(function ($q) {
                        $q->whereNull('reminded_at')
                          ->orWhere('reminded_at', '<=', now()->subHours(24));
                    });
    }
}
