<?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;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

use App\Models\Role; 
use App\Models\Campus; 

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

    // Model User menggunakan koneksi database default (pmb_cms)
    protected $connection = 'pmb_cms'; 

    /**
     * Kolom yang dapat diisi massal.
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'role_id',        
        'campus_id',     // <-- DIGANTI: Sekarang menggunakan ID
    ];

    /**
     * Kolom yang harus disembunyikan.
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Casting atribut.
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    protected $appends = ['role_name']; 
    
    /**
     * Relasi User memiliki Role.
     */
    public function role(): BelongsTo
    {
        return $this->belongsTo(Role::class);
    }
    
    /**
     * Relasi ke Model Campus (menggunakan campus_id).
     */
    public function campus(): BelongsTo
    {
        // campus_id (di users) terhubung ke id (di campuses)
        return $this->belongsTo(Campus::class, 'campus_id', 'id');
    }
    
    // ================================================================
    // ACCESSOR (Tambahan untuk Mengakses Nama Role dengan Mudah)
    // ================================================================
    
    public function getRoleNameAttribute(): ?string
    {
        return $this->role ? $this->role->name : null;
    }


    // ================================================================
    // METHOD PENCEGAHAN AKSES (Role Checking)
    // ================================================================

    public function isSuperAdmin(): bool
    {
        return $this->role_id === Role::ROLE_SUPERADMIN;
    }

    public function isCampusAdmin(): bool
    {
        return $this->role_id === Role::ROLE_CAMPUS_ADMIN;
    }
    
    /**
     * Cek apakah User adalah Admin dari kampus tertentu.
     * @param int|null $campusId ID kampus yang diakses
     * @return bool
     */
    public function isAdminForCampus(?int $campusId): bool
    {
        // Superadmin selalu memiliki akses ke semua kampus
        if ($this->isSuperAdmin()) {
            return true;
        }

        // Admin Kampus hanya memiliki akses jika campus_id mereka cocok
        if ($this->isCampusAdmin() && $this->campus_id === $campusId) {
            return true;
        }

        return false;
    }
}