<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcDoctor;
use Modules\ClinicCore\Entities\ClcScheduleException;

/**
 * SIFA P3-T7 — per-doctor schedule exceptions (unavailable / modified / extra).
 *
 * Exposed as AJAX endpoints consumed by the doctor schedule modal (an
 * "Exceptions" tab next to the weekly pattern manager). All business_id-scoped
 * and gated by clinic.schedule.manage_exceptions.
 */
class ClcScheduleExceptionController extends Controller
{
    /** List a doctor's upcoming (and recent) exceptions. */
    public function list(Request $request, $doctorId)
    {
        if (!auth()->user()->can('clinic.schedule.manage_exceptions')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = $request->session()->get('user.business_id');

        // Ownership check: the doctor must belong to this business.
        ClcDoctor::where('business_id', $businessId)->findOrFail($doctorId);

        $rows = ClcScheduleException::forBusiness($businessId)
            ->where('doctor_id', $doctorId)
            ->whereDate('date', '>=', now()->subMonth()->toDateString())
            ->orderBy('date')
            ->get();

        return response()->json($rows->map(fn ($e) => [
            'id'         => $e->id,
            'date'       => $e->date ? $e->date->toDateString() : null,
            'type'       => $e->type,
            'start_time' => $e->start_time ? substr((string) $e->start_time, 0, 5) : null,
            'end_time'   => $e->end_time ? substr((string) $e->end_time, 0, 5) : null,
            'reason'     => $e->reason,
        ]));
    }

    /** Create an exception for a doctor. */
    public function store(Request $request, $doctorId)
    {
        if (!auth()->user()->can('clinic.schedule.manage_exceptions')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = $request->session()->get('user.business_id');
        ClcDoctor::where('business_id', $businessId)->findOrFail($doctorId);

        $data = $request->validate([
            'date'       => 'required|date',
            'type'       => 'required|in:unavailable,modified,extra',
            'start_time' => 'nullable',
            'end_time'   => 'nullable',
            'reason'     => 'nullable|string|max:255',
        ]);

        // modified / extra require a window; unavailable may optionally have one.
        if (in_array($data['type'], ['modified', 'extra'], true)
            && (empty($data['start_time']) || empty($data['end_time']))) {
            return response()->json([
                'success' => false,
                'msg'     => 'A start and end time are required for a modified or extra exception.',
            ], 422);
        }
        if (!empty($data['start_time']) && !empty($data['end_time']) && $data['start_time'] >= $data['end_time']) {
            return response()->json([
                'success' => false,
                'msg'     => 'End time must be after start time.',
            ], 422);
        }

        ClcScheduleException::create([
            'business_id' => $businessId,
            'doctor_id'   => (int) $doctorId,
            'date'        => $data['date'],
            'type'        => $data['type'],
            'start_time'  => $data['start_time'] ?: null,
            'end_time'    => $data['end_time'] ?: null,
            'reason'      => $data['reason'] ?? null,
            'created_by'  => auth()->id(),
        ]);

        return response()->json(['success' => true, 'msg' => __('clinicCore::lang.saved_successfully')]);
    }

    /** Delete an exception. */
    public function destroy(Request $request, $id)
    {
        if (!auth()->user()->can('clinic.schedule.manage_exceptions')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = $request->session()->get('user.business_id');

        ClcScheduleException::forBusiness($businessId)->findOrFail($id)->delete();

        return response()->json(['success' => true, 'msg' => __('clinicCore::lang.deleted_successfully')]);
    }
}
