<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcMedicalCondition;
use Yajra\DataTables\Facades\DataTables;

class ClcMedicalConditionController extends Controller
{
    public function index()
    {
        if (!auth()->user()->can('clinic.manage_medical_conditions')) {
            abort(403, 'Unauthorized action.');
        }

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

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

        $businessId = request()->session()->get('user.business_id');
        $query = ClcMedicalCondition::forBusiness($businessId)->orderBy('name');

        return DataTables::of($query)
            ->addColumn('is_chronic_badge', fn($row) => $row->is_chronic
                ? '<span class="label label-warning">Chronic</span>'
                : '<span class="label label-default">Acute</span>')
            ->addColumn('status_badge', function ($row) {
                $color = $row->status === 'active' ? 'success' : 'danger';
                return '<span class="label label-' . $color . '">' . ucfirst($row->status) . '</span>';
            })
            ->addColumn('action', function ($row) {
                $edit = '<button class="btn btn-xs btn-primary btn-edit-condition" data-id="' . $row->id . '"><i class="fa fa-edit"></i></button> ';
                $del  = '<button class="btn btn-xs btn-danger btn-delete-condition" data-id="' . $row->id . '"><i class="fa fa-trash"></i></button>';
                return $edit . $del;
            })
            ->rawColumns(['action', 'is_chronic_badge', 'status_badge'])
            ->make(true);
    }

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

        $request->validate(['name' => 'required|string|max:150']);
        $businessId = request()->session()->get('user.business_id');

        ClcMedicalCondition::create([
            'business_id' => $businessId,
            'name'        => $request->name,
            'category'    => $request->category,
            'description' => $request->description,
            'icd_code'    => $request->icd_code,
            'is_chronic'  => $request->boolean('is_chronic'),
            'status'      => $request->status ?? 'active',
        ]);

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

    public function edit($id)
    {
        $businessId = request()->session()->get('user.business_id');
        return response()->json(ClcMedicalCondition::forBusiness($businessId)->findOrFail($id));
    }

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

        $request->validate(['name' => 'required|string|max:150']);
        $businessId = request()->session()->get('user.business_id');

        ClcMedicalCondition::forBusiness($businessId)->findOrFail($id)->update([
            'name'        => $request->name,
            'category'    => $request->category,
            'description' => $request->description,
            'icd_code'    => $request->icd_code,
            'is_chronic'  => $request->boolean('is_chronic'),
            'status'      => $request->status ?? 'active',
        ]);

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

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

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

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

    public function search(Request $request)
    {
        $businessId = request()->session()->get('user.business_id');
        $conditions = ClcMedicalCondition::active()->forBusiness($businessId)
            ->where('name', 'LIKE', '%' . $request->q . '%')
            ->orderBy('name')
            ->get(['id', 'name', 'category', 'is_chronic']);

        return response()->json($conditions->map(fn($c) => [
            'id'   => $c->id,
            'text' => $c->name . ($c->category ? ' [' . $c->category . ']' : ''),
        ]));
    }
}
