<?php

namespace Modules\ClinicCore\Http\Controllers;

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

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

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

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

        return view('clinicCore::birth-death.index', compact('doctors'));
    }

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

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

        if ($request->record_type) {
            $query->where('record_type', $request->record_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) {
                $color = $row->record_type === 'birth' ? 'success' : 'danger';
                $icon  = $row->record_type === 'birth' ? 'fa-heart' : 'fa-cross';
                return '<span class="label label-' . $color . '"><i class="fa ' . $icon . '"></i> ' . ucfirst($row->record_type) . '</span>';
            })
            ->addColumn('action', function ($row) {
                $edit = '<button class="btn btn-xs btn-primary btn-edit-bdr" data-id="' . $row->id . '"><i class="fa fa-edit"></i></button> ';
                $del  = '<button class="btn btn-xs btn-danger btn-delete-bdr" data-id="' . $row->id . '"><i class="fa fa-trash"></i></button>';
                return $edit . $del;
            })
            ->rawColumns(['action', 'type_badge'])
            ->make(true);
    }

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

        $request->validate([
            'record_type' => 'required|in:birth,death',
            'patient_id'      => 'required|integer',
            'contact_id'  => 'required|integer',
            'event_date'  => 'required|date',
        ]);

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

        $record = ClcBirthDeathRecord::create([
            'business_id' => $businessId,
            'record_type' => $request->record_type,
            'patient_id'      => $request->patient_id,
            'contact_id'  => $request->contact_id,
            'doctor_id'   => $request->doctor_id,
            'event_date'  => $request->event_date,
            'event_time'  => $request->event_time,
            'weight_kg'   => $request->weight_kg,
            'notes'       => $request->notes,
        ]);

        // Mark pet as deceased if this is a death record
        if ($request->record_type === 'death') {
            ClcPatient::where('id', $request->patient_id)
                ->where('business_id', $businessId)
                ->update(['deceased' => true, 'deceased_date' => $request->event_date]);
        }

        $this->drmLog('create', $record, ['note' => ucfirst($request->record_type) . ' record']);

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

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

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

        $businessId = request()->session()->get('user.business_id');
        $record = ClcBirthDeathRecord::where('business_id', $businessId)->findOrFail($id);
        $before = $record->getOriginal();
        $record->update($request->only(['event_date', 'event_time', 'doctor_id', 'weight_kg', 'notes']));
        $dirty = array_keys($record->getChanges());
        $this->drmLog('update', $record, [
            'before' => array_intersect_key($before, array_flip($dirty)),
            'after'  => array_intersect_key($record->getAttributes(), array_flip($dirty)),
            'fields' => $dirty,
        ]);

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

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

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

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