<?php

namespace Modules\VetPortal\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;
use Modules\VetPortal\Entities\VpPortalSetting;

class VpSettingsController extends Controller
{
    private function biz()
    {
        return request()->session()->get('user.business_id');
    }

    private function gate()
    {
        if (!auth()->user()->can('vet_portal.manage_settings')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->gate();
        $settings = VpPortalSetting::forBusiness($this->biz());
        return view('vetPortal::settings.index', compact('settings'));
    }

    public function save(Request $request)
    {
        $this->gate();
        $request->validate([
            'clinic_name' => 'nullable|string|max:150',
            'portal_slug' => 'nullable|alpha_dash|max:80',
        ]);

        $businessId = $this->biz();
        $settings   = VpPortalSetting::forBusiness($businessId);

        $data = [
            'enabled'         => $request->boolean('enabled'),
            'clinic_name'     => $request->clinic_name,
            'primary_color'   => $request->primary_color ?: '#2563eb',
            'welcome_text'    => $request->welcome_text,
            'whatsapp_number' => preg_replace('/[^0-9+]/', '', (string) $request->whatsapp_number) ?: null,
            'portal_slug'     => $request->portal_slug ? Str::slug($request->portal_slug) : null,
            'custom_domain'   => $request->custom_domain ?: null,
        ];

        if ($request->hasFile('logo') && $request->file('logo')->isValid()) {
            $dir = public_path('uploads/vet-portal');
            if (!is_dir($dir)) {
                @mkdir($dir, 0755, true);
            }
            $filename = 'logo-' . $businessId . '-' . time() . '.' . $request->file('logo')->getClientOriginalExtension();
            $request->file('logo')->move($dir, $filename);
            $data['logo_path'] = 'vet-portal/' . $filename;
        }

        $settings->update($data);

        return redirect()->route('vp.settings.index')
            ->with('status', ['success' => 1, 'msg' => __('vetPortal::lang.saved')]);
    }
}
