<?php

namespace Modules\VetClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetClinic\Entities\VcRoleLandingPage;
use Modules\VetClinic\Entities\VcRoleSetting;
use Spatie\Permission\Models\Role;

/**
 * VetClinic settings page that maps a role to its post-login landing URL.
 * The redirect itself is applied by ApplyRoleLandingRedirect middleware.
 */
class VcRoleLandingController extends Controller
{
    use \Modules\VetClinic\Http\Controllers\Traits\LogsVcActivity;

    private function guard(): void
    {
        if (!auth()->user()->can('vet_clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index(Request $request)
    {
        $this->guard();

        $businessId = $request->session()->get('user.business_id');

        // Per-business roles in UltimatePOS are suffixed "#<business_id>".
        $roles = Role::where('name', 'like', '%#' . $businessId)
            ->orderBy('name')->get(['id', 'name']);

        $existing = VcRoleLandingPage::where('business_id', $businessId)
            ->pluck('landing_url', 'role_id');

        $scopes = VcRoleSetting::where('business_id', $businessId)
            ->where('key', 'appointment_scope')
            ->pluck('value', 'role_id');

        return view('vetClinic::role-landing.index', [
            'roles'    => $roles,
            'existing' => $existing,
            'scopes'   => $scopes,
            'presets'  => VcRoleLandingPage::presets(),
        ]);
    }

    public function save(Request $request)
    {
        $this->guard();

        $businessId = $request->session()->get('user.business_id');

        $payload = $request->input('landing', []);
        $scopes  = $request->input('scope', []);
        $savedCount = 0;

        foreach ($payload as $roleId => $url) {
            $url = trim((string) $url);
            $row = VcRoleLandingPage::firstOrNew([
                'business_id' => $businessId,
                'role_id'     => (int) $roleId,
            ]);
            if ($url === '' || ltrim($url, '/') === 'home') {
                if ($row->exists) {
                    $row->delete();
                    $savedCount++;
                }
            } else {
                // Accept absolute paths only — never let an admin paste an external host.
                if (!str_starts_with($url, '/')) {
                    $url = '/' . $url;
                }
                $row->landing_url = $url;
                $row->save();
                $savedCount++;
            }

            // Appointment-scope flag (per role).
            $scopeVal = trim((string) ($scopes[$roleId] ?? ''));
            // Only 'own' is a real value; anything else clears the row.
            VcRoleSetting::set(
                (int) $businessId,
                (int) $roleId,
                'appointment_scope',
                $scopeVal === 'own' ? 'own' : null
            );
        }

        $this->vcLog('update', new VcRoleLandingPage([
            'business_id' => $businessId,
        ]), ['action' => 'role_landing_saved', 'changes' => $savedCount]);

        return back()->with('status', [
            'success' => 1,
            'msg'     => __('vetClinic::lang.saved_successfully'),
        ]);
    }
}
