<?php

namespace Modules\MedOrganization\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\MedOrganization\Entities\OrgRoom;
use Yajra\DataTables\Facades\DataTables;

/**
 * Room CRUD (spec §5 room) — org_rooms, FK to ClinicCore departments.
 */
class RoomController extends MedOrgBaseController
{
    public function index()
    {
        $this->guard('medorg.room.manage');

        if (request()->ajax()) {
            $rows = DB::table('org_rooms as r')
                ->join('clc_departments as d', 'd.id', '=', 'r.department_id')
                ->where('r.business_id', $this->businessId())
                ->select(['r.id', 'r.name', 'r.code', 'r.room_type', 'r.floor', 'r.capacity', 'r.status', 'r.scheduling_enabled', 'd.name as department_name']);

            return DataTables::of($rows)
                ->editColumn('room_type', fn ($r) => __('medorganization::lang.room_type_' . $r->room_type))
                ->editColumn('status', function ($r) {
                    $class = ['available' => 'success', 'occupied' => 'danger', 'maintenance' => 'warning', 'reserved' => 'info'][$r->status] ?? 'default';

                    return '<span class="label label-' . $class . '">' . __('medorganization::lang.room_status_' . $r->status) . '</span>';
                })
                ->editColumn('scheduling_enabled', fn ($r) => $r->scheduling_enabled
                    ? '<i class="fa fa-check text-success"></i>'
                    : '<i class="fa fa-times text-muted"></i>')
                ->addColumn('action', function ($r) {
                    return '<button data-href="' . route('medorg.rooms.edit', $r->id) . '" class="btn btn-xs btn-primary medorg-modal-btn"><i class="fa fa-edit"></i></button> '
                        . '<button data-href="' . route('medorg.rooms.destroy', $r->id) . '" class="btn btn-xs btn-danger medorg-delete"><i class="fa fa-trash"></i></button>';
                })
                ->rawColumns(['status', 'scheduling_enabled', 'action'])
                ->make(true);
        }

        return view('medorganization::rooms.index');
    }

    public function create()
    {
        $this->guard('medorg.room.manage');

        return view('medorganization::rooms.create', $this->formData());
    }

    public function store(Request $request)
    {
        $this->guard('medorg.room.manage');
        $data = $this->rules($request);

        try {
            $data['business_id'] = $this->businessId();
            $data['scheduling_enabled'] = $request->boolean('scheduling_enabled');
            $data['equipment'] = $this->equipmentList($request);

            OrgRoom::create($data);

            return $this->ok(__('medorganization::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    public function edit($id)
    {
        $this->guard('medorg.room.manage');

        $room = OrgRoom::forBusiness($this->businessId())->findOrFail($id);

        return view('medorganization::rooms.edit', array_merge($this->formData(), compact('room')));
    }

    public function update(Request $request, $id)
    {
        $this->guard('medorg.room.manage');
        $data = $this->rules($request);

        try {
            $room = OrgRoom::forBusiness($this->businessId())->findOrFail($id);
            $data['scheduling_enabled'] = $request->boolean('scheduling_enabled');
            $data['equipment'] = $this->equipmentList($request);

            $room->update($data);

            return $this->ok(__('medorganization::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    public function destroy($id)
    {
        $this->guard('medorg.room.manage');

        try {
            OrgRoom::forBusiness($this->businessId())->findOrFail($id)->delete();

            return $this->ok(__('medorganization::lang.deleted_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    protected function rules(Request $request): array
    {
        $data = $this->validate($request, [
            'name'          => 'required|string|max:100',
            'code'          => 'nullable|string|max:20',
            'department_id' => 'required|integer',
            'room_type'     => 'required|in:' . implode(',', OrgRoom::ROOM_TYPES),
            'floor'         => 'nullable|integer',
            'capacity'      => 'nullable|integer|min:0',
            'status'        => 'required|in:' . implode(',', OrgRoom::STATUSES),
        ]);

        // Department must belong to this business (tenant scoping).
        $owned = DB::table('clc_departments')
            ->where('business_id', $this->businessId())
            ->where('id', $data['department_id'])
            ->exists();
        if (! $owned) {
            abort(403, 'Unauthorized action.');
        }

        return $data;
    }

    /** Comma-separated equipment input → array|null. */
    protected function equipmentList(Request $request): ?array
    {
        $raw = trim((string) $request->input('equipment'));
        if ($raw === '') {
            return null;
        }

        $items = array_values(array_filter(array_map('trim', explode(',', $raw))));

        return $items ?: null;
    }

    protected function formData(): array
    {
        return [
            'departments' => $this->departments(),
            'roomTypes'   => OrgRoom::ROOM_TYPES,
            'statuses'    => OrgRoom::STATUSES,
        ];
    }
}
