<?php

namespace App\Http\Controllers\Operator;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use DB;
use URL;
use Auth;
use Uuid;
use Alert;
use Crypt;

use App\Models\Jenis;

class JenisController extends Controller
{
    public function index()
    {
        return view('backend.operator.jenis.index')->withTitle('Kategori PMW');
    }

    /* AJAX request */
    public function getData(Request $request){

        ## Read value
        $draw = $request->get('draw');
        $start = $request->get("start");
        $rowperpage = $request->get("length"); // Rows display per page

        $columnIndex_arr = $request->get('order');
        $columnName_arr = $request->get('columns');
        $order_arr = $request->get('order');
        $search_arr = $request->get('search');

        $columnIndex = $columnIndex_arr[0]['column']; // Column index
        $columnName = $columnName_arr[$columnIndex]['data']; // Column name
        $columnSortOrder = $order_arr[0]['dir']; // asc or desc
        $searchValue = strtoupper($search_arr['value']); // Search value

        // Total records
        $statementGlobal = " STATUS_HAPUS = '0' ";
        $totalRecords = Jenis::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $statement = " AND (UPPER(NAMA) LIKE '%".$searchValue."%') ";

        $totalRecordswithFilter =   Jenis::select('count(1) as allcount')
                                    ->whereRaw($statementGlobal.$statement)->count();

        // Fetch records
        $records = Jenis::orderBy($columnName,$columnSortOrder)
            ->whereRaw($statementGlobal.$statement)
            ->select('jenis.*')
            ->skip($start)
            ->take($rowperpage)
            ->get();

        $data_arr = array();
        foreach($records as $record){
            $jenis_id = $record->jenis_id;
            $nama = $record->nama;
            $keterangan = $record->keterangan;

            // $edit  =  route('admin/users/create',$id);
            $edit  =  URL::to('operator/jenis/'.Crypt::encrypt($jenis_id).'/edit');
            $delete = "confirmDelete('".Crypt::encrypt($jenis_id)."')";

            $data_arr[] = array(
                "jenis_id" => $jenis_id,
                "nama" => $nama,
                "keterangan" => $keterangan,
                "aksi" => '<td class="table-action">
                                <a href="'.$edit.'" class="btn btn-icon-sm btn-primary"><i class="fas fa-edit"></i></a>
                                <a href="#!" class="btn btn-icon-sm btn-danger" onclick="'.$delete.'"><i class="fas fa-trash"></i></a>
                            </td>'
            );
        }

        $response = array(
            "draw" => intval($draw),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalRecordswithFilter,
            "aaData" => $data_arr
        );

        echo json_encode($response);
        exit;
    }

    public function create()
    {
        return view('backend.operator.jenis.create')->withTitle('Tambah Kategori PMW');
    }

    public function store(Request $request)
    {
        $uuid = Uuid::generate();
        $data['jenis_id'] = $uuid;
        $data['nama'] = $request->input('nama');
        $data['keterangan'] = $request->input('keterangan');
        // BACKUP NVN
        // $data['created_user'] = Auth::user()->name;

        if(Jenis::create($data))
        {
            return redirect()->route('operator.jenis.index')->with('successMessage', 'Data berhasil disimpan.');
        }
        else
        {
            return redirect()->route('operator.jenis.index')->with('errorMessage', 'Data gagal disimpan.');
        }
    }

    public function edit($id)
    {
        $jenis = Jenis::where('jenis_id', '=', Crypt::decrypt($id))->get();

        $data = [
            'jenis' => $jenis,
            'encrypted_id' => $id,
        ];

        return view('backend.operator.jenis.edit', compact('data'))->withTitle('Ubah Kategori PMW');
    }

    public function update(Request $request, $id)
    {
        $data['nama'] = $request->input('nama');
        $data['keterangan'] = $request->input('keterangan');

        $jenis = Jenis::where('jenis_id', Crypt::decrypt($id))->firstOrFail();
        $jenis->update($data);

        return redirect()->route('operator.jenis.index')->with('successMessage', 'Data berhasil diubah.');

    }

    public function destroy($id)
    {
        try {
            $delete = Jenis::where('jenis_id', Crypt::decrypt($id))->update(['status_hapus'=>'1']);

            if ($delete == 1) {
                $status = 'success';
                $message = "Kategori PMW berhasil dihapus.";
            }
            else{
                $status = 'error';
                $message = "Kategori PMW tidak ada.";
            }

            return response()->json([
                'status' => $status,
                'message' => $message,
            ]);

        } catch (\Exception $id) {
            return response()->json([
                'status' => 'error',
                'message' => "Data gagal dihapus.",
            ]);
        }
    }
}
