<?php

namespace App\Models;

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

class Swms extends BaseModel
{
    use HasFactory;
    protected $table = 'swms'; // Explicit table name

    protected $fillable = [
        'customer_id',
        'workspace_id',
        'swms_number',
        'title',
        'description',
        'revision_number',
        'version_number',
        'start_date',
        'company_name',
        'company_address',
        'contact_number',
        'scope_of_work',
        'site_manager_or_forman',
        'principal_contractor',
        'principal_contractor_address',
        'principal_contractor_number',
        'fast_address',
        'site_id',
        'parent_id',
        'del',
        'process',
        'published',
        'report_method',
        'workplace_location_address'
    ];


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

    ];

    public function toArray()
    {
        $array = parent::toArray();
        $systemDateFormat = $this->getSystemDateFormat();
        $systemTimeFormat = $this->getSystemTimeFormat();
        
        // Format start_date if it exists
        if (isset($array['start_date']) && $array['start_date']) {
            $rawTimestamp = $this->getRawOriginal('start_date');
            $carbonDate = \Carbon\Carbon::parse($rawTimestamp);
            $array['start_date'] = $carbonDate->format($systemDateFormat);
        }
        
        return $array;
    }

    public function getSystemDateFormat()
    {
        try {
            $user = auth()->user();
            if (!$user) { return 'Y-m-d'; }
            $customerId = $user->access_role ? $user->customer_id : $user->id;
            $workspaceId = $user->current_workspace_id ?? $user->workspace_id ?? null;
            $setting = \App\Models\Adminsettings::where('customer_id', $customerId)
                ->where('key', 'system_date_format')
                ->when($workspaceId, function ($query) use ($workspaceId) { return $query->where('workspace', $workspaceId); })
                ->first();
            if ($setting && $setting->value) {
                // Convert the setting value to Carbon format
                $format = $setting->value;
                $format = str_replace('dd', 'd', $format);
                $format = str_replace('mm', 'm', $format);
                $format = str_replace('yyyy', 'Y', $format);
                $format = str_replace('yy', 'y', $format);
                return $format;
            }
        } catch (\Exception $e) { /* Log error */ }
        return 'Y-m-d';
    }

    public function getSystemTimeFormat()
    {
        try {
            $user = auth()->user();
            if (!$user) { return 'H:i'; }
            $customerId = $user->access_role ? $user->customer_id : $user->id;
            $workspaceId = $user->current_workspace_id ?? $user->workspace_id ?? null;
            $setting = \App\Models\Adminsettings::where('customer_id', $customerId)
                ->where('key', 'system_time_format')
                ->when($workspaceId, function ($query) use ($workspaceId) { return $query->where('workspace', $workspaceId); })
                ->first();
            if ($setting && $setting->value) {
                $value = strtoupper($setting->value);
                if (str_contains($value, 'AM') || str_contains($value, 'PM') || str_contains($value, '12') || str_contains($value, 'HOUR')) {
                    return 'g:i A';
                }
            }
        } catch (\Exception $e) { /* Log error */ }
        return 'H:i';
    }

    public function parent()
    {
        return $this->belongsTo(Swms::class, 'parent_id');
    }
    public function authorizedBy()
    {
        return $this->belongsTo(EmpPersonalDetails::class, 'site_manager_or_forman', 'emp_id');
    }

    public function developedBies()
    {
        return $this->hasMany(SwmsDevelopedBy::class, 'swms_id');
    }

    public function approvedBies()
    {
        return $this->hasMany(SwmsApprovedBy::class, 'swms_id');
    }

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

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