<?php

namespace Modules\MedWorkforce\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedWorkforce\Entities\ShiftTemplate;
use Yajra\DataTables\Facades\DataTables;

/** Shift-template CRUD (SIFA P7-T1). Business-scoped; guarded by medwf.roster.manage. */
class TemplateController extends MedWorkforceBaseController
{
    public function index(Request $request)
    {
        $this->guard('medwf.roster.manage');

        if ($request->ajax()) {
            $query = ShiftTemplate::forBusiness($this->businessId());

            return DataTables::of($query)
                ->editColumn('start_time', fn ($r) => substr((string) $r->start_time, 0, 5))
                ->editColumn('end_time', fn ($r) => substr((string) $r->end_time, 0, 5))
                ->addColumn('color_badge', fn ($r) => '<span class="label" style="background:' . e($r->badgeColor()) . '">'
                    . e($r->name) . '</span>')
                ->editColumn('night_allowance', fn ($r) => $r->night_allowance
                    ? '<span class="label label-warning">' . __('medworkforce::lang.yes') . '</span>'
                    : '<span class="label label-default">' . __('medworkforce::lang.no') . '</span>')
                ->editColumn('is_active', fn ($r) => $r->is_active
                    ? '<span class="label label-success">' . __('medworkforce::lang.active') . '</span>'
                    : '<span class="label label-default">' . __('medworkforce::lang.inactive') . '</span>')
                ->addColumn('action', function ($r) {
                    return '<button class="btn btn-xs btn-default medwf-modal-btn" data-href="'
                        . route('medwf.templates.edit', $r->id) . '"><i class="fa fa-edit"></i> ' . __('messages.edit') . '</button> '
                        . '<button class="btn btn-xs btn-danger medwf-delete-btn" data-href="'
                        . route('medwf.templates.destroy', $r->id) . '"><i class="fa fa-trash"></i></button>';
                })
                ->rawColumns(['color_badge', 'night_allowance', 'is_active', 'action'])
                ->make(true);
        }

        return view('medworkforce::templates.index');
    }

    public function create()
    {
        $this->guard('medwf.roster.manage');

        return view('medworkforce::templates.form', [
            'template'    => new ShiftTemplate(),
            'departments' => $this->departments(),
            'locations'   => $this->locations(),
        ]);
    }

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

        $template = ShiftTemplate::forBusiness($this->businessId())->findOrFail($id);

        return view('medworkforce::templates.form', [
            'template'    => $template,
            'departments' => $this->departments(),
            'locations'   => $this->locations(),
        ]);
    }

    public function store(Request $request)
    {
        $this->guard('medwf.roster.manage');
        $data = $this->validated($request);

        try {
            $data['business_id'] = $this->businessId();
            ShiftTemplate::create($data);

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

            return $this->fail();
        }
    }

    public function update(Request $request, $id)
    {
        $this->guard('medwf.roster.manage');
        $template = ShiftTemplate::forBusiness($this->businessId())->findOrFail($id);
        $data = $this->validated($request);

        try {
            $template->update($data);

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

            return $this->fail();
        }
    }

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

        try {
            $template = ShiftTemplate::forBusiness($this->businessId())->findOrFail($id);
            if ($template->assignments()->exists()) {
                return $this->fail(__('medworkforce::lang.template_in_use'));
            }
            $template->delete();

            return $this->ok(__('medworkforce::lang.template_deleted'));
        } catch (\Exception $e) {
            return $this->fail();
        }
    }

    private function validated(Request $request): array
    {
        $data = $this->validate($request, [
            'name'                 => 'required|string|max:100',
            'start_time'           => 'required',
            'end_time'             => 'required',
            'department_id'        => 'nullable|integer',
            'business_location_id' => 'nullable|integer',
            'break_minutes'        => 'nullable|integer|min:0',
            'night_allowance'      => 'nullable|boolean',
            'color'                => 'nullable|string|max:20',
            'is_active'            => 'nullable|boolean',
        ]);

        return [
            'name'                 => $data['name'],
            'start_time'           => $data['start_time'],
            'end_time'             => $data['end_time'],
            'department_id'        => ! empty($data['department_id']) ? (int) $data['department_id'] : null,
            'business_location_id' => ! empty($data['business_location_id']) ? (int) $data['business_location_id'] : null,
            'break_minutes'        => (int) ($data['break_minutes'] ?? 0),
            'night_allowance'      => $request->boolean('night_allowance'),
            'color'                => $data['color'] ?? null,
            'is_active'            => $request->boolean('is_active', true),
        ];
    }
}
