<?php

namespace Modules\VetClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetClinic\Entities\VcAppointment;
use Modules\VetClinic\Entities\VcAppointmentEditRequest;
use Yajra\DataTables\Facades\DataTables;

class VcAppointmentEditRequestController extends Controller
{
    use \Modules\VetClinic\Http\Controllers\Traits\LogsVcActivity;

    /** Submit a request to edit a completed appointment. */
    public function store(Request $request, $appointmentId)
    {
        if (!auth()->user()->can('vet_clinic.manage_appointments')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate(['reason' => 'required|string|max:1000']);

        $businessId  = $request->session()->get('user.business_id');
        $appointment = VcAppointment::where('business_id', $businessId)->findOrFail($appointmentId);

        if ($appointment->status !== 'completed') {
            return response()->json(['success' => false, 'msg' => 'Only completed appointments need an edit request.'], 422);
        }

        // Block duplicates: an open (pending) or still-usable approved request
        $existing = VcAppointmentEditRequest::where('appointment_id', $appointment->id)
            ->where('requested_by', auth()->id())
            ->where(function ($q) {
                $q->where('status', 'pending')
                  ->orWhere(fn($x) => $x->where('status', 'approved')->whereNull('consumed_at'));
            })
            ->exists();

        if ($existing) {
            return response()->json(['success' => false, 'msg' => 'You already have an open edit request for this appointment.'], 422);
        }

        $editRequest = VcAppointmentEditRequest::create([
            'business_id'    => $businessId,
            'appointment_id' => $appointment->id,
            'requested_by'   => auth()->id(),
            'reason'         => $request->reason,
            'status'         => 'pending',
        ]);

        $this->vcLog('create', $editRequest, ['note' => 'Edit request for appointment #' . $appointment->id]);

        return response()->json(['success' => true, 'msg' => 'Edit request submitted for approval.']);
    }

    /** Approver dashboard. */
    public function index()
    {
        if (!auth()->user()->can('vet_clinic.approve_edit_requests')) {
            abort(403, 'Unauthorized action.');
        }
        return view('vetClinic::appointment-edit-requests.index');
    }

    public function list(Request $request)
    {
        if (!auth()->user()->can('vet_clinic.approve_edit_requests')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = $request->session()->get('user.business_id');
        $query = VcAppointmentEditRequest::with(['appointment.pet', 'appointment.doctor', 'requester', 'reviewer'])
            ->forBusiness($businessId)
            ->latest();

        if ($request->filled('status') && in_array($request->status, ['pending', 'approved', 'rejected'])) {
            $query->where('status', $request->status);
        }

        return DataTables::of($query)
            ->addColumn('appointment_ref', function ($row) {
                $apt = $row->appointment;
                if (!$apt) return '—';
                $ref = $apt->ref_no ?: ('#' . $apt->id);
                return '<a href="' . route('vc.appointments.show', $apt->id) . '" target="_blank">' . e($ref) . '</a>';
            })
            ->addColumn('pet_name', fn($row) => e(optional(optional($row->appointment)->pet)->petname ?? '—'))
            ->addColumn('doctor_name', fn($row) => e(optional(optional($row->appointment)->doctor)->name ?? '—'))
            ->addColumn('requester_name', fn($row) => e(optional($row->requester)->first_name ?? ('User #' . $row->requested_by)))
            ->editColumn('reason', fn($row) => '<span title="' . e($row->reason) . '">' . e(\Illuminate\Support\Str::limit($row->reason, 60)) . '</span>')
            ->addColumn('requested_at', fn($row) => optional($row->created_at)->format('d M Y H:i'))
            ->addColumn('status_badge', function ($row) {
                $map = ['pending' => 'warning', 'approved' => 'success', 'rejected' => 'danger'];
                $color = $map[$row->status] ?? 'default';
                $extra = '';
                if ($row->status === 'approved') {
                    $extra = $row->consumed_at
                        ? ' <span class="label label-default">Used</span>'
                        : ' <span class="label label-info">Unused</span>';
                }
                return '<span class="label label-' . $color . '">' . ucfirst($row->status) . '</span>' . $extra;
            })
            ->addColumn('reviewed_info', function ($row) {
                if ($row->status === 'pending') return '<span class="text-muted">—</span>';
                $by = optional($row->reviewer)->first_name ?? '—';
                $at = optional($row->reviewed_at)->format('d M Y H:i') ?? '';
                $notes = $row->review_notes ? '<br><small class="text-muted">' . e($row->review_notes) . '</small>' : '';
                return e($by) . '<br><small class="text-muted">' . $at . '</small>' . $notes;
            })
            ->addColumn('action', function ($row) {
                if ($row->status !== 'pending') {
                    return '<span class="text-muted">—</span>';
                }
                return '<button class="btn btn-xs btn-success btn-approve-req" data-id="' . $row->id . '"><i class="fa fa-check"></i> Approve</button> '
                     . '<button class="btn btn-xs btn-danger btn-reject-req" data-id="' . $row->id . '"><i class="fa fa-times"></i> Reject</button>';
            })
            ->rawColumns(['appointment_ref', 'reason', 'status_badge', 'reviewed_info', 'action'])
            ->make(true);
    }

    public function approve(Request $request, $id)
    {
        return $this->review($request, $id, 'approved');
    }

    public function reject(Request $request, $id)
    {
        return $this->review($request, $id, 'rejected');
    }

    private function review(Request $request, $id, string $decision)
    {
        if (!auth()->user()->can('vet_clinic.approve_edit_requests')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId  = $request->session()->get('user.business_id');
        $editRequest = VcAppointmentEditRequest::forBusiness($businessId)->findOrFail($id);

        if ($editRequest->status !== 'pending') {
            return response()->json(['success' => false, 'msg' => 'This request has already been reviewed.'], 422);
        }

        $before = ['status' => $editRequest->status];
        $editRequest->update([
            'status'       => $decision,
            'reviewed_by'  => auth()->id(),
            'reviewed_at'  => now(),
            'review_notes' => $request->input('review_notes'),
        ]);

        $this->vcLog('update', $editRequest, [
            'before' => $before,
            'after'  => ['status' => $decision, 'review_notes' => $request->input('review_notes')],
            'fields' => ['status', 'reviewed_by', 'reviewed_at', 'review_notes'],
        ]);

        $msg = $decision === 'approved'
            ? 'Request approved — the user can now make one edit to this appointment.'
            : 'Request rejected.';

        return response()->json(['success' => true, 'msg' => $msg]);
    }
}
