<?php

namespace App\Http\Controllers;

use App\Models\Purchase_request\ListPr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\User;

use Validator;
use Helper;
use DB;
use Hashids;
use Session;

class FetchController extends Controller
{
	private $pagetitle = 'Fetch Controller';
	private $route     = 'fetch';
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
		$data['pagetitle']  = $this->pagetitle;
		$data['breadcrumb'] = [$this->pagetitle => route($this->route.'.create')];
		$data['route']      = $this->route;

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


    //security yang telah di kembangkan
    public function globalfetch(Request $param )
    {
        DB::enableQueryLog();
        $q          = $param->post('q');
        $parameter  = $param->post('parameter');
        $query      = DB::table(decrypt($parameter['t']));
        $except     = $param->post('except');
        $onlyin     = $param->post('onlyin');
        $select     = explode(',', decrypt($parameter['s']));
        // dd($parameter);

        $query->select($select);

        if (@$parameter['j'] != '' && @$parameter['j'] != NULL) {
            foreach ($parameter['j'] as $key => $value) {
                if ($value['type'] == 'inner') {
                    $query->join($value['t'] ,$value['fieldA'], $value['operator'], $value['fieldB']);
                }elseif ($value['type'] == 'left') {
                    $query->leftJoin($value['t'] ,$value['fieldA'], $value['operator'], $value['fieldB']);
                }elseif ($value['type'] == 'right') {
                    $query->rightJoin($value['t'] ,$value['fieldA'], $value['operator'], $value['fieldB']);
                }
            }
        }
        if (@$parameter['w'] != '' && @$parameter['w'] != NULL) {
            foreach ($parameter['w'] as $key => $value) {
                // print_r($value['value']);exit();
                $likeornot = '';
                $thefield  = '';
                if ($value['operator'] == 'LIKE' || $value['operator'] == 'Like' || $value['operator'] == 'like' ||
                    $value['operator'] == 'ILIKE' || $value['operator'] == 'Ilike' || $value['operator'] == 'ilike') {
                    $likeornot = '%';
                }
                if (strpos($value['field'], 'select-index-') !== false) {
                    $thefield  = $select[str_replace('select-index-', '', $value['field'])];
                }else{
                    $thefield  = decrypt($value['field']);
                }
                $query->where($thefield, $value['operator'], $likeornot.($value['value'] == '-NMSearch-' ? $q : $value['value']).$likeornot);
            }
        }

        $id        = explode(',', decrypt($parameter['s']) );
        $exceptarr = explode(',', $except);
        if ($except != '') {
            $query->whereNOTIn($id[0],array_filter($exceptarr));
        }

        $onlyinarr = explode(',', $onlyin);
        $onlyinarr = array_filter($onlyinarr);
        foreach ($onlyinarr as $key => $value) {
            $onlyinarr[$key] = Hashids::decode($value)[0];
        }
        if ($onlyin != '') {
            $query->whereIn($id[0],array_filter($onlyinarr));
        }
        // $query->where(decrypt($value['field']), $value['operator'], $value);

        $query->offset((@$parameter['field'] != '' && @$parameter['field'] != NULL ? $parameter['field'] : 0));
        $query->limit((@$parameter['field'] != '' && @$parameter['field'] != NULL ? $parameter['field'] : 5));

        $result = $query->get();
        // print_r(
        //    DB::getQueryLog()
        // );
        // print_r($result);exit();
        
        $data = array();
        $i    = 0;
        foreach ($result as $keyres => $valueres) {
            $j = 0;
            foreach (explode(',', decrypt($parameter['s']) ) as $key => $value) {
                if ($j == 0) {
                    $data[$i]['id'] = $valueres->{$value};
                }elseif($j == 1){
                    $data[$i]['text'] = $valueres->{$value};
                }else{
                    $data[$i][$value] = $valueres->{$value};
                }
                $j++;
            }
            $i++;
        }
        // echo "<pre>";
        // print_r($data);exit();

        echo json_encode( ['item' => $data] );
    }

}
