<?php

namespace App\Models;

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

class User extends Authenticatable
{
    use HasFactory, Notifiable, SoftDeletes;

    protected $fillable = [
        'name', 'username', 'email', 'password',
        'role', 'is_active',
    ];

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

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

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

    public function cashSessions()
    {
        return $this->hasMany(CashSession::class);
    }

    public function stockMovements()
    {
        return $this->hasMany(StockMovement::class);
    }

    // Scope
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

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

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

    public function isKasir(): bool
    {
        return in_array($this->role, ['kasir', 'admin', 'manajer']);
    }

    public function isManajer(): bool
    {
        return in_array($this->role, ['manajer', 'admin']);
    }

    // Statistik kasir
    public function getTodaySales()
    {
        return $this->transactions()
            ->whereDate('transaction_date', today())
            ->where('status', 'completed')
            ->selectRaw('COUNT(*) as total_trx, SUM(grand_total) as total_sales')
            ->first();
    }

    public function getActiveSession()
    {
        return $this->cashSessions()->where('status', 'open')->latest()->first();
    }
}
