<?php

namespace App\Http\Controllers;

use App\Models\ArmadaType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class ArmadaTypesController extends Controller
{

    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = ArmadaType::select('m_armada_types.*');

            // Searching
            if ($request->has('search') && $request->search['value'] != '') {
                $search = $request->search['value'];
                $query->where(function ($q) use ($search) {
                    $q->where('m_armada_types.name', 'ilike', "%{$search}%")
                        ->orWhere('m_armada_types.description', 'ilike', "%{$search}%");
                });
            }

            $total = $query->count();

            // Sorting
            $columns = ['id', 'name', 'description', 'created_at'];
            $orderColumn = $columns[$request->order[0]['column']] ?? 'created_at';
            $orderDir = $request->order[0]['dir'] ?? 'desc';

            $query->orderBy($orderColumn, $orderDir);

            // Pagination
            $start = $request->start;
            $length = $request->length;
            $data = $query->skip($start)->take($length)->get();

            // Format data
            $result = [];
            $no = $start + 1;
            foreach ($data as $row) {
                $result[] = [
                    $no++,
                    '<a href="' . route('armada_types.show', $row->id) . '">' . $row->name . '</a>',
                    $row->description,
                    $row->created_at->format('M jS Y, H:i'),
                ];
            }

            return response()->json([
                "draw" => intval($request->draw),
                "recordsTotal" => $total,
                "recordsFiltered" => $total,
                "data" => $result,
            ]);
        }

        return view('m-armada-types.index', [
            'variables' => $this->variables()
        ]);
    }

    public function create()
    {
        $variables['judul'] = 'Add data';
        return view('m-armada-types.form', [
            'data' => json_decode(json_encode(array('id' => 0))),
            'variables' => $this->variables($variables)
        ]);
    }

    public function edit(ArmadaType $armadaType)
    {
        $variables['judul'] = 'Edit data';
        return view('m-armada-types.form', [
            'data' => $armadaType,
            'variables' => $this->variables($variables)
        ]);
    }

    private function variables($variables = null)
    {
        $variables['header_routes'] = ' 
								<li class="breadcrumb-item">Master</li>  
								<li class="breadcrumb-item active">Armada Types</li>
							 ';
        return $variables;
    }

    public function store(Request $request, $prm_id)
    {
        $armadaType = null;
        if ($prm_id)
            $armadaType = ArmadaType::findOrFail($prm_id);

        // Validasi
        $rules = [
            'name' => [
                'required',
                'string',
                'max:50',
                Rule::unique('m_armada_types', 'name')->ignore($armadaType?->id),
            ],
            'description' => 'nullable|string',
        ];

        $messages = [];
        $saveData = $request->validate($rules, $messages);

        try {
            DB::beginTransaction();
            
            if ($armadaType) {
                $armadaType->update(array_merge($saveData, [
                    'updated_by' => $this->logged_user_id,
                ]));
                $notif = 'Updated successfully.';
            } else {
                $armadaType = ArmadaType::create(array_merge($saveData, [
                    'created_by' => $this->logged_user_id,
                ]));
                $notif = 'Successfully created.';
            }

            DB::commit();
            return response()->json(['success', $notif]);
        } catch (\Exception $e) {
            DB::rollback();

            $notif = $this->getErrorCatch($e->getMessage());
            return response()->json(['warning', $notif]);
        }
    }

    public function show(ArmadaType $armadaType)
    {
        $armadaType->load(['creator', 'modificator']);
        $variables['judul'] = 'View data ID#' . $armadaType->id;
        return view('m-armada-types.show', [
            'data' => $armadaType,
            'variables' => $this->variables($variables)
        ]);
    }

    public function destroy(ArmadaType $armadaType)
    {
        if ($armadaType->delete_flag == 0) {
            $armadaType->update([
                'delete_flag' => 1,
                'updated_by' => $this->logged_user_id
            ]);

            return redirect()->route('armada_types.index')
                ->with('success', 'Successfully inactive');
        } else {
            $armadaType->update([
                'delete_flag' => 0,
                'updated_by' => $this->logged_user_id
            ]);

            return redirect()->route('armada_types.index')
                ->with('success', 'Successfully activated');
        }
    }

    private function getErrorCatch($e)
    {
        if (strpos($e, '#error#') !== false) {
            $e = explode('#error#', $e);
            $e = $e[1];
        }

        return $e;
    }
}
