<?php

namespace App\Models;

use App\Models\SystemSetting;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'phone_number',
        'password',
        'pin_hash',
        'role',
        'is_verified',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_verified' => 'boolean',
        ];
    }

    public function tickets()
    {
        return $this->hasMany(Ticket::class);
    }

    public function assignedTickets()
    {
        return $this->hasMany(Ticket::class, 'assigned_to');
    }

    public function ticketReplies()
    {
        return $this->hasMany(TicketReply::class);
    }

    public function news()
    {
        return $this->hasMany(News::class);
    }

    public function transactions(): HasMany
    {
        return $this->hasMany(Transaction::class);
    }

    public function bankAccounts(): HasMany
    {
        return $this->hasMany(BankAccount::class);
    }

    /**
     * System messages that this user can view
     */
    public function systemMessages()
    {
        return $this->belongsToMany(SystemMessage::class, 'system_message_users');
    }

    public function getBalanceAttribute(): float
    {
        $balance = $this->transactions()
            ->selectRaw("
            COALESCE(SUM(CASE
                WHEN type IN ('Tambah Baki', 'Penambahan System') AND status = 'completed' THEN amount
                WHEN type IN ('Pengeluaran', 'Pengurangan System') AND status <> 'failed' THEN amount
                ELSE 0 END), 0) AS balance
        ")
            ->value('balance');

        return (float) $balance;
    }

    public function getFormattedBalanceAttribute(): string
    {
        return 'RM ' . number_format($this->balance, 2);
    }

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

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

    public function hasRole(string $role): bool
    {
        return $this->role === $role;
    }

    /**
     * Boot method to handle model events
     */
    protected static function boot()
    {
        parent::boot();

        // When a new user is created, automatically add their initial balance
        static::created(function ($user) {
            if ($user->role === 'user') {
                $initialBalance = SystemSetting::getNewUserBalance();

                if ($initialBalance > 0) {
                    // Create a system transaction for the new user
                    $user->transactions()->create([
                        'type' => 'Penambahan System',
                        'amount' => $initialBalance,
                        'status' => 'completed',
                        'reference' => Str::ulid(),
                        'recipient' => $user->name,
                        'evidence' => null,
                        'notes' => 'Initial balance for new user registration',
                        'bank_account_id' => null,
                    ]);
                }
            }
        });
    }
}
