<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use App\Models\UserLogin;
use Illuminate\Support\Carbon;

class User extends Authenticatable implements FilamentUser, MustVerifyEmail
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'email_otp',
        'email_otp_expires_at',
        'otp_expires_at',
        'otp_last_sent_at',
        'verification_token',
        'email_verified_at',
    ];

    protected $hidden = [
        'password',
        'remember_token',
        'email_otp',
    ];

    protected $casts = [
        'email_verified_at'      => 'datetime',
        'email_otp_expires_at'   => 'datetime',
        'otp_expires_at'         => 'datetime',
        'otp_last_sent_at'       => 'datetime',
        'password'               => 'hashed',
    ];

    public function canAccessPanel(Panel $panel): bool
    {
        return true;
    }

    public function logins()
    {
        return $this->hasMany(UserLogin::class);
    }

    public function transactions()
    {
        return $this->hasMany(\App\Models\BorrowTransaction::class, 'anggota_id');
    }

    public function anggota()
    {
        return $this->hasOne(\App\Models\Anggota::class, 'user_id');
    }

    public function getRecentLogins($perPage = 10)
    {
        return $this->logins()->latest()->paginate($perPage);
    }

    // ==============================
    // 🔥 EMAIL VERIFICATION (WAJIB)
    // ==============================

    public function hasVerifiedEmail()
    {
        return !is_null($this->email_verified_at);
    }

    public function markEmailAsVerified()
    {
        if ($this->hasVerifiedEmail()) {
            return true;
        }

        $this->forceFill([
            'email_verified_at' => Carbon::now(),
        ])->save();

        return true;
    }

    public function sendEmailVerificationNotification()
    {
        $this->notify(new \Illuminate\Auth\Notifications\VerifyEmail());
    }
}

