<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SystemSetting;
use App\Models\BusinessHour;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    private function admin(): void {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
    }

    // ── Panel principal ───────────────────────────────────────────────────────
    public function index()
    {
        $this->admin();
        $settings = SystemSetting::all()->keyBy('key');
        $hours    = BusinessHour::orderBy('day_of_week')->get()
            ->keyBy('day_of_week');
        return view('admin.settings.index', compact('settings','hours'));
    }

    // ── Guardar configuración general / branding ──────────────────────────────
    public function update(Request $request)
    {
        $this->admin();
        $fields = [
            'app_name'           => ['general','string'],
            'app_tagline'        => ['general','string'],
            'app_primary_color'  => ['branding','string'],
            'app_logo_url'       => ['branding','string'],
            'support_email'      => ['general','string'],
            'support_phone'      => ['general','string'],
            'tickets_per_page'   => ['tickets','integer'],
            'auto_close_days'    => ['tickets','integer'],
            'sla_pauses_outside' => ['sla','boolean'],
            'welcome_message'    => ['portal','text'],
        ];

        foreach ($fields as $key => [$group, $type]) {
            if ($request->has($key)) {
                $value = $type === 'boolean'
                    ? ($request->boolean($key) ? '1' : '0')
                    : $request->input($key);
                SystemSetting::set($key, $value, $group, $type);
            }
        }

        return back()->with('success', 'Configuración guardada.');
    }

    // ── Guardar horarios ──────────────────────────────────────────────────────
    public function updateHours(Request $request)
    {
        $this->admin();
        foreach (range(0, 6) as $day) {
            BusinessHour::updateOrCreate(
                ['day_of_week' => $day],
                [
                    'active'    => $request->boolean("day_{$day}_active"),
                    'opens_at'  => $request->input("day_{$day}_opens",  '08:00'),
                    'closes_at' => $request->input("day_{$day}_closes", '17:00'),
                ]
            );
        }
        return back()->with('success', 'Horarios de atención guardados.');
    }
}
