<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcMedicalReport;
use Modules\ClinicCore\Entities\ClcPatient;
use Modules\ClinicCore\Entities\ClcDoctor;
use Yajra\DataTables\Facades\DataTables;

class ClcMedicalReportController extends Controller
{
    use \Modules\ClinicCore\Http\Controllers\Traits\LogsClcActivity;

    public function index()
    {
        if (!auth()->user()->can('clinic.manage_reports')) {
            abort(403, 'Unauthorized action.');
        }

        return view('clinicCore::medical-reports.index');
    }

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

        $businessId = request()->session()->get('user.business_id');
        $query = ClcMedicalReport::with(['pet', 'owner', 'doctor'])
            ->where('business_id', $businessId);

        if ($request->report_type) {
            $query->where('report_type', $request->report_type);
        }

        return DataTables::of($query)
            ->addColumn('pet_name', fn($row) => optional($row->pet)->patient_name ?? '—')
            ->addColumn('owner_name', fn($row) => optional($row->owner)->name ?? '—')
            ->addColumn('doctor_name', fn($row) => optional($row->doctor)->name ?? '—')
            ->addColumn('type_badge', function ($row) {
                $colors = ['lab' => 'info', 'xray' => 'primary', 'ultrasound' => 'warning', 'ecg' => 'success', 'other' => 'default'];
                $color = $colors[$row->report_type] ?? 'default';
                $badge = '<span class="label label-' . $color . '">' . ucfirst($row->report_type) . '</span>';
                if (($row->source ?? 'manual') === 'appointment_lab') {
                    $badge .= ' <span class="label label-success" title="Auto-synced from an appointment\'s lab / investigation results">'
                            . '<i class="fa fa-sync"></i> Synced</span>';
                }
                return $badge;
            })
            ->addColumn('action', function ($row) {
                $show = '<a href="' . route('clinic.medical-reports.show', $row->id) . '" class="btn btn-xs btn-info"><i class="fa fa-eye"></i></a> ';
                $edit = '<a href="' . route('clinic.medical-reports.edit', $row->id) . '" class="btn btn-xs btn-primary"><i class="fa fa-edit"></i></a> ';
                $del  = '<button class="btn btn-xs btn-danger btn-delete-report" data-id="' . $row->id . '"><i class="fa fa-trash"></i></button>';
                return $show . $edit . $del;
            })
            ->rawColumns(['action', 'type_badge'])
            ->make(true);
    }

    public function create()
    {
        if (!auth()->user()->can('clinic.manage_reports')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $doctors    = ClcDoctor::where('business_id', $businessId)->active()->orderBy('name')->get();

        return view('clinicCore::medical-reports.create', compact('doctors'));
    }

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

        $request->validate([
            'patient_id'       => 'required|integer',
            'contact_id'   => 'required|integer',
            'report_title' => 'required|string|max:200',
            'report_type'  => 'required|in:lab,xray,ultrasound,ecg,other',
        ]);

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

        $report = ClcMedicalReport::create([
            'business_id'    => $businessId,
            'patient_id'         => $request->patient_id,
            'contact_id'     => $request->contact_id,
            'doctor_id'      => $request->doctor_id,
            'appointment_id' => $request->appointment_id,
            'report_type'    => $request->report_type,
            'report_title'   => $request->report_title,
            'findings'       => $request->findings,
            'attachments'    => null,
        ]);
        $this->drmLog('create', $report);

        return redirect()->route('clinic.medical-reports.index')
            ->with('status', ['success' => 1, 'msg' => __('clinicCore::lang.saved_successfully')]);
    }

    public function show($id)
    {
        if (!auth()->user()->can('clinic.manage_reports')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $report     = ClcMedicalReport::with(['pet', 'owner', 'doctor', 'appointment'])
            ->where('business_id', $businessId)->findOrFail($id);

        return view('clinicCore::medical-reports.show', compact('report'));
    }

    public function edit($id)
    {
        if (!auth()->user()->can('clinic.manage_reports')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $report     = ClcMedicalReport::where('business_id', $businessId)->findOrFail($id);
        $doctors    = ClcDoctor::where('business_id', $businessId)->active()->orderBy('name')->get();

        return view('clinicCore::medical-reports.create', compact('report', 'doctors'));
    }

    public function update(Request $request, $id)
    {
        if (!auth()->user()->can('clinic.manage_reports')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'report_title' => 'required|string|max:200',
            'report_type'  => 'required|in:lab,xray,ultrasound,ecg,other',
        ]);

        $businessId = request()->session()->get('user.business_id');
        $report = ClcMedicalReport::where('business_id', $businessId)->findOrFail($id);
        $before = $report->getOriginal();
        $report->update($request->only(['report_type', 'report_title', 'findings', 'doctor_id']));
        $dirty = array_keys($report->getChanges());
        $this->drmLog('update', $report, [
            'before' => array_intersect_key($before, array_flip($dirty)),
            'after'  => array_intersect_key($report->getAttributes(), array_flip($dirty)),
            'fields' => $dirty,
        ]);

        // Two-way sync: write edits back into the source appointment's exam_results
        try {
            app(\Modules\ClinicCore\Services\MedicalReportSyncService::class)->syncToAppointment($report);
        } catch (\Throwable $e) {
            \Log::warning('ClinicCore report→lab sync failed: ' . $e->getMessage());
        }

        return redirect()->route('clinic.medical-reports.show', $id)
            ->with('status', ['success' => 1, 'msg' => __('clinicCore::lang.updated_successfully')]);
    }

    public function destroy($id)
    {
        if (!auth()->user()->can('clinic.manage_reports')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $report = ClcMedicalReport::where('business_id', $businessId)->findOrFail($id);
        $this->drmLog('delete', $report, ['before' => $this->_drmFilterAttrs($report->getAttributes())]);
        $report->delete();

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