<?php

namespace App\Models;

use App\Services\S3PresignedService;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use NotificationChannels\WebPush\HasPushSubscriptions;
use Spatie\Image\Enums\Fit;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\Permission\Traits\HasRoles;

#[Appends(['avatar', 'full_name', 'name'])]
#[Guarded(['id'])]
class User extends Authenticatable implements HasMedia
{
    use HasFactory, HasPushSubscriptions, HasRoles, InteractsWithMedia, Notifiable, SoftDeletes, TwoFactorAuthenticatable;

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'is_active' => 'boolean',
            'last_login_at' => 'datetime',
            'password' => 'hashed',
            'two_factor_confirmed_at' => 'datetime',
        ];
    }

    protected function email(): Attribute
    {
        return Attribute::make(
            set: fn (string $value) => strtolower($value),
        );
    }

    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->userProfile?->full_name ?? '',
        );
    }

    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->userProfile?->full_name ?: $this->username,
        );
    }

    protected function avatar(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->getFirstMedia('photos')
                ? app(S3PresignedService::class)->getTemporaryUrl($this->getFirstMedia('photos')->getPath())
                : null,
        );
    }

    #[Scope]
    protected function active(Builder $query): void
    {
        $query->where('is_active', true);
    }

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

    public function cashAccounts(): HasMany
    {
        return $this->hasMany(CashAccount::class, 'created_by_id');
    }

    public function cashTransactions(): HasMany
    {
        return $this->hasMany(CashTransaction::class, 'created_by_id');
    }

    public function createdCuttings(): HasMany
    {
        return $this->hasMany(Cutting::class, 'created_by_id');
    }

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

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

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

    public function createdExpenses(): HasMany
    {
        return $this->hasMany(Expense::class, 'created_by_id');
    }

    public function createdOrders(): HasMany
    {
        return $this->hasMany(Order::class, 'created_by_id');
    }

    public function createdPayrollAdjustments(): HasMany
    {
        return $this->hasMany(PayrollAdjustment::class, 'created_by_id');
    }

    public function createdPurchases(): HasMany
    {
        return $this->hasMany(Purchase::class, 'created_by_id');
    }

    public function createdRestocks(): HasMany
    {
        return $this->hasMany(Restock::class, 'created_by_id');
    }

    public function employee(): HasOne
    {
        return $this->hasOne(Employee::class);
    }

    public function employeeAdvancesPaid(): HasMany
    {
        return $this->hasMany(EmployeeAdvance::class, 'paid_by_id');
    }

    public function employeeAdvancesVerified(): HasMany
    {
        return $this->hasMany(EmployeeAdvance::class, 'verified_by_id');
    }

    public function leaveRequestsVerified(): HasMany
    {
        return $this->hasMany(LeaveRequest::class, 'verified_by_id');
    }

    public function marketingOrders(): HasMany
    {
        return $this->hasMany(Order::class, 'marketing_id');
    }

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

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

    public function paidPayrolls(): HasMany
    {
        return $this->hasMany(Payroll::class, 'paid_by_id');
    }

    public function payrollPeriodsClosed(): HasMany
    {
        return $this->hasMany(PayrollPeriod::class, 'closed_by_id');
    }

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

    public function rejections(): HasMany
    {
        return $this->hasMany(Rejection::class, 'rejected_by_id');
    }

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

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

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

    public function stokOpnamesCreated(): HasMany
    {
        return $this->hasMany(StokOpname::class, 'created_by_id');
    }

    public function stokOpnamesVerified(): HasMany
    {
        return $this->hasMany(StokOpname::class, 'verified_by_id');
    }

    public function userProfile(): HasOne
    {
        return $this->hasOne(UserProfile::class);
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('photos');
    }

    public function registerMediaConversions(?Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->fit(Fit::Contain, 150, 150);
    }
}
