<?php

namespace MtcPharmacy\ReferAFriend\Models;

use Illuminate\Database\Eloquent\Model;
use Mtc\Modules\Members\Models\Member;
use Mtc\Shop\Coupon;

class ReferralReward extends Model
{
    protected $table = 'referral_rewards';

    protected $fillable = [
        'referral_id',
        'member_id',
        'type',
        'coupon_id',
        'coupon_code',
        'amount',
        'status',
        'issued_at',
        'redeemed_at',
        'revoked_at',
        'revoke_reason',
        'admin_id',
    ];

    protected $casts = [
        'amount'      => 'decimal:2',
        'issued_at'   => 'datetime',
        'redeemed_at' => 'datetime',
        'revoked_at'  => 'datetime',
    ];

    // --- Relationships ---

    public function referral()
    {
        return $this->belongsTo(Referral::class, 'referral_id');
    }

    public function member()
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class, 'coupon_id');
    }

    // --- Scopes ---

    public function scopeIssued($query)
    {
        return $query->where('status', 'issued');
    }

    public function scopeRedeemed($query)
    {
        return $query->where('status', 'redeemed');
    }

    public function scopeAvailable($query, $memberId)
    {
        return $query->where('member_id', $memberId)
            ->where('status', 'issued')
            ->whereHas('coupon', function ($q) {
                $q->where('redemptions', '>', 0)
                    ->where('exp_date', '>=', now()->format('Y-m-d'));
            });
    }
}
