<?php

namespace App\Http\Controllers\Master;

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

class FormKriteriaController extends Controller
{
    protected $title = 'Form Kriteria';
    protected $template = 'modules.master.form-kriteria';
    protected $route = 'modules.master.form-kriteria';

    public function index()
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Management & Akses Role'],
            ['name' => $this->title,'active' => true],
        ];
        $data['title'] = $this->title;
        $data['route'] = $this->route;

        return view($this->template.'.index',$data);
    }

    public function update($id = null)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Management & Akses Role'],
            ['name' => $this->title,'active' => true],
        ];
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        $keyId = decode_id($id);
        $data['item'] = FormKriteria::find($keyId);
        $data['keyId'] = $id;

        return view($this->template.'.form',$data);
    }

    public function grid(Request $request)
    {

        $data = FormKriteria::orderBy('page_number','ASC')->where('tahun',date('Y'))->get();
        $_data = [];


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


            $action = '';

            if((permission('is_create', $this->route.'.*','module',false)) || (permission('is_update', $this->route.'.*','module',false))){
                $action .= '<a href="'.url('master/form-kriteria/update/'.encode_id($row->MsFormKriteriaId)).'" data-toggle="tooltip" title="Edit Data" class="btn btn-xs btn-block btn-primary"><i class="fal fa-pencil text-white"></i></a>';
                if(session('group_id') == 1){
                    $action .= '<a href="#" data-href="'.url('master/form-kriteria/delete/'.encode_id($row->MsFormKriteriaId)).'" data-toggle="tooltip" title="Edit Data" class="remove_data btn btn-xs btn-block btn-danger"><i class="fal fa-trash text-white"></i></a>';
                }
            }
            
           $_data[] = [
            'no'          => $key+1,
            'id'          => encode_id($row->MsFormKriteriaId),
            'kategori' => @$row->kategori,
            'page_number' => @$row->page_number,
            'judul'       => @$row->judul,
            'type'       => \Str::title(str_replace('_',' ',@$row->type)),
            'created_at'  => dateTime(@$row->created_at),
            'action'      => @$action,
        ];

        }

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

    }

    public function store(Request $request)
    {
        
        try {
            $keyId = decode_id($request->secure_id);

            if(!@$keyId){
                Validator::make($request->all(), [
                        'page_number' => 'required',
                        'kategori'    => 'required',
                        'judul'       => 'required',
                        'type'        => 'required',
                    ])->validate();

                $insert = new FormKriteria;
                $insert->page_number            = $request->page_number;
                $insert->key                    = $request->key;
                $insert->kategori               = $request->kategori;
                $insert->keterangan             = $request->keterangan;
                $insert->judul                  = $request->judul;
                $insert->type                   = $request->type;
                $insert->option                 = json_encode($request->jawaban);
                $insert->active_lainnya         = $request->active_lainnya;
                $insert->judul_lainnya          = $request->judul_lainnya;
                $insert->number_answer_lainnya  = $request->number_answer_lainnya;
                $insert->active                 = 1;
                $insert->tahun                  = date('Y');
                $insert->save();

                logActivity($request, __('Create',['val' => strtolower(__('Title',['val' => 'Form Kriteria']))]));
            }else{
                $insert = FormKriteria::find($keyId);
                $insert->page_number            = $request->page_number;
                $insert->key                    = $request->key;
                $insert->kategori               = $request->kategori;
                $insert->keterangan             = $request->keterangan;
                $insert->judul                  = $request->judul;
                $insert->type                   = $request->type;
                $insert->option                 = json_encode($request->jawaban);
                $insert->active_lainnya         = $request->active_lainnya;
                $insert->judul_lainnya          = $request->judul_lainnya;
                $insert->number_answer_lainnya  = $request->number_answer_lainnya;
                // $insert->active                 = 1;
                $insert->save();

                logActivity($request, __('Update',['val' => strtolower(__('Title',['val' => 'Form Kriteria User ID => '.auth()->user()->id.' Form ID => '.$keyId]))]));
            }
            return redirect()->back()->with([
                    'message' => 'Berhasil update data',
                    'type'    => 'success',
                ]);

            
        } catch (Exception $e) {
            return redirect()->back()->with([
                     'message' => $e->getMessage(),
                     'type'    => "error"
                ]);
        }
        
        // dd(request()->all());
    }

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

        $form = FormKriteria::where('MsFormKriteriaId',$keyId)->delete();

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