<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Carbon\Carbon;

class HoldSale extends Model
{
    use HasFactory;

    protected $fillable = [
        'reference',
        'customer_id',
        'user_id',
        'items',
        'subtotal',
        'vat',
        'discount',
        'total',
        'notes',
        'status',
        'expires_at',
        'converted_at',
    ];

    protected $casts = [
        'items' => 'array',
        'subtotal' => 'decimal:2',
        'vat' => 'decimal:2',
        'discount' => 'decimal:2',
        'total' => 'decimal:2',
        'expires_at' => 'datetime',
        'converted_at' => 'datetime',
    ];

    // Relationships
    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

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

    // Scopes
    public function scopeByUser(Builder $query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function scopeActive(Builder $query)
    {
        return $query->where('status', 'active')
                    ->where('expires_at', '>', now());
    }

    public function scopeExpired(Builder $query)
    {
        return $query->where(function($q) {
            $q->where('status', 'expired')
              ->orWhere('expires_at', '<=', now());
        });
    }

    public function scopeConverted(Builder $query)
    {
        return $query->where('status', 'converted');
    }

    // Methods
    public function getIsExpiredAttribute()
    {
        return $this->expires_at <= now() || $this->status === 'expired';
    }

    public function markAsExpired()
    {
        $this->update(['status' => 'expired']);
    }

    public function extendValidity($hours = 24)
    {
        $this->update([
            'expires_at' => now()->addHours($hours)
        ]);
    }

    public static function generateReference()
    {
        $prefix = 'HOLD';
        $date = date('Ymd');
        $random = strtoupper(substr(md5(uniqid()), 0, 6));
        
        return "{$prefix}-{$date}-{$random}";
    }
}