<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class InductionDocument extends BaseModel
{
    use HasFactory;

    protected $table = 'induction_documents';

    protected $fillable = [
        'title',
        'document_type',
        'role_types',
        'trade_ids',
        'version',
        'file_path',
        'is_active',
        'update_type',
        'parent_document_id',
        'customer_id',
        'workspace_id',
        'created_by',
        'description',
        'del'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'is_valid' => 'boolean',
        'role_types' => 'array',
        'trade_ids' => 'array'
    ];

 

    /**
     * Get the parent document (previous version)
     */
    public function parentDocument()
    {
        return $this->belongsTo(InductionDocument::class, 'parent_document_id', 'id');
    }

    /**
     * Get all child documents (newer versions)
     */
    public function childDocuments()
    {
        return $this->hasMany(InductionDocument::class, 'parent_document_id', 'id');
    }

    /**
     * Get all signatures for this document version
     */
    public function signatures()
    {
        return $this->hasMany(InductionDocumentSignature::class, 'induction_document_id', 'id')
            ->where('document_version', $this->version)
            ->where('is_valid', true)
            ->where('del', 0);
    }

    /**
     * Get all signatures (including invalid ones for audit trail)
     */
    public function allSignatures()
    {
        return $this->hasMany(InductionDocumentSignature::class, 'induction_document_id', 'id')
            ->where('document_version', $this->version)
            ->where('del', 0);
    }

    /**
     * Get the user who created this document
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by', 'id');
    }

    /**
     * Get the trades associated with this document
     * Uses trade_ids JSON array to fetch related Trade models
     * Note: This is a custom relationship since we store IDs in JSON array, not a pivot table
     * 
     * Usage: $document->trades (accessor) or $document->getTrades() (method)
     */
    public function getTrades()
    {
        $tradeIds = $this->trade_ids ?? [];
        
        // Ensure trade_ids is an array
        if (!is_array($tradeIds)) {
            $tradeIds = json_decode($tradeIds, true) ?? [];
        }
        
        if (empty($tradeIds)) {
            return collect([]);
        }
        
        return Trade::whereIn('id', $tradeIds)
            ->where('del', '0')
            ->get();
    }

    /**
     * Accessor to get trades collection
     * This provides a convenient way to access trades as a collection
     */
    public function getTradesAttribute()
    {
        $tradeIds = $this->trade_ids ?? [];
        
        // Ensure trade_ids is an array
        if (!is_array($tradeIds)) {
            $tradeIds = json_decode($tradeIds, true) ?? [];
        }
        
        if (empty($tradeIds)) {
            return collect([]);
        }
        
        return Trade::whereIn('id', $tradeIds)
            ->where('del', '0')
            ->get();
    }



    /**
     * Scope to get only active versions
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true)->where('del', 0);
    }

  

    /**
     * Scope to get documents for customer/workspace
     */
    public function scopeForWorkspace($query, $customerId, $workspaceId = null)
    {
        $query->where('customer_id', $customerId);
        if ($workspaceId) {
            $query->where('workspace_id', $workspaceId);
        }
        return $query;
    }

    /**
     * Get pending signature count for this document version
     */
    public function getPendingSignatureCountAttribute()
    {
        // This would need to be calculated based on total employees/users who need to sign
        // vs those who have already signed this version
        // Implementation would depend on your employee/user structure
        return 0; // Placeholder
    }

    /**
     * Get signed count for this document version
     */
    public function getSignedCountAttribute()
    {
        return $this->signatures()->count();
    }

    /**
     * Get the latest version of a document by title
     */
    public static function getLatestVersion($title, $customerId, $workspaceId = null)
    {
        $query = static::where('title', $title)
            ->where('customer_id', $customerId)
            ->where('del', 0);
        
        if ($workspaceId) {
            $query->where('workspace_id', $workspaceId);
        }
        
        return $query->orderBy('version', 'desc')->first();
    }

    /**
     * Get all versions of a document
     */
    public static function getAllVersions($title, $customerId, $workspaceId = null)
    {
        $query = static::where('title', $title)
            ->where('customer_id', $customerId)
            ->where('del', 0);
        
        if ($workspaceId) {
            $query->where('workspace_id', $workspaceId);
        }
        
        return $query->orderBy('version', 'asc')->get();
    }

    /**
     * Get the minimum version that needs to be signed
     * This is the latest version for major updates, or the version where user hasn't signed yet for minor updates
     */
    public static function getMinimumRequiredVersion($title, $customerId, $workspaceId = null, $employeeId = null, $userId = null)
    {
        $latestDocument = static::getLatestVersion($title, $customerId, $workspaceId);
        
        if (!$latestDocument) {
            return null;
        }

        // For major updates, everyone must sign the latest version
        if ($latestDocument->update_type === 'major') {
            return $latestDocument->version;
        }

        // For minor updates, check if user has signed any version
        if ($employeeId || $userId) {
            $hasSigned = InductionDocumentSignature::where('induction_document_id', $latestDocument->id)
                ->where(function($query) use ($employeeId, $userId) {
                    if ($employeeId) {
                        $query->where('employee_id', $employeeId);
                    }
                    if ($userId) {
                        $query->orWhere('user_id', $userId);
                    }
                })
                ->where('is_valid', true)
                ->where('del', 0)
                ->exists();

            // If user has signed before, they don't need to sign again (minor update)
            // If not, they need to sign the latest version
            return $hasSigned ? null : $latestDocument->version;
        }

        // If no specific user, return latest version
        return $latestDocument->version;
    }
}

