<?php

namespace Modules\VetClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Modules\VetClinic\Entities\VcAuthorizedVet;
use Modules\VetClinic\Entities\VcDoctor;
use Modules\VetClinic\Entities\VcMedicine;

/**
 * Settings page: which doctors hold a permit to dispense controlled drugs,
 * which schedules they may dispense, and when the permit expires.
 *
 * Gated by vet_clinic.manage_controlled (the same permission that lets a user
 * flag a medicine as controlled).
 */
class VcAuthorizedVetController extends Controller
{
    use \Modules\VetClinic\Http\Controllers\Traits\LogsVcActivity;

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

    public function index(Request $request)
    {
        $this->guard();
        $businessId = $request->session()->get('user.business_id');

        $rows = VcAuthorizedVet::with('doctor:id,name,specialization')
            ->where('business_id', $businessId)
            ->get()->keyBy('doctor_id');

        $doctors = VcDoctor::where('business_id', $businessId)
            ->active()->orderBy('name')->get(['id', 'name', 'specialization']);

        return view('vetClinic::authorized-vets.index', [
            'doctors'   => $doctors,
            'rows'      => $rows,
            'schedules' => VcMedicine::schedules(),
        ]);
    }

    public function store(Request $request)
    {
        $this->guard();
        $businessId = $request->session()->get('user.business_id');

        $request->validate([
            'doctor_id'   => 'required|integer',
            'schedules'   => 'required|array|min:1',
            'schedules.*' => 'string',
            'permit_no'   => 'nullable|string|max:80',
            'valid_until' => 'nullable|date',
            'notes'       => 'nullable|string|max:500',
            'document'    => 'nullable|file|max:5120|mimes:pdf,jpg,jpeg,png',
        ]);

        $schedules = array_values(array_intersect($request->schedules, array_keys(VcMedicine::schedules())));

        $row = VcAuthorizedVet::firstOrNew([
            'business_id' => $businessId,
            'doctor_id'   => (int) $request->doctor_id,
        ]);

        $row->fill([
            'schedules'   => $schedules,
            'permit_no'   => $request->permit_no,
            'valid_until' => $request->valid_until ?: null,
            'notes'       => $request->notes,
        ]);

        if ($request->hasFile('document')) {
            if ($row->document_path) Storage::disk('public')->delete($row->document_path);
            $row->document_path = $request->file('document')
                ->store("vc_authorized_vets/{$businessId}", 'public');
        }
        $row->created_by = $row->created_by ?: auth()->id();
        $row->save();
        $this->vcLog('update', $row, ['action' => 'authorisation_saved']);

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

    public function destroy(Request $request, $id)
    {
        $this->guard();
        $businessId = $request->session()->get('user.business_id');
        $row = VcAuthorizedVet::where('business_id', $businessId)->findOrFail($id);
        if ($row->document_path) Storage::disk('public')->delete($row->document_path);
        $this->vcLog('delete', $row);
        $row->delete();
        return back()->with('status', ['success' => 1, 'msg' => __('vetClinic::lang.deleted_successfully')]);
    }
}
