<?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 Illuminate\Support\Facades\File;
use Carbon\Carbon;
use App\Models\Master\Instansi;
use App\Models\Master\Template;
use App\Models\Master\TabelData;
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="p-2 text-white rounded bg-blue-500">Edit</a>';
                if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
                    $action .= '<a href="#" data-href="'.url('master/instansi/delete/'.encode_id($row->MsInstansiId)).'" data-toggle="tooltip" title="Hapus Data" class="remove_data p-2 text-white rounded bg-red-500">Hapus</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,
            'logo'            => '<img width="45" class="mx-auto" src="'.asset('uploads/'.@$row->logo).'">',
            '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();

                if (@$request->hasFile('logo')) {
                    $file = $request->file('logo');
                    $destinationPath = public_path('uploads/logo');
                    $current = Carbon::now()->format('Y/m/d');
                    $path = $destinationPath . '/' . $current;
                    $fileName = $file->getClientOriginalName();
                    $fileMime = $file->getClientMimeType();
                    $fileExtension = $file->getClientOriginalExtension();
                    $fileSize = $file->getSize();
                    if(($fileExtension != 'png') && ($fileExtension != 'jpg') && ($fileExtension != 'jpeg')){
                        return redirect()->back()->with([
                            'message' => 'Maaf File Harus Berupa png,jpg,jpeg!',
                            'type'    => "error"
                        ]);   
                    }
                    $newFilename = session('id').'_'.uniqid('file_') . '.' . $fileExtension;

                    if (!File::exists($path)) {
                        File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                    }

                    $filePath = 'logo/' . $current . '/' . $newFilename;
                    $uploaded = $file->move($path, $newFilename);

                }

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

                if (@$request->hasFile('logo')) {
                    $file = $request->file('logo');
                    $destinationPath = public_path('uploads/logo');
                    $current = Carbon::now()->format('Y/m/d');
                    $path = $destinationPath . '/' . $current;
                    $fileName = $file->getClientOriginalName();
                    $fileMime = $file->getClientMimeType();
                    $fileExtension = $file->getClientOriginalExtension();
                    $fileSize = $file->getSize();
                    if(($fileExtension != 'png') && ($fileExtension != 'jpg') && ($fileExtension != 'jpeg')){
                        return redirect()->back()->with([
                            'message' => 'Maaf File Harus Berupa png,jpg,jpeg!',
                            'type'    => "error"
                        ]);   
                    }
                    $newFilename = session('id').'_'.uniqid('file_') . '.' . $fileExtension;

                    if (!File::exists($path)) {
                        File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                    }

                    $filePath = 'logo/' . $current . '/' . $newFilename;
                    $uploaded = $file->move($path, $newFilename);

                }

                $inst = new Instansi;
                $inst->name = $request->name;
                $inst->parent = $request->parent;
                $inst->alamat     = $request->alamat;
                $inst->telp     = $request->telp;
                $inst->website     = $request->website;
                $inst->resource_data     = json_encode($request->resource_data);
                $inst->logo         = @$filePath;
                $inst->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'] = TabelData::all();
        return view($this->template.'.form',$data);
    }

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

    public function delete($id)
    {
        $keyId = decode_id($id);

        $user = Instansi::where('MsInstansiId',$keyId)->delete();

        return response()->json(['success' => true,'message' => 'Berhasil update data','type' => 'success']);
    }
}
