<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'role',
        'is_banned', 'ban_reason', 'banned_at',
        'google_id', 'email_verified_at',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'banned_at'         => 'datetime',
        'is_banned'         => 'boolean',
        'password'          => 'hashed',
    ];

    

    // ── Role helpers ──────────────────────────────────────────────────
    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }

    public function isUser(): bool
    {
        return $this->role === 'user';
    }

    public function isBanned(): bool
    {
        return (bool) $this->is_banned;
    }

    // ── Relasi ────────────────────────────────────────────────────────
    public function analyses()
    {
        return $this->hasMany(AnalysisResult::class);
    }

    public function companies()
    {
        return $this->hasMany(Company::class);
    }

    public function subscriptions()
    {
        return $this->hasMany(Subscription::class);
    }

    public function currentSubscription()
    {
        return $this->subscriptions()
            ->where('status', 'active')
            ->latest()
            ->first();
    }

    public function userSetting(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(UserSetting::class);
    }

    public function news(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(News::class);
    }

    // Accessor: Auth::user()->settings['news_notif']
    // Dipakai di index.blade.php:
    //   @php $isChecked = Auth::user()->settings[$key] ?? false; @endphp
    public function getSettingsAttribute(): array
    {
        $s = $this->userSetting;
        if (! $s) {
            return [];
        }
        return $s->only([
            'news_notif',
            'promo_notif',
            'report_notif',
            'email_notif',
            'browser_notif',
        ]);
    }

    // ── Scope ─────────────────────────────────────────────────────────
    public function scopeAdmins($query)
    {
        return $query->where('role', 'admin');
    }

    public function scopeRegularUsers($query)
    {
        return $query->where('role', 'user');
    }

    public function scopeActive($query)
    {
        return $query->where('is_banned', false);
    }
}