<?php

namespace App\Models;

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

class Code extends Model
{
    protected $fillable = [
        'guid',
        'qr',
        'status',
        'islucky',
        'exported',
        'lastverified',
        'ipv',
        'product_id',
        'attempts',
    ];

    protected $casts = [
        'islucky' => 'boolean',
        'exported' => 'date',
        'lastverified' => 'date',
        'attempts' => 'integer',
    ];

    /**
     * Get the product associated with this code
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * Get the sellers assigned to this code
     */
    public function sellers(): BelongsToMany
    {
        return $this->belongsToMany(Seller::class, 'seller_qr', 'code_id', 'seller_id')
                    ->withTimestamps();
    }

    /**
     * Get the customers who verified this code
     */
    public function customers(): HasMany
    {
        return $this->hasMany(Customer::class, 'serial', 'qr');
    }

    /**
     * Scope to get unused codes
     */
    public function scopeUnused($query)
    {
        return $query->where('status', 'unused');
    }

    /**
     * Scope to get lucky codes
     */
    public function scopeLucky($query)
    {
        return $query->where('islucky', true);
    }

    /**
     * Scope to get codes verified between dates
     */
    public function scopeVerifiedBetween($query, $start, $end)
    {
        return $query->whereBetween('lastverified', [$start, $end]);
    }
}
