<?php

namespace App\Models;

use App\Traits\VisibleToAdmin;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Kyc extends Model
{
    use HasFactory;
    use VisibleToAdmin;

    // This tells the trait how to reach the user who controls visibility
    protected function adminVisibilityRelation(): string
    {
        return 'user';
    }

    protected $table = 'kycs';

    /** ================= STATUSES ================= */
    public const STATUS_PENDING = 'pending';
    public const STATUS_VERIFIED = 'verified';
    public const STATUS_REJECTED = 'rejected';

    protected $fillable = [
        'user_id',
        'id_type',
        'id_number',
        'id_document_paths',
        'address',
        'address_document_path',
        'status',
        'rejection_reason',
        'data',
        'verified_at',
        'version',
        'is_latest',
    ];

    protected $casts = [
        'verified_at' => 'datetime',
        'id_document_paths' => 'array',
        'data' => 'array',
        'is_latest' => 'boolean',
    ];

    /** ================= RELATIONSHIPS ================= */

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

    /** ================= STATUS HELPERS ================= */

    public function isPending(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    public function isVerified(): bool
    {
        return $this->status === self::STATUS_VERIFIED;
    }

    public function isRejected(): bool
    {
        return $this->status === self::STATUS_REJECTED;
    }

    /** ================= QUERY SCOPES ================= */

    public function scopePending($query)
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    public function scopeVerified($query)
    {
        return $query->where('status', self::STATUS_VERIFIED);
    }

    public function scopeRejected($query)
    {
        return $query->where('status', self::STATUS_REJECTED);
    }

    public function scopeLatestForUser($query, int $userId)
    {
        return $query->where('user_id', $userId)
            ->where('is_latest', true);
    }
}
