<?php

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\SRO_VT_PROXY\_Players;
use App\Models\SRO_VT_SHARD\Char;

class SystemHealth extends Component
{
    public $isVisible = false;
    public $healthData = [];
    public $lastUpdate = null;

    public function mount()
    {
        // إخفاء المكون افتراضياً، يظهر فقط عند وجود مشاكل
        $this->checkSystemHealth();
    }

    public function checkSystemHealth()
    {
        try {
            $this->healthData = [
                'database_connections' => $this->checkDatabaseConnections(),
                'livewire_errors' => $this->checkLivewireErrors(),
                'session_health' => $this->checkSessionHealth(),
                'cache_health' => $this->checkCacheHealth(),
                'overall_status' => 'healthy'
            ];

            // تحديد الحالة العامة
            $hasIssues = false;
            foreach ($this->healthData as $key => $data) {
                if ($key !== 'overall_status' && isset($data['status']) && $data['status'] !== 'ok') {
                    $hasIssues = true;
                    break;
                }
            }

            $this->healthData['overall_status'] = $hasIssues ? 'issues_detected' : 'healthy';
            $this->isVisible = $hasIssues;
            $this->lastUpdate = now()->format('H:i:s');

        } catch (\Exception $e) {
            Log::error('System health check failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            $this->healthData = [
                'overall_status' => 'error',
                'error_message' => 'Failed to check system health'
            ];
            $this->isVisible = true;
        }
    }

    protected function checkDatabaseConnections()
    {
        $connections = [
            'shard' => 'sqlsrv_shard',
            'proxy' => 'sqlsrv_proxy',
            'default' => 'sqlsrv'
        ];

        $results = [];
        foreach ($connections as $name => $connection) {
            try {
                DB::connection($connection)->getPdo();
                $results[$name] = [
                    'status' => 'ok',
                    'message' => 'Connected'
                ];
            } catch (\Exception $e) {
                $results[$name] = [
                    'status' => 'error',
                    'message' => 'Connection failed: ' . $e->getMessage()
                ];
            }
        }

        return [
            'status' => collect($results)->contains('status', 'error') ? 'error' : 'ok',
            'connections' => $results
        ];
    }

    protected function checkLivewireErrors()
    {
        try {
            // فحص آخر 10 دقائق من logs
            $logPath = storage_path('logs/livewire.log');

            if (!file_exists($logPath)) {
                return [
                    'status' => 'ok',
                    'message' => 'No Livewire log file found'
                ];
            }

            $recentErrors = 0;
            $lines = file($logPath);
            $tenMinutesAgo = now()->subMinutes(10);

            foreach (array_reverse($lines) as $line) {
                if (strpos($line, 'ERROR') !== false) {
                    // محاولة استخراج التاريخ من السطر
                    preg_match('/\[(.*?)\]/', $line, $matches);
                    if (isset($matches[1])) {
                        try {
                            $logTime = \Carbon\Carbon::parse($matches[1]);
                            if ($logTime->greaterThan($tenMinutesAgo)) {
                                $recentErrors++;
                            }
                        } catch (\Exception $e) {
                            // تجاهل أخطاء تحليل التاريخ
                        }
                    }
                }
            }

            return [
                'status' => $recentErrors > 5 ? 'warning' : 'ok',
                'recent_errors' => $recentErrors,
                'message' => $recentErrors > 5 ? 'High error rate detected' : 'Normal error rate'
            ];

        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => 'Failed to check Livewire logs'
            ];
        }
    }

    protected function checkSessionHealth()
    {
        try {
            // فحص إعدادات الجلسة
            $sessionDriver = config('session.driver');
            $sessionLifetime = config('session.lifetime');

            return [
                'status' => 'ok',
                'driver' => $sessionDriver,
                'lifetime' => $sessionLifetime,
                'message' => "Driver: {$sessionDriver}, Lifetime: {$sessionLifetime} minutes"
            ];

        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => 'Session configuration error'
            ];
        }
    }

    protected function checkCacheHealth()
    {
        try {
            // اختبار Cache
            $testKey = 'health_check_' . time();
            $testValue = 'test_value';

            Cache::put($testKey, $testValue, 60);
            $retrievedValue = Cache::get($testKey);
            Cache::forget($testKey);

            $cacheWorking = $retrievedValue === $testValue;

            return [
                'status' => $cacheWorking ? 'ok' : 'error',
                'driver' => config('cache.default'),
                'message' => $cacheWorking ? 'Cache working properly' : 'Cache not working'
            ];

        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => 'Cache test failed'
            ];
        }
    }

    public function fixIssues()
    {
        try {
            // تشغيل أوامر الإصلاح
            $this->dispatch('show-notification', [
                'type' => 'info',
                'message' => 'جاري إصلاح المشاكل المكتشفة...',
                'duration' => 3000
            ]);

            // إعادة فحص النظام بعد محاولة الإصلاح
            $this->checkSystemHealth();

            $this->dispatch('show-notification', [
                'type' => 'success',
                'message' => 'تم إجراء فحص جديد للنظام',
                'duration' => 2000
            ]);

        } catch (\Exception $e) {
            $this->dispatch('show-notification', [
                'type' => 'error',
                'message' => 'فشل في إصلاح المشاكل: ' . $e->getMessage(),
                'duration' => 5000
            ]);
        }
    }

    public function hide()
    {
        $this->isVisible = false;
    }

    public function refresh()
    {
        $this->checkSystemHealth();
        $this->dispatch('show-notification', [
            'type' => 'info',
            'message' => 'تم تحديث حالة النظام',
            'duration' => 1500
        ]);
    }

    public function render()
    {
        return view('livewire.system-health');
    }
}
