<?php

namespace App\Http\Controllers\Master;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\Master\Instansi;
use App\Models\Master\Template;
use App\Models\Master\Group;
use Illuminate\Http\Request;

class InstansiController extends Controller
{
    protected $title = 'Data Instansi';
    protected $template = 'modules.master.instansi';
    protected $route = 'modules.master.instansi';

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        permission('is_read', $this->route, 'module',true);
        
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Master Data'],
            ['name' => 'Data Instansi','active' => true],
        ];
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        return view($this->template.'.index',$data);
    }

    public function grid(Request $request)
    {

        $data = Instansi::orderBy('MsInstansiId','ASC')->get();
        // $data = User::with(['group'])->orderBy('id','DESC')->get();
        $_data = [];


        foreach ($data as $key => $row) {


            $action = '';

            if((permission('is_create', $this->route.'.*','module',false)) || (permission('is_update', $this->route.'.*','module',false))){
                $action .= '<div class="flex gap-3 justify-center items-center flex-row">';
                $action .= '<a href="'.url('master/instansi/update/'.encode_id($row->MsInstansiId)).'" data-toggle="tooltip" title="Edit Data" class="btn btn-sm btn-block bg-primary"><i class="ri-pencil-line text-white"></i></a>';
                if(session('group_id') == 1){
                    // $action .= '<a href="#" data-href="'.url('management/user/forcelogin/'.encode_id($row->id)).'" data-toggle="tooltip" title="Force Login" class="forcelogin btn btn-sm btn-block bg-success"><i class="ri-user-2-line text-white"></i></a>';
                    // $action .= '<a href="#" data-href="'.url('management/user/delete/'.encode_id($row->id)).'" data-toggle="tooltip" title="Hapus Data" class="remove_data btn btn-sm btn-block bg-danger"><i class="ri-delete-bin-line text-white"></i></a>';
                }
                $action .= '</div>';
            }

            if(@$row->resource_data){
                $resource = 'Ada';
            }else{
                $resource = '';
            }
            
           $_data[] = [
            'no'                => $key+1,
            'id'                => encode_id($row->id),
            'name'              => @$row->name,
            'parent'            => @$row->parent,
            'resource'            => @$resource,
            'action'            => @$action,
        ];

        }

        // return response()->json($_data);  // Return the data as a JSON response
        return response()->json($_data);

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {

            $keyId = decode_id($request->secure_id);

            if(@$keyId){
                Validator::make($request->all(), [
                    'name'            => 'required',
                    'parent'            => 'required',
                ])->validate();

                $user = Instansi::find($keyId);
                $user->name = $request->name;
                $user->parent = $request->parent;
                $user->alamat     = $request->alamat;
                $user->telp     = $request->telp;
                $user->website     = $request->website;
                $user->resource_data     = json_encode($request->resource_data);
                $user->save();
            }else{
                Validator::make($request->all(), [
                    'name'            => 'required',
                    'parent'            => 'required',
                ])->validate();

                $user = new Instansi;
                $user->name = $request->name;
                $user->parent = $request->parent;
                $user->alamat     = $request->alamat;
                $user->telp     = $request->telp;
                $user->website     = $request->website;
                $user->resource_data     = json_encode($request->resource_data);
                $user->save();
            }

            return redirect()->back()->with([
                'message' => 'Berhasil update data',
                'type'    => 'success',
            ]);
            
        } catch (Exception $e) {
            return redirect()->back()->with([
                     'message' => $e->getMessage(),
                     'type'    => "error"
                ]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Instansi $instansi)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Instansi $instansi)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update($id = null)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Master Data'],
            ['name' => 'Data Instansi','active' => true],
        ];
        $keyId = decode_id($id);
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        $data['keyId'] = $id;
        $data['item'] = Instansi::where('MsInstansiId',$keyId)->first();
        $data['group'] = Group::where('MsGroupId','!=',1)->get();
        $data['template'] = Template::all();
        return view($this->template.'.form',$data);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Instansi $instansi)
    {
        //
    }
}
