<?php

namespace App\Models;

class WhsqReport extends BaseModel
{
    protected $table = 'whsq_reports';

    protected $fillable = [
        'created_by',
        'document_title',
        'authorised_by',
        'revision_number',
        'document_number',
        'revision_date',
        'next_revision_date',
        'site_id',
        'version',
        'customer_id',
        'workspace_id',
        'publish',
        'approval_status',
        'del',
        'parent_report_id',
        'is_completed',
        'report_method'
    ];

    protected $casts = [
        'parent_settings' => 'array',
        'child_settings' => 'array',
        'grandchild_settings' => 'array',
        'revision_date' => 'date',
        'next_revision_date' => 'date',
        'publish' => 'boolean'
    ];

    protected $hidden = [
        'customer_id',
        'workspace_id',
    ];

    public function tableOfContent()
    {
        return $this->belongsTo(WHSQE_TableOfContent::class, 'table_of_content_id');
    }

    public function generatedPdf()
    {
        return $this->hasOne(GeneratedPdfReport::class, 'report_id','id')
            ->where('report_type', 'whsqe_report');
    }

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

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

  
    public function authoriseBy()
    {
        return $this->belongsTo(EmpPersonalDetails::class, 'authorised_by' , 'emp_id')->select('emp_id','first_name','middle_name','last_name');
    }
 
    // Scope for published reports
    public function scopePublished($query)
    {
        return $query->where('publish', true);
    }

    // Scope for unpublished reports
    public function scopeUnpublished($query)
    {
        return $query->where('publish', false);
    }

   

    /**
     * Get the chain ID for this report
     */
    public function getChainId()
    {
        $chainEntry = $this->chainEntry;
        return $chainEntry ? $chainEntry->chain_id : null;
    }

    /**
     * Get the step number in the chain
     */
    public function getStepNumber()
    {
        $chainEntry = $this->chainEntry;
        return $chainEntry ? $chainEntry->step_number : null;
    }

    public function createNewVersion(): self
    {
        $newReport = $this->replicate();
        $newReport->version = $this->version + 0.1;
        $newReport->is_latest_version = true;
        $newReport->previous_version_id = $this->id;
        $newReport->status = 'draft';
        $newReport->save();

        // Update current report
        $this->update(['is_latest_version' => false]);

        // Copy sections and content
        $this->copySectionsToReport($newReport);

        return $newReport;
    }
}
