<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcDepartment;
use Modules\ClinicCore\Entities\ClcClinicLocation;
use Modules\ClinicCore\Entities\ClcDoctor;
use Yajra\DataTables\Facades\DataTables;

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

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

        $businessId  = request()->session()->get('user.business_id');
        $departments = ClcDepartment::where('business_id', $businessId)->orderBy('name')->get();
        $locations   = ClcClinicLocation::where('business_id', $businessId)->active()->orderBy('name')->get();

        return view('clinicCore::departments.index', compact('departments', 'locations'));
    }

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

        $businessId = request()->session()->get('user.business_id');
        $query = ClcDepartment::with('location')->where('business_id', $businessId);

        if ($request->filter_status) {
            $query->where('status', $request->filter_status);
        }
        if ($request->filter_location_id) {
            $query->where('location_id', $request->filter_location_id);
        }

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

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

        $request->validate([
            'name' => 'required|string|max:100',
        ]);

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

        $dept = ClcDepartment::create([
            'business_id' => $businessId,
            'name'        => $request->name,
            'icon'        => $request->icon,
            'description' => $request->description,
            'location_id' => $request->location_id ?: null,
            'status'      => $request->status ?? 'active',
        ]);
        $this->drmLog('create', $dept);

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

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

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

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

        $businessId = request()->session()->get('user.business_id');
        $department = ClcDepartment::where('business_id', $businessId)->findOrFail($id);

        $original = $department->getOriginal();
        $department->update([
            'name'        => $request->name,
            'icon'        => $request->icon,
            'description' => $request->description,
            'location_id' => $request->location_id ?: null,
            'status'      => $request->status ?? 'active',
        ]);
        $dirty = array_keys($department->getChanges());
        if ($dirty) {
            $this->drmLog('update', $department, [
                'before' => array_intersect_key($original, array_flip($dirty)),
                'after'  => array_intersect_key($department->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.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $department = ClcDepartment::where('business_id', $businessId)->findOrFail($id);

        // Block if any doctor has this as primary department
        $primaryCount = ClcDoctor::where('department_id', $id)->count();
        // Block if any doctor is assigned via pivot
        $pivotCount   = \DB::table('clc_doctor_departments')->where('department_id', $id)->count();
        $total        = $primaryCount + $pivotCount;

        if ($total > 0) {
            return response()->json([
                'success' => false,
                'msg'     => "Cannot delete: {$total} doctor(s) are assigned to this department. Reassign or remove them first.",
            ], 422);
        }

        $snap = $department->getAttributes();
        $this->drmLog('delete', $department, ['before' => $this->_drmFilterAttrs($snap)]);
        $department->delete();

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