<?php

namespace App\Http\Controllers;

use App\Models\SiteSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AdminSiteSettingController extends Controller
{
    public function edit()
    {
        return view('admin.settings.edit', [
            'settings' => SiteSetting::current(),
        ]);
    }

    public function update(Request $request)
    {
        $settings = SiteSetting::current();

        $data = $request->validate([
            'site_name_ar' => ['required', 'string', 'max:120'],
            'site_name_en' => ['required', 'string', 'max:120'],
            'logo_path' => ['nullable', 'string', 'max:255'],
            'logo' => ['nullable', 'image', 'max:4096'],
            'facebook_url' => ['nullable', 'url', 'max:255'],
            'instagram_url' => ['nullable', 'url', 'max:255'],
            'tiktok_url' => ['nullable', 'url', 'max:255'],
            'youtube_url' => ['nullable', 'url', 'max:255'],
            'whatsapp_url' => ['nullable', 'url', 'max:255'],
        ]);

        unset($data['logo']);

        if ($request->hasFile('logo')) {
            $directory = public_path('images/brand');
            if (! is_dir($directory)) {
                mkdir($directory, 0755, true);
            }

            $file = $request->file('logo');
            $filename = 'logo-'.Str::random(10).'.'.$file->getClientOriginalExtension();
            $file->move($directory, $filename);
            $data['logo_path'] = 'images/brand/'.$filename;
        } elseif (! isset($data['logo_path'])) {
            $data['logo_path'] = $settings->logo_path;
        }

        $settings->update($data);

        return back()->with('status', 'تم تحديث إعدادات المتجر.');
    }
}
