<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Console\Scheduling\Schedule;

class CronJobController extends Controller
{
    /**
     * Afișează pagina CronJobs
     */
    public function index()
    {
        // Obține toate comenzile scheduled
        $schedule = app(Schedule::class);
        $events = $schedule->events();

        $scheduledCommands = [];
        foreach ($events as $event) {
            $scheduledCommands[] = [
                'command' => $event->command ?? $event->description ?? 'Callback',
                'expression' => $event->expression,
                'description' => $event->description ?? '',
                'next_run' => $event->nextRunDate()->format('Y-m-d H:i:s'),
                'timezone' => $event->timezone ?? config('app.timezone'),
            ];
        }

        // Grupează comenzile pe categorii
        $categorizedCommands = $this->categorizeCommands($scheduledCommands);

        // Obține status queue
        $queueStatus = $this->getQueueStatus();

        // Obține ultimele execuții din log
        $recentExecutions = $this->getRecentExecutions();

        // Verifică dacă Windows Task Scheduler este configurat
        $taskSchedulerConfigured = $this->checkTaskScheduler();

        return view('admin.settings.cronjobs', compact(
            'categorizedCommands',
            'queueStatus',
            'recentExecutions',
            'taskSchedulerConfigured'
        ));
    }

    /**
     * Categorize commands by type
     */
    private function categorizeCommands($commands)
    {
        $categories = [
            'dns' => [
                'title' => '🌐 DNS & Nameservere',
                'commands' => []
            ],
            'backup' => [
                'title' => '💾 Backup & Maintenance',
                'commands' => []
            ],
            'other' => [
                'title' => '💰 Altele',
                'commands' => []
            ]
        ];

        foreach ($commands as $command) {
            $cmd = $command['command'];
            
            if (str_contains($cmd, 'dns:') || str_contains($cmd, 'nameservers:') || str_contains($cmd, 'zones:') || str_contains($cmd, 'dispatch-statistics')) {
                $categories['dns']['commands'][] = $command;
            } elseif (str_contains($cmd, 'backup:') || str_contains($cmd, 'cache:') || str_contains($cmd, 'queue:')) {
                $categories['backup']['commands'][] = $command;
            } else {
                $categories['other']['commands'][] = $command;
            }
        }

        return $categories;
    }

    /**
     * Get queue status
     */
    private function getQueueStatus()
    {
        try {
            $pending = DB::table('jobs')->where('queue', 'dns-statistics')->count();
            $failed = DB::table('failed_jobs')->count();
            
            return [
                'pending' => $pending,
                'failed' => $failed,
                'status' => $pending > 0 ? 'processing' : 'idle'
            ];
        } catch (\Exception $e) {
            return [
                'pending' => 0,
                'failed' => 0,
                'status' => 'unknown'
            ];
        }
    }

    /**
     * Get recent executions from log
     */
    private function getRecentExecutions()
    {
        $logFile = storage_path('logs/scheduler.log');
        $executions = [];

        if (file_exists($logFile)) {
            $lines = array_slice(file($logFile), -50);
            
            foreach ($lines as $line) {
                if (preg_match('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*Running.*\["artisan" ([^\]]+)\]/', $line, $matches)) {
                    $executions[] = [
                        'time' => $matches[1],
                        'command' => $matches[2],
                        'status' => 'running'
                    ];
                } elseif (preg_match('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*(\d+) sec\. (DONE|FAIL)/', $line, $matches)) {
                    if (!empty($executions)) {
                        $executions[count($executions) - 1]['status'] = strtolower($matches[3]);
                        $executions[count($executions) - 1]['duration'] = $matches[2];
                    }
                }
            }
        }

        return array_slice(array_reverse($executions), 0, 10);
    }

    /**
     * Check if Windows Task Scheduler is configured
     */
    private function checkTaskScheduler()
    {
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            // Verifică dacă task exists
            exec('schtasks /query /tn "Laravel Scheduler - PanelDNS" 2>&1', $output, $returnCode);
            return $returnCode === 0;
        }
        
        return false; // Not Windows or not configured
    }

    /**
     * Run scheduler manually
     */
    public function runScheduler(Request $request)
    {
        try {
            Artisan::call('schedule:run');
            $output = Artisan::output();

            Log::info('Scheduler rulat manual din admin panel');

            return response()->json([
                'success' => true,
                'message' => 'Scheduler executat cu succes!',
                'output' => $output
            ]);
        } catch (\Exception $e) {
            Log::error('Eroare la rularea manuală a scheduler-ului: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Eroare: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Restart queue workers
     */
    public function restartQueue(Request $request)
    {
        try {
            Artisan::call('queue:restart');

            Log::info('Queue workers restarted din admin panel');

            return response()->json([
                'success' => true,
                'message' => 'Queue workers vor fi restartați la următorul job!'
            ]);
        } catch (\Exception $e) {
            Log::error('Eroare la restart queue: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Eroare: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get queue status (AJAX)
     */
    public function getQueueStatusAjax(Request $request)
    {
        return response()->json([
            'success' => true,
            'data' => $this->getQueueStatus()
        ]);
    }

    /**
     * Get failed jobs
     */
    public function getFailedJobs(Request $request)
    {
        try {
            $failedJobs = DB::table('failed_jobs')
                ->orderBy('failed_at', 'desc')
                ->limit(20)
                ->get();

            return response()->json([
                'success' => true,
                'data' => $failedJobs
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Eroare: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Retry all failed jobs
     */
    public function retryFailedJobs(Request $request)
    {
        try {
            Artisan::call('queue:retry', ['id' => 'all']);

            Log::info('Toate joburile eșuate au fost repuse în queue din admin panel');

            return response()->json([
                'success' => true,
                'message' => 'Toate joburile eșuate au fost repuse în queue!'
            ]);
        } catch (\Exception $e) {
            Log::error('Eroare la retry failed jobs: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Eroare: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get scheduler log (tail)
     */
    public function getSchedulerLog(Request $request)
    {
        $logFile = storage_path('logs/scheduler.log');
        $lines = $request->get('lines', 50);

        if (file_exists($logFile)) {
            $content = array_slice(file($logFile), -$lines);
            
            return response()->json([
                'success' => true,
                'data' => implode('', $content)
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Log file not found'
        ], 404);
    }

    /**
     * Download setup script
     */
    public function downloadSetupScript(Request $request)
    {
        $scriptContent = '@echo off
REM Laravel Scheduler Setup Script
REM Generated: ' . now()->format('Y-m-d H:i:s') . '

echo ========================================
echo Laravel Scheduler - PanelDNS Setup
echo ========================================
echo.

REM Create scheduled task
schtasks /create /tn "Laravel Scheduler - PanelDNS" /tr "' . base_path('run-scheduler.bat') . '" /sc minute /mo 1 /ru SYSTEM /f

if %errorlevel% equ 0 (
    echo.
    echo ========================================
    echo ✅ Task Scheduler configurat cu succes!
    echo ========================================
    echo.
    echo Scheduler-ul va rula automat la fiecare minut.
) else (
    echo.
    echo ========================================
    echo ❌ Eroare la configurare!
    echo ========================================
    echo.
    echo Te rog rulează acest script ca Administrator.
)

pause
';

        return response($scriptContent)
            ->header('Content-Type', 'text/plain')
            ->header('Content-Disposition', 'attachment; filename="setup-scheduler.bat"');
    }

    /**
     * Salvează configurările CronJobs
     */
    public function saveSettings(Request $request)
    {
        $validated = $request->validate([
            // numeserver Check
            'cron_nameserver_check_enabled' => 'nullable|boolean',
            'cron_nameserver_check_interval' => 'required|integer|min:1|max:1440',
            
            // statistici Yesterday
            'cron_statistics_yesterday_enabled' => 'nullable|boolean',
            'cron_statistics_yesterday_interval' => 'required|integer|min:1|max:1440',
            'cron_statistics_yesterday_limit' => 'required|integer|min:1|max:1000',
            
            // statistici Today
            'cron_statistics_today_enabled' => 'nullable|boolean',
            'cron_statistics_today_interval' => 'required|integer|min:1|max:1440',
            'cron_statistics_today_limit' => 'required|integer|min:1|max:1000',
            
            // DNS Health Check & Alerts
            'cron_dns_health_check_enabled' => 'nullable|boolean',
            'cron_dns_health_check_interval' => 'required|integer|min:1|max:1440',
            'cron_dns_health_check_notify' => 'nullable|boolean',
        ]);

        // Salvează setările
        foreach ($validated as $key => $value) {
            $type = (str_ends_with($key, '_enabled') || str_ends_with($key, '_notify')) ? 'boolean' : 'integer';
            setting_set($key, $value, null, $type);
        }

        // Log modificarea
        Log::info('CronJob settings updated', [
            'user_id' => auth()->id(),
            'user_name' => auth()->user()->name,
            'settings' => $validated,
            'ip' => request()->ip(),
        ]);

        return redirect()
            ->route('admin.cronjobs.index')
            ->with('success', 'Configurările CronJobs au fost salvate cu succes!');
    }
}
