<?php

namespace App\Models;

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

class HelpdeskTicket extends BaseModel
{
    use HasFactory;
    protected $fillable = [
        'email',
        'user_id',
        'ticket_id',
        'category',     
        'subject',         
        'description',     
        'status',
        'attachments',
        'name',     
        'note',     
        'workspace',     
        'created_by',     


    ];
  
    public function conversations()
    {
        return $this->hasMany(HelpdeskConversions::class ,'ticket_id');
    }

    public function category()
    {
        return $this->belongsTo(HelpdeskTicketCategories::class ,'category');
    }
    public function assigne_by()
    {
        return $this->belongsTo(User::class ,'user_id');
    }
    public function created_by()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function createdByEmployee()
    {
        return $this->belongsTo(EmpPersonalDetails::class, 'created_by' , 'emp_id')->select('emp_id', 'first_name', 'middle_name', 'last_name');
    }


    /**
     * Override toArray to ensure timestamps preserve exact time and format according to system settings
     * and consolidate created_by relations into a single key
     */
    public function toArray()
    {
        $array = parent::toArray();
        
        // Get system date and time format settings
        $systemDateFormat = $this->getSystemDateFormat();
        $systemTimeFormat = $this->getSystemTimeFormat();
        
        // Ensure created_at and updated_at preserve the exact time from database and format according to system settings
        if (isset($array['created_at']) && $array['created_at']) {
            $rawTimestamp = $this->getRawOriginal('created_at');
            $carbonDate = \Carbon\Carbon::parse($rawTimestamp);
            $array['created_at'] = $carbonDate->format($systemDateFormat . ' ' . $systemTimeFormat);
        }
        
        if (isset($array['updated_at']) && $array['updated_at']) {
            $rawTimestamp = $this->getRawOriginal('updated_at');
            $carbonDate = \Carbon\Carbon::parse($rawTimestamp);
            $array['updated_at'] = $carbonDate->format($systemDateFormat . ' ' . $systemTimeFormat);
        }
        
        // Consolidate created_by relations into a single key
        $this->consolidateCreatedByData($array);
        
        return $array;
    }

    /**
     * Consolidate created_by and createdByEmployee relations into a single created_by key
     */
    private function consolidateCreatedByData(&$array)
    {
        $createdByData = null;
        
        // Check if we have createdByEmployee data (employee)
        if (isset($array['created_by_employee']) && $array['created_by_employee']) {
            $employee = $array['created_by_employee'];
            $firstName = $employee['first_name'] ?? '';
            $middleName = $employee['middle_name'] ?? '';
            $lastName = $employee['last_name'] ?? '';
            
            // Build full name, handling empty middle names
            $fullName = trim($firstName . ' ' . $middleName . ' ' . $lastName);
            
            $createdByData = [
                'id' => $employee['emp_id'] ?? null,
                'name' => $fullName
            ];
        }
        // Check if we have created_by data (user)
        elseif (isset($array['created_by']) && $array['created_by']) {
            $user = $array['created_by'];
            $createdByData = [
                'id' => $user['id'] ?? null,
                'name' => $user['name'] ?? null
            ];
        }
        
        // Set the consolidated created_by data
        if ($createdByData) {
            $array['created_by'] = $createdByData;
        }
        
        // Remove the separate createdByEmployee key if it exists
        unset($array['created_by_employee']);
    }

    /**
     * Get system date format from settings
     */
    private function getSystemDateFormat()
    {
        try {
            $user = auth()->user();
            if (!$user) {
                return 'd-m-Y'; // Default format if no user
            }

            // Determine customer_id and workspace_id based on user type
            $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 system format to Carbon format
                $formatMap = [
                    'mm-dd-yyyy' => 'm-d-Y',
                    'dd-mm-yyyy' => 'd-m-Y',
                    'yyyy-mm-dd' => 'Y-m-d',
                    'mm/dd/yyyy' => 'm/d/Y',
                    'dd/mm/yyyy' => 'd/m/Y',
                    'yyyy/mm/dd' => 'Y/m/d',
                ];
                return $formatMap[strtolower($setting->value)] ?? 'd-m-Y';
            }
        } catch (\Exception $e) {
            // Log error but continue with default
        }
        return 'd-m-Y'; // Default format
    }

    /**
     * Get system time format from settings
     */
    private function getSystemTimeFormat()
    {
        try {
            $user = auth()->user();
            if (!$user) {
                return 'H:i'; // Default 24-hour format if no user
            }

            // Determine customer_id and workspace_id based on user type
            $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) {
                // Check if the format contains AM/PM or if user prefers 12-hour format
                $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'; // 12-hour format with AM/PM
                }
            }
        } catch (\Exception $e) {
            // Log error but continue with default
        }
        return 'H:i'; // Default 24-hour format
    }
}
