<?php
// app/Models/Users.php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravolt\Indonesia\Models\Province;
use Laravolt\Indonesia\Models\City;
use Laravolt\Indonesia\Models\District;
use Laravolt\Indonesia\Models\Village;

class Users extends Authenticatable
{
    use Notifiable;

    protected $table = 'tbl_users';
    protected $primaryKey = 'user_id';

    protected $fillable = [
        'username', 
        'address',
        'email', 
        'password', 
        'role',             
        'is_admin',         
        'fullname',
        'phone',
        'bio',
        'birth_date',
        'gender',
        'province_code',
        'city_code',
        'district_code',
        'village_code',
        'postal_code',
        'avatar',
        'verification_code',
        'verification_expiry',
        'is_verified'
    ];

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

    protected $casts = [
        'verification_expiry' => 'datetime',
        'is_verified' => 'boolean',
        'is_admin' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Boot function untuk menjaga konsistensi data
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($user) {
            $user->syncRoleAndIsAdmin();
        });

        static::updating(function ($user) {
            $user->syncRoleAndIsAdmin();
        });
    }

    /**
     * Sinkronisasi antara role dan is_admin
     */
    protected function syncRoleAndIsAdmin()
    {
        if (isset($this->attributes['role'])) {
            $this->attributes['is_admin'] = ($this->attributes['role'] === 'admin');
        }
        elseif (isset($this->attributes['is_admin'])) {
            $this->attributes['role'] = $this->attributes['is_admin'] ? 'admin' : 'pengguna';
        }
    }

    /**
     * Setter untuk role
     */
    public function setRoleAttribute($value)
    {
        $this->attributes['role'] = $value;
        $this->attributes['is_admin'] = ($value === 'admin');
    }

    /**
     * Setter untuk is_admin
     */
    public function setIsAdminAttribute($value)
    {
        $this->attributes['is_admin'] = $value;
        $this->attributes['role'] = $value ? 'admin' : 'pengguna';
    }

    /**
     * Cek apakah user adalah admin
     */
    public function isAdmin(): bool
    {
        return $this->is_admin == true || $this->role === 'admin';
    }

    /**
     * Get role name yang lebih readable
     */
    public function getRoleNameAttribute(): string
    {
        return $this->isAdmin() ? 'Administrator' : 'Pengguna';
    }

    /**
     * Scope untuk filter admin
     */
    public function scopeAdmins($query)
    {
        return $query->where('is_admin', true);
    }

    /**
     * Scope untuk filter pengguna biasa
     */
    public function scopeRegularUsers($query)
    {
        return $query->where('is_admin', false);
    }

    /**
     * Cek apakah user sudah terverifikasi
     */
    public function isVerified(): bool
    {
        return $this->is_verified == true;
    }

    /**
     * Mendapatkan URL avatar
     */
    public function getAvatarUrlAttribute(): string
    {
        if ($this->avatar) {
            return asset('storage/' . $this->avatar) . '?t=' . ($this->updated_at ? $this->updated_at->timestamp : time());
        }
        
        return 'https://ui-avatars.com/api/?name=' . urlencode($this->fullname ?: $this->username) . '&background=FF85B3&color=fff&bold=true';
    }

    /**
     * Get inisial untuk avatar
     */
    public function getInitialAttribute(): string
    {
        $name = $this->fullname ?: $this->username;
        $words = explode(' ', $name);
        $initial = '';
        
        foreach ($words as $word) {
            if (!empty($word)) {
                $initial .= strtoupper(substr($word, 0, 1));
            }
        }
        
        return substr($initial, 0, 2);
    }

    /**
     * Generate verification code
     */
    public function generateVerificationCode()
    {
        $this->verification_code = rand(100000, 999999);
        $this->verification_expiry = now()->addHours(24);
        $this->save();
        
        return $this->verification_code;
    }

    /**
     * Verify account with code
     */
    public function verifyWithCode($code)
    {
        if ($this->verification_code == $code && now()->lt($this->verification_expiry)) {
            $this->is_verified = true;
            $this->verification_code = null;
            $this->verification_expiry = null;
            $this->save();
            
            return true;
        }
        
        return false;
    }

    // ========== RELASI ==========
    
    /**
     * Relasi ke Provinsi
     */
    public function province()
    {
        return $this->belongsTo(Province::class, 'province_code', 'code');
    }

    /**
     * Relasi ke Kota/Kabupaten
     */
    public function city()
    {
        return $this->belongsTo(City::class, 'city_code', 'code');
    }

    /**
     * Relasi ke Kecamatan
     */
    public function district()
    {
        return $this->belongsTo(District::class, 'district_code', 'code');
    }

    /**
     * Relasi ke Kelurahan/Desa
     */
    public function village()
    {
        return $this->belongsTo(Village::class, 'village_code', 'code');
    }

    /**
     * Relasi ke Review (TAMBAHKAN INI)
     */
    public function reviews()
    {
        return $this->hasMany(Review::class, 'user_id', 'user_id');
    }

    /**
     * Relasi ke Penjualan
     */
    public function penjualan()
    {
        return $this->hasMany(Penjualan::class, 'user_id', 'user_id');
    }

    /**
     * Get alamat lengkap dengan format:
     * Alamat, Kelurahan, Kecamatan, Kota/Kabupaten, Provinsi - Kode Pos
     */
    public function getFullAddressAttribute(): string
    {
        $parts = [];
        
        if ($this->address) {
            $parts[] = $this->address;
        }
        
        if ($this->village) {
            $parts[] = $this->village->name;
        }
        
        if ($this->district) {
            $parts[] = $this->district->name;
        }
        
        if ($this->city) {
            $parts[] = $this->city->name;
        }
        
        if ($this->province) {
            $parts[] = $this->province->name;
        }
        
        if ($this->postal_code) {
            $parts[] = $this->postal_code;
        }
        
        return implode(', ', $parts);
    }

    /**
     * Get alamat singkat (tanpa provinsi)
     */
    public function getShortAddressAttribute(): string
    {
        $parts = [];
        
        if ($this->address) {
            $parts[] = $this->address;
        }
        
        if ($this->village) {
            $parts[] = $this->village->name;
        }
        
        if ($this->district) {
            $parts[] = $this->district->name;
        }
        
        if ($this->city) {
            $parts[] = $this->city->name;
        }
        
        return implode(', ', $parts);
    }

    /**
     * Get lokasi lengkap untuk peta/maps
     */
    public function getLocationAttribute(): array
    {
        return [
            'province' => $this->province->name ?? null,
            'city' => $this->city->name ?? null,
            'district' => $this->district->name ?? null,
            'village' => $this->village->name ?? null,
            'address' => $this->address,
            'postal_code' => $this->postal_code,
            'full_address' => $this->full_address
        ];
    }
}