<?php

namespace App\Http\Controllers;

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

class ParameterGlobalsController extends Controller
{

    function __construct()
    {
        parent::__construct();
    }

    public function index(Request $request)
    {
        $parameter_globals = ParameterGlobal::orderBy('id', 'DESC')->get();
        return view('m-paramater-globals.index', [
            'parameter_globals' => $parameter_globals,
            'variables' => $this->variables(),
        ]);
    }


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

    public function edit(ParameterGlobal $parameterGlobal)
    {
        $variables['judul'] = 'Edit data';
        return view('m-paramater-globals.form', [
            'data' => $parameterGlobal,
            'variables' => $this->variables($variables)
        ]);
    }

    public function store(Request $request, $prm_id)
    {
        $parameterGlobal = null;

        if ($prm_id)
            $parameterGlobal = ParameterGlobal::findOrFail($prm_id); // Jika tidak ditemukan, otomatis throw 404

        // Validasi untuk description dan data items
        $rules = [
            'version' => 'required|numeric|min:0',
            'value' => 'required|string|max:100',
            'description' => 'required|string|max:255',
        ];

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

        // echo '<pre>';
        // print_r($validated);
        // exit;
        try {
            // Mulai transaksi
            DB::beginTransaction();
 
            // Jika ada $parameterGlobal, berarti update
            if ($parameterGlobal) {
                $parameterGlobal->update(array_merge($saveData, [
                    'updated_by' => $this->logged_user_id,
                ]));
                $notif = 'Updated successfully.';
            } else {
                // Jika tidak ada $parameterGlobal, berarti create
                $parameterGlobal = ParameterGlobal::create(array_merge($saveData, [
                    'created_by' => $this->logged_user_id,
                ]));
                $notif = 'Successfully created.';
            }

            DB::commit();

            // Mengirim response JSON sukses
            return response()->json(['success', $notif]);
        } catch (\Exception $e) {

            DB::rollback();

            $notif = $this->getErrorCatch($e->getMessage());

            // Mengirim response JSON error
            return response()->json(['warning', $notif]);
        }
    }

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

        return $e;
    }

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