<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;

class SettingController extends Controller
{
    // ── Tampilkan halaman pengaturan ──────────────────────────

    public function index()
    {
        // Muat semua setting dari DB, gabungkan dengan defaults untuk key yang belum ada
        $rows = Setting::orderBy('group')->orderBy('key')->get()->keyBy('key');

        // Struktur tab/grup
        $groups = [
            'perusahaan' => [
                'label' => 'Identitas Perusahaan',
                'icon'  => 'M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-2 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4',
            ],
            'nota' => [
                'label' => 'Nota & Tanda Terima',
                'icon'  => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z',
            ],
            'form' => [
                'label' => 'Form Pendaftaran',
                'icon'  => 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2',
            ],
            'invoice' => [
                'label' => 'Tampilan Invoice',
                'icon'  => 'M9 14H7a2 2 0 00-2 2v2a2 2 0 002 2h10a2 2 0 002-2v-2a2 2 0 00-2-2h-2m-6-4h6M9 7h6M9 11h6',
            ],
            'notifikasi' => [
                'label' => 'Notifikasi',
                'icon'  => 'M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9',
            ],
        ];

        return view('admin.settings.index', compact('rows', 'groups'));
    }

    // ── Simpan semua setting ──────────────────────────────────

    public function update(Request $request)
    {
        // ── Logo upload ────────────────────────────────────────
        if ($request->hasFile('logo_upload')) {
            $request->validate([
                'logo_upload' => ['file', 'image', 'max:2048', 'mimes:png,jpg,jpeg,svg,webp'],
            ]);
            $oldPath = Setting::get('invoice_logo_path');
            if ($oldPath) {
                Storage::disk('public')->delete($oldPath);
            }
            $path = $request->file('logo_upload')->store('settings/logos', 'public');
            Setting::set('invoice_logo_path', $path);
            Cache::forget('setting.invoice_logo_path');
        }

        // ── Semua field lain ───────────────────────────────────
        $input = $request->except(['_token', '_method', 'logo_upload']);

        foreach ($input as $key => $value) {
            if (array_key_exists($key, Setting::$defaults) || Setting::where('key', $key)->exists()) {
                Setting::set($key, is_array($value) ? implode(',', $value) : (string) $value);
            }
        }

        // Toggle fields yang tidak di-submit (unchecked checkbox = off)
        $toggleKeys = Setting::where('type', 'toggle')->pluck('key');
        foreach ($toggleKeys as $k) {
            if (! isset($input[$k])) {
                Setting::set($k, '0');
            }
        }

        Cache::flush();

        return back()->with('success', 'Pengaturan berhasil disimpan.');
    }
}
