<?php

declare(strict_types=1);

namespace App\Livewire\Admin\Settings;

use App\Models\Setting;
use Illuminate\Support\Facades\Artisan;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.admin')]
final class Index extends Component
{
    public string $search = '';

    public string $groupFilter = '';

    public function updatingSearch(): void
    {
        $this->resetPage();
    }

    public function updatingGroupFilter(): void
    {
        $this->resetPage();
    }

    #[Computed]
    public function settings()
    {
        return Setting::query()
            ->when($this->search, fn ($q) => $q->where('key', 'like', "%{$this->search}%")
                ->orWhere('description', 'like', "%{$this->search}%"))
            ->when($this->groupFilter, fn ($q) => $q->where('group', $this->groupFilter))
            ->orderBy('group')
            ->orderBy('key')
            ->paginate(20);
    }

    #[Computed]
    public function groups()
    {
        return Setting::select('group')
            ->distinct()
            ->orderBy('group')
            ->pluck('group');
    }

    #[Computed]
    public function stats()
    {
        return [
            'total' => Setting::count(),
            'groups' => Setting::distinct('group')->count('group'),
            'types' => Setting::distinct('type')->count('type'),
        ];
    }

    public function clearCache(): void
    {
        try {
            Artisan::call('cache:clear');
            Artisan::call('config:clear');
            Artisan::call('route:clear');
            Artisan::call('view:clear');

            session()->flash('success', 'All caches cleared successfully!');
        } catch (\Exception $e) {
            session()->flash('error', 'Failed to clear cache: '.$e->getMessage());
        }
    }

    public function clearLogs(): void
    {
        try {
            // Clear Laravel logs (daily log files)
            $logFiles = [
                storage_path('logs/laravel-'.date('Y-m-d').'.log'),
                storage_path('logs/browser.log'),
            ];

            // Also check for any existing daily log files
            $logDirectory = storage_path('logs');
            $dailyLogFiles = glob($logDirectory.'/laravel-*.log');

            // Clear all daily log files
            foreach ($dailyLogFiles as $logFile) {
                if (file_exists($logFile)) {
                    file_put_contents($logFile, '');
                }
            }

            // Clear specific log files
            foreach ($logFiles as $logFile) {
                if (file_exists($logFile)) {
                    file_put_contents($logFile, '');
                }
            }

            session()->flash('success', 'All logs cleared successfully!');
        } catch (\Exception $e) {
            session()->flash('error', 'Failed to clear logs: '.$e->getMessage());
        }
    }

    public function createStorageLink(): void
    {
        try {
            Artisan::call('storage:link');
            session()->flash('success', 'Storage link created successfully!');
        } catch (\Exception $e) {
            session()->flash('error', 'Failed to create storage link: '.$e->getMessage());
        }
    }

    public function optimizeApplication(): void
    {
        try {
            Artisan::call('optimize:clear');
            session()->flash('success', 'Application optimized successfully!');
        } catch (\Exception $e) {
            session()->flash('error', 'Failed to clear caches: '.$e->getMessage());
        }
    }

    public function deleteSetting(Setting $setting): void
    {
        activity()
            ->causedBy(auth()->user())
            ->performedOn($setting)
            ->withProperties([
                'setting_key' => $setting->key,
                'setting_group' => $setting->group,
                'setting_value' => $setting->value,
            ])
            ->log('setting_deleted');

        $setting->delete();

        session()->flash('success', 'Setting deleted successfully!');
    }

    public function render()
    {
        return view('livewire.admin.settings.index');
    }
}
