<?php

namespace Modules\ClinicSite\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;
use Modules\ClinicSite\Entities\CsSite;

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

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

    public function index()
    {
        $this->gate();
        $site       = CsSite::forBusiness($this->biz());
        $baseDomain = config('clinicsite.base_domain');
        return view('clinicSite::admin.domain', compact('site', 'baseDomain'));
    }

    public function save(Request $request)
    {
        $this->gate();
        $site = CsSite::forBusiness($this->biz());

        $request->validate([
            'subdomain_slug' => 'nullable|alpha_dash|max:80',
            'custom_domain'  => 'nullable|string|max:150',
        ]);

        $slug   = $request->subdomain_slug ? Str::slug($request->subdomain_slug) : null;
        $domain = $request->custom_domain
            ? strtolower(preg_replace('#^https?://#', '', rtrim(trim($request->custom_domain), '/')))
            : null;

        // Uniqueness across all businesses.
        if ($slug && CsSite::where('subdomain_slug', $slug)->where('id', '!=', $site->id)->exists()) {
            return back()->with('status', ['success' => 0, 'msg' => 'That subdomain is already taken.']);
        }
        if ($domain && CsSite::where('custom_domain', $domain)->where('id', '!=', $site->id)->exists()) {
            return back()->with('status', ['success' => 0, 'msg' => 'That domain is already registered to another site.']);
        }

        $site->update([
            'subdomain_slug'         => $slug,
            'custom_domain'          => $domain,
            // Changing the domain resets verification.
            'custom_domain_verified' => $domain === $site->custom_domain ? $site->custom_domain_verified : false,
        ]);

        return redirect()->route('cs.domain')->with('status', ['success' => 1, 'msg' => __('clinicSite::lang.saved')]);
    }
}
