<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Schema;
use Modules\ClinicCore\Entities\ClcClinicLocation;
use Modules\ClinicCore\Entities\ClcDepartment;
use App\BusinessLocation;
use Yajra\DataTables\Facades\DataTables;

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

        $businessId        = request()->session()->get('user.business_id');
        $businessLocations = BusinessLocation::where('business_id', $businessId)->get();

        return view('clinicCore::settings.locations', compact('businessLocations'));
    }

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

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

        return DataTables::of($query)
            ->addColumn('erp_location', fn($row) => optional($row->businessLocation)->name ?? '—')
            ->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-location" data-id="' . $row->id . '"><i class="fa fa-edit"></i></button> ';
                $del  = '<button class="btn btn-xs btn-danger btn-delete-location" data-id="' . $row->id . '"><i class="fa fa-trash"></i></button>';
                return $edit . $del;
            })
            ->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:150',
            'business_location_id' => 'required|integer|exists:business_locations,id',
        ]);

        $businessId = request()->session()->get('user.business_id');
        $data = array_merge(
            $request->only(['name', 'address', 'phone', 'email', 'notes']),
            ['business_id' => $businessId, 'status' => $request->input('status', 'active')]
        );

        if (Schema::hasColumn('clc_clinic_locations', 'business_location_id')) {
            $data['business_location_id'] = (int) $request->business_location_id;
        }

        ClcClinicLocation::create($data);

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

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

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

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

        $request->validate([
            'name'                 => 'required|string|max:150',
            'business_location_id' => 'required|integer|exists:business_locations,id',
        ]);

        $businessId = request()->session()->get('user.business_id');
        $data = $request->only(['name', 'address', 'phone', 'email', 'notes', 'status']);

        if (Schema::hasColumn('clc_clinic_locations', 'business_location_id')) {
            $data['business_location_id'] = (int) $request->business_location_id;
        }

        ClcClinicLocation::where('business_id', $businessId)->findOrFail($id)->update($data);

        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');
        $location   = ClcClinicLocation::where('business_id', $businessId)->findOrFail($id);

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

        $location->delete();

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