<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class SettingsController extends Controller
{
    public function index()
    {
        $settings = DB::table('settings')->pluck('value', 'key')->toArray();
        $adminUser = \App\Models\User::find(session('admin_id'));

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

    public function update(Request $request)
    {
        $request->validate([
            'app_name'         => 'required|string|max:100',
            'contact_email'    => 'required|email',
            'contact_phone'    => 'nullable|string',
            'google_maps_key'  => 'nullable|string',
            'trial_days'       => 'integer|min:0',
            'site_logo'        => 'nullable|image|mimes:jpeg,jpg,png,webp,gif|max:2048',
            'site_favicon'     => 'nullable|file|mimes:ico,png,svg,jpg,jpeg,webp|max:512',
        ]);

        $prev = DB::table('settings')->whereIn('key', ['site_logo', 'site_favicon'])->pluck('value', 'key')->all();

        $logoPath = $prev['site_logo'] ?? '';
        $faviconPath = $prev['site_favicon'] ?? '';

        if ($request->hasFile('site_logo')) {
            if ($logoPath) {
                Storage::disk('public')->delete($logoPath);
            }
            $logoPath = $request->file('site_logo')->store('site', 'public');
        }

        if ($request->hasFile('site_favicon')) {
            if ($faviconPath) {
                Storage::disk('public')->delete($faviconPath);
            }
            $faviconPath = $request->file('site_favicon')->store('site', 'public');
        }

        $settings = [
            'app_name'        => $request->app_name,
            'contact_email'   => $request->contact_email,
            'contact_phone'   => $request->contact_phone ?? '',
            'google_maps_key' => $request->google_maps_key ?? '',
            'trial_days'      => $request->trial_days ?? 14,
            'site_logo'       => $logoPath,
            'site_favicon'    => $faviconPath,
        ];

        foreach ($settings as $key => $value) {
            DB::table('settings')->updateOrInsert(
                ['key' => $key],
                ['value' => $value, 'updated_at' => now()]
            );
        }

        if ($request->filled('new_password')) {
            $request->validate([
                'new_password' => 'required|string|min:8|confirmed',
            ]);
            $admin = \App\Models\User::find(session('admin_id'));
            $admin->update(['password' => Hash::make($request->new_password)]);
        }

        return back()->with('success', 'تم حفظ الإعدادات بنجاح');
    }
}
