<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SiteDocument extends BaseModel
{
    use HasFactory;

    protected $table = 'site_documents';

    protected $fillable = [
        'site_id',
        'title',
        'document_type',
        'file',
        'uploaded_by',
        'uploaded_by_type',
        'role_ids',
        'subcontractors',
        'sign_requires',
        'signature_timing'
    ];

    protected $casts = [
        'role_ids' => 'array',
        'subcontractors' => 'array'
    ];

    public function site()
    {
        return $this->belongsTo(Sites::class, 'site_id');
    }

    public function uploadedBy()
    {
        // This will need to handle both User and EmpPersonalDetails
        // For now, we'll check if uploaded_by exists in users table or emp_personal_details
        return $this->belongsTo(User::class, 'uploaded_by');
    }

    public function documentType()
    {
        return $this->belongsTo(DocumentType::class, 'document_type', 'id');
    }

    public function subcontractor()
    {
        return $this->belongsTo(LinkManagement::class, 'subcontractors', 'id');
    }

    public function roles()
    {
        // Get roles from role_ids JSON array
        if ($this->role_ids && is_array($this->role_ids)) {
            return Role::whereIn('id', $this->role_ids)->get();
        }
        return collect([]);
    }

    public function signatures()
    {
        return $this->hasMany(SiteDocumentSignature::class, 'site_document_id');
    }

    public function isSignedByEmployee($employeeId, $siteId = null)
    {
        $query = SiteDocumentSignature::where('site_document_id', $this->id)
            ->where('employee_id', $employeeId);
        
        if ($siteId) {
            $query->where('site_id', $siteId);
        }
        
        return $query->exists();
    }
}

