<?php

namespace App\Livewire\Admin\Maintenance;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.admin')]
#[Title('Maintenance')]
class Index extends Component
{
    // ── Modal konfirmasi ─────────────────────────────────────────────────
    public bool $showConfirmModal = false;
    public string $pendingAction  = ''; // cache | view | config | route

    private const ACTION_LABELS = [
        'cache'  => 'Clear Cache',
        'view'   => 'Clear View',
        'config' => 'Clear Config',
        'route'  => 'Clear Route',
    ];

    public function confirmAction(string $action): void
    {
        abort_unless(auth()->user()->can('setting.manage'), 403);

        if (! array_key_exists($action, self::ACTION_LABELS)) {
            return;
        }

        $this->pendingAction    = $action;
        $this->showConfirmModal = true;
    }

    public function executeAction(): void
    {
        abort_unless(auth()->user()->can('setting.manage'), 403);

        $label = self::ACTION_LABELS[$this->pendingAction] ?? null;

        if (! $label) {
            $this->showConfirmModal = false;
            return;
        }

        try {
            match ($this->pendingAction) {
                'cache'  => Artisan::call('cache:clear'),
                'view'   => Artisan::call('view:clear'),
                'config' => Artisan::call('config:clear'),
                'route'  => Artisan::call('route:clear'),
                default  => null,
            };

            $this->dispatch('notify', type: 'success', message: "{$label} berhasil dijalankan.");
        } catch (\Throwable $e) {
            $this->dispatch('notify', type: 'error', message: "{$label} gagal: " . $e->getMessage());
        }

        $this->showConfirmModal = false;
        $this->pendingAction    = '';
    }

    /**
     * Info sistem untuk ditampilkan — semua read-only, tidak ada yang
     * mengekspos kredensial (password DB, dsb tidak pernah disentuh).
     */
    private function getSystemInfo(): array
    {
        // Database: hanya nama driver & status koneksi, TIDAK ada kredensial.
        $dbStatus = 'Terputus';
        try {
            DB::connection()->getPdo();
            $dbStatus = 'Terhubung';
        } catch (\Throwable $e) {
            $dbStatus = 'Terputus';
        }

        $storageWritable = is_writable(storage_path());

        $cacheStatus = 'Tidak diketahui';
        try {
            Cache::put('maintenance_check', true, 5);
            $cacheStatus = Cache::get('maintenance_check') === true ? 'Aktif' : 'Bermasalah';
        } catch (\Throwable $e) {
            $cacheStatus = 'Bermasalah';
        }

        return [
            'php_version'      => PHP_VERSION,
            'laravel_version'  => app()->version(),
            'db_driver'        => config('database.default'),
            'db_status'        => $dbStatus,
            'storage_disk'     => config('filesystems.default'),
            'storage_writable' => $storageWritable,
            'cache_driver'     => config('cache.default'),
            'cache_status'     => $cacheStatus,
        ];
    }

    public function render()
    {
        $info = $this->getSystemInfo();

        return view('livewire.admin.maintenance.index', [
            'info'          => $info,
            'actionLabels'  => self::ACTION_LABELS,
        ]);
    }
}
