<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Facades\Storage;

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

    protected $fillable = [
        'name',
        'email',
        'password',
        'phone',
        'profile_image',
        'status',
        'last_login_at',
        'last_login_ip',
        'settings',
        'department',
        'position',
        'address',
        'date_of_birth',
        'gender',
        'employee_id',
        'hire_date',
        'notes',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'last_login_at' => 'datetime',
        'date_of_birth' => 'date',
        'hire_date' => 'date',
        'settings' => 'array',
        'status' => 'boolean',
    ];

    protected $appends = [
        'profile_image_url',
        'role_names',
        'is_active',
    ];

    /**
     * Get profile image URL
     */
    public function getProfileImageUrlAttribute()
    {
        if ($this->profile_image) {
            return Storage::url('profile-images/' . $this->profile_image);
        }
        return asset('assets/images/default-avatar.png');
    }

    /**
     * Get role names
     */
    public function getRoleNamesAttribute()
    {
        return $this->roles->pluck('name')->toArray();
    }

    /**
     * Get is active status
     */
    public function getIsActiveAttribute()
    {
        return $this->status ?? true;
    }

    /**
     * Activities performed by user
     */
    public function activities(): MorphMany
    {
        return $this->morphMany(ActivityLog::class, 'causer');
    }

    /**
     * Sales created by user - Check if your sales table has user_id or created_by
     * Adjust the foreign key based on your actual database schema
     */
    public function sales(): HasMany
    {
        // Try different column names that might exist in your sales table
        if (\Schema::hasColumn('sales', 'user_id')) {
            return $this->hasMany(Sale::class, 'user_id');
        } elseif (\Schema::hasColumn('sales', 'created_by')) {
            return $this->hasMany(Sale::class, 'created_by');
        } else {
            // If no user relation exists, return empty relationship
            return $this->hasMany(Sale::class, 'id', 'id')->whereRaw('1=0');
        }
    }

    /**
     * Purchases created by user - Check if your purchases table has user_id or created_by
     */
    public function purchases(): HasMany
    {
        // Try different column names
        if (\Schema::hasColumn('purchases', 'user_id')) {
            return $this->hasMany(Purchase::class, 'user_id');
        } elseif (\Schema::hasColumn('purchases', 'created_by')) {
            return $this->hasMany(Purchase::class, 'created_by');
        } else {
            // If no user relation exists, return empty relationship
            return $this->hasMany(Purchase::class, 'id', 'id')->whereRaw('1=0');
        }
    }

    /**
     * Notifications for user
     */
    public function notifications(): HasMany
    {
        return $this->hasMany(Notification::class);
    }

    /**
     * Audit logs for user
     */
    public function auditLogs(): HasMany
    {
        return $this->hasMany(AuditLog::class, 'user_id');
    }

    /**
     * Login history
     */
    public function loginHistory(): HasMany
    {
        return $this->hasMany(LoginHistory::class);
    }

    /**
     * Check if user is active
     */
    public function isActive(): bool
    {
        return $this->status ?? true;
    }

    /**
     * Check if user has any sales
     */
    public function hasSales(): bool
    {
        // Check if the relationship exists before trying to count
        try {
            return $this->sales()->exists();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Check if user has any purchases
     */
    public function hasPurchases(): bool
    {
        // Check if the relationship exists before trying to count
        try {
            return $this->purchases()->exists();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Get user's full statistics - with error handling
     */
    public function getStatistics(): array
    {
        $stats = [
            'total_sales' => 0,
            'total_purchases' => 0,
            'total_sales_amount' => 0,
            'total_purchases_amount' => 0,
            'last_login' => $this->last_login_at ? $this->last_login_at->diffForHumans() : 'Never',
            'login_count' => $this->loginHistory()->count(),
        ];

        try {
            // Safely get sales count
            if (\Schema::hasTable('sales')) {
                $stats['total_sales'] = $this->sales()->count();
                
                // Try to get sales amount if amount column exists
                if (\Schema::hasColumn('sales', 'total_amount')) {
                    $stats['total_sales_amount'] = $this->sales()->sum('total_amount');
                } elseif (\Schema::hasColumn('sales', 'amount')) {
                    $stats['total_sales_amount'] = $this->sales()->sum('amount');
                }
            }
        } catch (\Exception $e) {
            // Silently fail if sales table doesn't exist or has issues
        }

        try {
            // Safely get purchases count
            if (\Schema::hasTable('purchases')) {
                $stats['total_purchases'] = $this->purchases()->count();
                
                // Try to get purchases amount if amount column exists
                if (\Schema::hasColumn('purchases', 'total_amount')) {
                    $stats['total_purchases_amount'] = $this->purchases()->sum('total_amount');
                } elseif (\Schema::hasColumn('purchases', 'amount')) {
                    $stats['total_purchases_amount'] = $this->purchases()->sum('amount');
                }
            }
        } catch (\Exception $e) {
            // Silently fail if purchases table doesn't exist or has issues
        }

        return $stats;
    }

    /**
     * Scope active users
     */
    public function scopeActive($query)
    {
        return $query->where('status', true);
    }

    /**
     * Scope inactive users
     */
    public function scopeInactive($query)
    {
        return $query->where('status', false);
    }

    /**
     * Scope by role
     */
    public function scopeByRole($query, $role)
    {
        return $query->whereHas('roles', function ($q) use ($role) {
            $q->where('name', $role);
        });
    }

    /**
     * Get sales count safely for profile view
     */
    public function getSalesCountAttribute(): int
    {
        try {
            return $this->sales()->count();
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Get purchases count safely for profile view
     */
    public function getPurchasesCountAttribute(): int
    {
        try {
            return $this->purchases()->count();
        } catch (\Exception $e) {
            return 0;
        }
    }
}