<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class ApplicationRequirement extends Model
{
    use HasFactory;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'applicationrequirements';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'documentname',
        'companyid',
        'description',
        'status',
        'createdby'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'companyid' => 'integer',
        'createdat' => 'datetime',
        'updatedat' => 'datetime',
    ];

    /**
     * Indicates if the model should be timestamped.
     * Since your table has custom timestamp names, set this to false.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * Bootstrap the model and its traits.
     */
    protected static function boot()
    {
        parent::boot();
        
        /**
         * Automatically set companyid, createdby, and timestamps when creating a new record.
         */
        static::creating(function ($model) {
            $user = Auth::user();
            
            if ($user) {
                // Try to get company ID from user's employee record
                $companyId = self::getUserCompanyId($user);
                
                if ($companyId) {
                    $model->companyid = $companyId;
                } else {
                    // If no company ID found, you might want to throw an exception or handle it
                    throw new \Exception('User is not associated with any company.');
                }
                
                // Set createdby if not already provided
                if (empty($model->createdby)) {
                    $model->createdby = $user->name ?? $user->email ?? 'System';
                }
            } else {
                throw new \Exception('No authenticated user found.');
            }
            
            // Ensure timestamps are set
            if (empty($model->createdat)) {
                $model->createdat = now();
            }
            if (empty($model->updatedat)) {
                $model->updatedat = now();
            }
        });
        
        /**
         * Automatically update updatedat when updating a record.
         */
        static::updating(function ($model) {
            $model->updatedat = now();
        });
    }

    /**
     * Get the company that owns the application requirement.
     */
    public function company()
    {
        return $this->belongsTo(Company::class, 'companyid', 'id');
    }

    /**
     * Helper method to get company ID from authenticated user.
     * This assumes the authenticated user has an employee record.
     */
    protected static function getUserCompanyId($user)
    {
        // Method 1: If user has direct company_id attribute
        if (isset($user->company_id) && !empty($user->company_id)) {
            return $user->company_id;
        }
        
        // Method 2: If user has employee relationship
        if (method_exists($user, 'employee') && $user->employee) {
            return $user->employee->company_id;
        }
        
        // Method 3: Query Employee model directly
        $employee = Employee::where('email', $user->email)->first();
        if ($employee) {
            return $employee->company_id;
        }
        
        // Method 4: Check if user has any other relationship to company
        if (method_exists($user, 'companies') && $user->companies()->exists()) {
            return $user->companies()->first()->id;
        }
        
        return null;
    }

    /**
     * Scope a query to only include requirements for the authenticated user's company.
     * No parameter needed - automatically uses auth()->user()->company_id
     */
    public function scopeForCompany($query)
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return $query->where('companyid', $companyId);
        }
        return $query;
    }

    /**
     * Scope a query to only include active requirements.
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope a query to only include inactive requirements.
     */
    public function scopeInactive($query)
    {
        return $query->where('status', 'inactive');
    }

    /**
     * Get the status badge color.
     */
    public function getStatusBadgeAttribute()
    {
        return $this->status == 'active' 
            ? '<span class="badge bg-success">Active</span>'
            : '<span class="badge bg-danger">Inactive</span>';
    }

    /**
     * Get the created at date formatted.
     */
    public function getCreatedAtFormattedAttribute()
    {
        return $this->createdat ? $this->createdat->format('M d, Y H:i') : 'N/A';
    }

    /**
     * Get the updated at date formatted.
     */
    public function getUpdatedAtFormattedAttribute()
    {
        return $this->updatedat ? $this->updatedat->format('M d, Y H:i') : 'N/A';
    }

    /**
     * Check if the requirement is active.
     */
    public function isActive()
    {
        return $this->status == 'active';
    }

    /**
     * Check if the requirement is inactive.
     */
    public function isInactive()
    {
        return $this->status == 'inactive';
    }

    /**
     * Activate the requirement.
     */
    public function activate()
    {
        $this->update(['status' => 'active']);
    }

    /**
     * Deactivate the requirement.
     */
    public function deactivate()
    {
        $this->update(['status' => 'inactive']);
    }

    /**
     * Get requirements count for current user's company.
     */
    public static function getCountForCurrentCompany()
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)->count();
        }
        return 0;
    }

    /**
     * Get active requirements count for current user's company.
     */
    public static function getActiveCountForCurrentCompany()
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)
                       ->where('status', 'active')
                       ->count();
        }
        return 0;
    }

    /**
     * Get inactive requirements count for current user's company.
     */
    public static function getInactiveCountForCurrentCompany()
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)
                       ->where('status', 'inactive')
                       ->count();
        }
        return 0;
    }

    /**
     * Get the latest requirements for the current user's company.
     */
    public static function getLatestForCurrentCompany($limit = 5)
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)
                       ->orderBy('createdat', 'desc')
                       ->limit($limit)
                       ->get();
        }
        return collect();
    }

    /**
     * Get requirements grouped by status for the current user's company.
     */
    public static function getGroupedByStatusForCurrentCompany()
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)
                       ->selectRaw('status, count(*) as count')
                       ->groupBy('status')
                       ->pluck('count', 'status')
                       ->toArray();
        }
        return [];
    }

    /**
     * Search requirements for the current user's company.
     */
    public static function searchForCurrentCompany($searchTerm)
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)
                       ->where(function($query) use ($searchTerm) {
                           $query->where('documentname', 'like', "%{$searchTerm}%")
                                 ->orWhere('description', 'like', "%{$searchTerm}%");
                       })
                       ->orderBy('createdat', 'desc')
                       ->get();
        }
        return collect();
    }

    /**
     * Get requirements by status for the current user's company.
     */
    public static function getByStatusForCurrentCompany($status)
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)
                       ->where('status', $status)
                       ->orderBy('createdat', 'desc')
                       ->get();
        }
        return collect();
    }

    /**
     * Check if a document name already exists for the current user's company.
     */
    public static function documentNameExists($documentName)
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)
                       ->where('documentname', $documentName)
                       ->exists();
        }
        return false;
    }

    /**
     * Get document name suggestions for the current user's company.
     */
    public static function getDocumentNameSuggestions($searchTerm)
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            return self::where('companyid', $companyId)
                       ->where('documentname', 'like', "%{$searchTerm}%")
                       ->pluck('documentname')
                       ->unique()
                       ->values()
                       ->toArray();
        }
        return [];
    }

    /**
     * Get statistics for the current user's company.
     */
    public static function getStatisticsForCurrentCompany()
    {
        $user = Auth::user();
        $companyId = self::getUserCompanyId($user);
        
        if ($companyId) {
            $total = self::where('companyid', $companyId)->count();
            $active = self::where('companyid', $companyId)
                          ->where('status', 'active')
                          ->count();
            $inactive = self::where('companyid', $companyId)
                            ->where('status', 'inactive')
                            ->count();
            
            return [
                'total' => $total,
                'active' => $active,
                'inactive' => $inactive,
                'active_percentage' => $total > 0 ? round(($active / $total) * 100, 2) : 0,
                'inactive_percentage' => $total > 0 ? round(($inactive / $total) * 100, 2) : 0,
            ];
        }
        return [
            'total' => 0,
            'active' => 0,
            'inactive' => 0,
            'active_percentage' => 0,
            'inactive_percentage' => 0,
        ];
    }

    /**
     * Create a new requirement for the current user's company.
     * Helper method to ensure companyid and createdby are always set.
     */
    public static function createForCurrentUser(array $attributes = [])
    {
        $user = Auth::user();
        
        if (!$user) {
            throw new \Exception('No authenticated user found.');
        }
        
        $companyId = self::getUserCompanyId($user);
        
        if (!$companyId) {
            throw new \Exception('User is not associated with any company.');
        }
        
        $attributes['companyid'] = $companyId;
        $attributes['createdby'] = $user->name ?? $user->email ?? 'System';
        
        return self::create($attributes);
    }
    
    // In App\Models\ApplicationRequirement.php, add these methods:

/**
 * Get the loan types that require this document.
 */
public function loanTypes()
{
    return $this->belongsToMany(
        LoanType::class,
        'product_requirements',
        'requirement_id',
        'product_id'
    )->withPivot('is_mandatory');
}

/**
 * Get the count of products that require this document.
 */
public function getProductCountAttribute()
{
    return $this->loanTypes()->count();
}

/**
 * Check if this requirement is assigned to a specific product.
 */
public function isAssignedToProduct($productId)
{
    return $this->loanTypes()->where('product_id', $productId)->exists();
}
}