<?php

namespace App\Http\Controllers\Admin\Settings;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;

class GeneralSettingsController extends BaseSettingsController
{
    public function index()
    {
        $allSettings = $this->getAllSettings();

        $lastSyncInfo = Cache::get('rankings_last_sync');
        $lastFactionSyncInfo = Cache::get('factions_last_sync');

        return Inertia::render('admin/settings/general/index', [
            'timezone' => $this->setting('server_timezone', 'Asia/Jakarta'),
            'timezones' => \DateTimeZone::listIdentifiers(),
            'appName' => config('app.name', 'Perfect World'),
            'logoUrl' => $this->getLogoUrl(),
            'availableFonts' => $this->getAvailableFonts(),
            'appFont' => $this->setting('app_font', 'The Golden Blade.woff2'),
            'appNameColor' => $this->setting('app_name_color', '#fbbf24'),
            'serverStartTime' => $this->setting('server_start_time'),
            'discordServerId' => $this->setting('discord_server_id', ''),
            'rankingsLastSync' => $lastSyncInfo,
            'factionsLastSync' => $lastFactionSyncInfo,
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'timezone' => 'required|timezone',
            'app_name' => 'required|string|max:255',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            'app_font' => 'nullable|string|max:255',
            'app_name_color' => 'nullable|string|regex:/^#[0-9A-Fa-f]{6}$/',
            'server_start_time' => 'nullable|date',
            'discord_server_id' => 'nullable|string|max:50',
        ]);

        $this->setSetting('server_timezone', $request->timezone);
        $this->updateEnv(['APP_NAME' => $request->app_name]);

        $fontValue = $request->input('app_font') ?: 'The Golden Blade.woff2';
        $this->setSetting('app_font', $fontValue);
        $this->setSetting('app_name_color', $request->input('app_name_color') ?: '#fbbf24');
        $this->setSetting('discord_server_id', $request->input('discord_server_id') ?: '');

        if ($request->has('server_start_time') && $request->input('server_start_time')) {
            $this->setSetting('server_start_time', $request->input('server_start_time'));
        }

        $this->handleLogoUpload($request);
        $this->refreshSettingsCache();

        return back()->with('success', 'General settings updated successfully.');
    }

    public function syncRankings(Request $request)
    {
        try {
            $exitCode = Artisan::call('rankings:sync');

            $output = Artisan::output();

            if ($exitCode === 0) {
                Cache::put('rankings_last_sync', [
                    'time' => now()->format('Y-m-d H:i:s'),
                    'status' => 'success',
                ], now()->addHours(24));

                return back()->with('success', 'Player rankings sync completed successfully.');
            } else {
                return back()->with('error', 'Sync failed. Check logs for details.');
            }
        } catch (\Exception $e) {
            return back()->with('error', 'Sync failed: '.$e->getMessage());
        }
    }

    public function syncFactions(Request $request)
    {
        try {
            $exitCode = Artisan::call('factions:sync', [
                '--limit' => 0,
                '--start-id' => 1,
                '--batch' => 50,
                '--delay' => 50,
            ]);

            $output = Artisan::output();

            if ($exitCode === 0) {
                Cache::put('factions_last_sync', [
                    'time' => now()->format('Y-m-d H:i:s'),
                    'status' => 'success',
                ], now()->addHours(24));

                return back()->with('success', 'Faction rankings sync completed successfully.');
            } else {
                return back()->with('error', 'Sync failed. Check logs for details.');
            }
        } catch (\Exception $e) {
            return back()->with('error', 'Sync failed: '.$e->getMessage());
        }
    }

    private function getLogoUrl(): ?string
    {
        $logoPath = $this->setting('app_logo');
        return $logoPath ? asset($logoPath) : null;
    }
}
