<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsTaskTemplate;
use Yajra\DataTables\Facades\DataTables;

class TaskTemplateController extends BmsBaseController
{
    protected function departments(): array
    {
        return [
            'sales'       => __('bms::lang.dep_sales'),
            'finance'     => __('bms::lang.dep_finance'),
            'kitchen'     => __('bms::lang.dep_kitchen'),
            'logistics'   => __('bms::lang.dep_logistics'),
            'operations'  => __('bms::lang.dep_operations'),
            'warehouse'   => __('bms::lang.dep_warehouse'),
            'qc'          => __('bms::lang.dep_qc'),
            'maintenance' => __('bms::lang.dep_maintenance'),
        ];
    }

    public function index()
    {
        $this->guard('bms.settings.access');

        if (request()->ajax()) {
            $deps = $this->departments();
            $rows = BmsTaskTemplate::where('business_id', $this->businessId())
                ->select(['id', 'title', 'department', 'event_type', 'offset_days', 'offset_hour', 'is_active']);

            return DataTables::of($rows)
                ->editColumn('department', fn ($r) => $deps[$r->department] ?? $r->department)
                ->editColumn('event_type', fn ($r) => $r->event_type ?: '<em>'.__('messages.all').'</em>')
                ->editColumn('offset_days', fn ($r) => $r->offset_days == 0 ? __('bms::lang.event_day') : ($r->offset_days < 0 ? abs($r->offset_days).' '.__('bms::lang.days_before') : $r->offset_days.' '.__('bms::lang.days_after')))
                ->editColumn('is_active', fn ($r) => $r->is_active
                    ? '<span class="label label-success">'.__('bms::lang.active').'</span>'
                    : '<span class="label label-default">'.__('bms::lang.inactive').'</span>')
                ->addColumn('action', function ($r) {
                    $edit = '<button data-href="'.route('bms.task-templates.edit', $r->id).'" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline tw-dw-btn-primary bms-modal-btn"><i class="glyphicon glyphicon-edit"></i> '.__('messages.edit').'</button>';
                    $del = '<button data-href="'.route('bms.task-templates.destroy', $r->id).'" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline tw-dw-btn-error bms-delete"><i class="glyphicon glyphicon-trash"></i> '.__('messages.delete').'</button>';
                    return $edit.' '.$del;
                })
                ->rawColumns(['action', 'is_active', 'event_type'])
                ->make(true);
        }

        return view('bms::task_templates.index');
    }

    public function create()
    {
        $this->guard('bms.settings.access');
        return view('bms::task_templates.create', ['departments' => $this->departments()]);
    }

    public function store(Request $request)
    {
        $this->guard('bms.settings.access');
        $data = $this->validatedData($request);
        try {
            $data['business_id'] = $this->businessId();
            $data['is_active'] = $request->boolean('is_active');
            BmsTaskTemplate::create($data);
            return $this->ok(__('bms::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function edit($id)
    {
        $this->guard('bms.settings.access');
        $template = BmsTaskTemplate::where('business_id', $this->businessId())->findOrFail($id);
        return view('bms::task_templates.edit', ['template' => $template, 'departments' => $this->departments()]);
    }

    public function update(Request $request, $id)
    {
        $this->guard('bms.settings.access');
        $data = $this->validatedData($request);
        try {
            $template = BmsTaskTemplate::where('business_id', $this->businessId())->findOrFail($id);
            $data['is_active'] = $request->boolean('is_active');
            $template->update($data);
            return $this->ok(__('bms::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function destroy($id)
    {
        $this->guard('bms.settings.access');
        try {
            BmsTaskTemplate::where('business_id', $this->businessId())->findOrFail($id)->delete();
            return $this->ok(__('bms::lang.deleted_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    protected function validatedData(Request $request): array
    {
        return $this->validate($request, [
            'title'         => 'required|string|max:191',
            'department'    => 'required|string|max:40',
            'event_type'    => 'nullable|string|max:60',
            'offset_days'   => 'required|integer|min:-365|max:365',
            'offset_hour'   => 'nullable|integer|min:0|max:23',
            'assignee_role' => 'nullable|string|max:60',
            'description'   => 'nullable|string',
            'is_active'     => 'nullable',
        ]);
    }
}
