<?php

namespace App\Models;

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

class HelpdeskConversions extends BaseModel
{
    use HasFactory;

    protected $table = 'helpdesk_conversions';
    
    protected $fillable = [
        'ticket_id',
        'descriptions',
        'attachments',
        'sender'
    ];

    public function senderUser()
    {
        return $this->belongsTo(User::class, 'sender', 'id'); // sender is the foreign key in the conversations table
    }

    public function ticket()
    {
        return $this->belongsTo(HelpdeskTicket::class, 'ticket_id', 'id');
    }

    /**
     * Override toArray to ensure timestamps preserve exact time and format according to system settings
     */
    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);
        }
        
        return $array;
    }

    /**
     * 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
    }
}
