<?php
namespace App\Controllers;
use Config\Services;

class Geneditor extends BaseController{
    private $dbHandle;

    public function getsourcesandfields(){
        $dataToReturn = [];
        $source = $this->request->getVar('source');
        
        $L = [];
        $L["sources"] = [
            "api1",
			"supplementary",
			"clients"
		];
		$L["fields"] = [
		    "api1" => ["customervin","ABS","ActiveSafetySysNote","AdaptiveCruiseControl","AdaptiveDrivingBeam","AdaptiveHeadlights","AdditionalErrorText","AirBagLocCurtain","AirBagLocFront","AirBagLocKnee","AirBagLocSeatCushion","AirBagLocSide","AutoReverseSystem","AutomaticPedestrianAlertingSound","AxleConfiguration","Axles","BasePrice","BatteryA","BatteryA_to","BatteryCells","BatteryInfo","BatteryKWh","BatteryKWh_to","BatteryModules","BatteryPacks","BatteryType","BatteryV","BatteryV_to","BedLengthIN","BedType","BlindSpotIntervention","BlindSpotMon","BodyCabType","BodyClass","BrakeSystemDesc","BrakeSystemType","BusFloorConfigType","BusLength","BusType","CAN_AACN","CIB","CashForClunkers","ChargerLevel","ChargerPowerKW","CombinedBrakingSystem","CoolingType","CurbWeightLB","CustomMotorcycleType","DaytimeRunningLight","DestinationMarket","DisplacementCC","DisplacementCI","DisplacementL","Doors","DriveType","DriverAssist","DynamicBrakeSupport","EDR","ESC","EVDriveUnit","ElectrificationLevel","EngineConfiguration","EngineCycles","EngineCylinders","EngineHP","EngineHP_to","EngineKW","EngineManufacturer","EngineModel","EntertainmentSystem","ErrorCode","ErrorText","ForwardCollisionWarning","FuelInjectionType","FuelTankMaterial","FuelTankType","FuelTypePrimary","FuelTypeSecondary","GCWR","GCWR_to","GVWR","GVWR_to","KeylessIgnition","LaneCenteringAssistance","LaneDepartureWarning","LaneKeepSystem","LowerBeamHeadlampLightSource","Make","MakeID","Manufacturer","ManufacturerId","Model","ModelID","ModelYear","MotorcycleChassisType","MotorcycleSuspensionType","NCSABodyType","NCSAMake","NCSAMapExcApprovedBy","NCSAMapExcApprovedOn","NCSAMappingException","NCSAModel","NCSANote","NonLandUse","Note","OtherBusInfo","OtherEngineInfo","OtherMotorcycleInfo","OtherRestraintSystemInfo","OtherTrailerInfo","ParkAssist","PedestrianAutomaticEmergencyBraking","PlantCity","PlantCompanyName","PlantCountry","PlantState","PossibleValues","Pretensioner","RearAutomaticEmergencyBraking","RearCrossTrafficAlert","RearVisibilitySystem","SAEAutomationLevel","SAEAutomationLevel_to","SeatBeltsAll","SeatRows","Seats","SemiautomaticHeadlampBeamSwitching","Series","Series2","SteeringLocation","SuggestedVIN","TPMS","TopSpeedMPH","TrackWidth","TractionControl","TrailerBodyType","TrailerLength","TrailerType","TransmissionSpeeds","TransmissionStyle","Trim","Trim2","Turbo","VIN","ValveTrainDesign","VehicleDescriptor","VehicleType","WheelBaseLong","WheelBaseShort","WheelBaseType","WheelSizeFront","WheelSizeRear","WheelieMitigation","Wheels","Windows"],
			"supplementary" => ["vin","vfam","vfamref","vfamlen","wmi","make","model","makecode","modelcode","engdesc","genlen","genfr","gento","yearpos","seriallen","year","module","modulesub","FuelTypePrimary","FuelTypeSecondary","engine","displacementL","DisplacementCC","engineCylinders","englayout","bodytype","seats","doors","TransmissionSpeeds","SeatRows","weightg","weightn","EngineHP","DriveType","Manufacturer","PlantCountry","PlantCity","PlantCompanyName","PlantCountrycode","TransmissionStyle","Transmissiontype","ValveTrainDesign","datasource","note"],
			"clients" => ["firstname","phone","whatsapp","region","town","district","address","password","note","personnel","transactdate"]
		];
		
		if($source !=''){
		    $L["sources"] = [$source];
		    $L["fields"] = [$source => $L["fields"][$source]];
		}
        
        $dataToReturn['status'] = 0;
        $dataToReturn['load'] = $L;

        return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
    }
    
    public function getsourcerows(){
        $this->dbHandle   = \Config\Database::connect();
        $dataToReturn = [];
        
        $bod = [
            "source" => $this->request->getVar('source'),
            "parnames" => $this->request->getVar('parnames'),
            "parvalues" => $this->request->getVar('parvalues'),
            "picks" => $this->request->getVar('picks'),
            "limit" => $this->request->getVar('limit'),
            "offset" => $this->request->getVar('offset')
        ];
        
        $selectclause = '';
        $whereclause = '';
        $limitclause = " limit " . $bod['limit'] . " offset " . $bod['offset'];
        $countclause = '';

    	if($bod['parnames'] != ""){
    		$whereclause = " where " . $this->toDBParams_and_like($bod['parnames'], $bod['parvalues']);
    	}
    	if($bod['picks'] == ""){
    		$selectclause = "select * from " . $bod['source'] . $whereclause . $limitclause;
    	}else{
    		$selectclause = "select " . implode(',',$bod['picks']) . " from " . $bod['source'] . $whereclause . $limitclause;
    	}
    	$countclause = "select count(*) as 'totalrows' from " . $bod['source'] . $whereclause;
    	
    	$R = $this->dbHandle->query($selectclause);
    	$R2 = $this->dbHandle->query($countclause);
    	
    	if( $R->getNumRows()>0 ){
            $dataToReturn['status'] = 0;
            $dataToReturn['load'] = $R->getResultArray();
            $dataToReturn['total'] = $R2->getResultArray()[0]['totalrows'];
        }else{
            $dataToReturn['status'] = 1;
        }

        return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
    }
    
    public function updatefield(){
        $this->dbHandle   = \Config\Database::connect();
        $dataToReturn = [];
        
        $bod = [
            "source" => $this->request->getVar('source'),
            "id" => $this->request->getVar('id'),
            "field" => $this->request->getVar('field'),
            "value" => $this->request->getVar('value')
        ];
        
        $R = $this->dbHandle->query("update `".$bod['source']."` set `".$bod['field']."`='".$bod['value']."' where `id`='".$bod['id']."'");
        $E = $this->dbHandle->error()['code'];
    	
    	if( $E == 0 ){
            $dataToReturn['status'] = 0;
            $dataToReturn['load'] = $bod['value'];
        }else{
            $dataToReturn['status'] = 1;
        }

        return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
    }
    
    private function uuidv4(){
      $data = random_bytes(16);
    
      $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
      $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
        
      return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    
    // private function toDBParams_and($params, $values){
    //   $ar = explode(',', $params); $ar2 = explode(',', $values);
    //   $ret = '';
    //   for($i = 0; $i < count($ar); $i++){ $ret .= " and `" . $ar[$i] . "`=' . $ar2[$i] . '"; }
    //   return substr($ret, 5);
    // }
    
    private function toDBParams_and_like($params, $values){
      $ar = explode(',', $params); $ar2 = explode(',', $values);
      $ret = '';
      for($i = 0; $i < count($ar); $i++){ $ret .= " and `" . $ar[$i] . "` like '%" . $ar2[$i] . "%'"; }
      return substr($ret, 5);
    }
    
    private function toDBParams_and($params, $values){
      $ar = explode(',', $params); $ar2 = explode(',', $values);
      $ret = '';
      for($i = 0; $i < count($ar); $i++){ $ret .= " and `" . $ar[$i] . "` = '" . $ar2[$i] . "'"; }
      return substr($ret, 5);
    }
    
    public function loaddata(){
        $this->dbHandle   = \Config\Database::connect();
        $dataToReturn = [];
        
        $bod = [
            "source" => $this->request->getVar('source'),
            "picks" => $this->request->getVar('picks'),
            "parnames" => $this->request->getVar('parnames'),
            "parvalues" => $this->request->getVar('parvalues'),
            "order" => $this->request->getVar('order')
        ];
        
    	$selectclause = '';
    	$whereclause = '';
    	$orderclause = '';
    
    	if($bod['order'] != ""){
    		$orderclause = " ".$bod['order'];
    	}
    	if($bod['parnames'] != ""){
    		$whereclause = " where " . $this->toD1Params_and($bod['parnames']);
    	}
    	if($bod['picks'] == ""){
    		$selectclause = "select * from " . $bod['source'] . $whereclause . $orderclause;
    	}else{
    		$selectclause = "select " . $bod['picks'] . " from " . $bod['source'] . $whereclause . $orderclause;
    	}
    
    	$R = $this->dbHandle->query($selectclause);
    	if( $R->getNumRows()>0 ){
            $dataToReturn['status'] = 0;
            $dataToReturn['load'] = $R->getResultArray();
        }else{
            $dataToReturn['status'] = 1;
        }

        return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
    }
/*
import { v4 as uuidv4 } from 'uuid';
export const toHolesThenPegsList = (obj: any): any[] => {
  let keysStr = '';
  let placeholdersStr = '';
  let values: any[] = [];
  let keys = Object.keys(obj.payload);
  for(var i = 0; i < keys.length; i++){
    keysStr += "," + keys[i];
    placeholdersStr += ",?" + (i+1);

    switch(keys[i]){
      case "eid": switch(obj.destination){
        case "ingredients": values[i] = 'ing-' + uuidv4(); break;
        case "snacks": values[i] = 'sna-' + uuidv4(); break;
        case "meals": values[i] = 'mea-' + uuidv4(); break;
        default: values[i] = uuidv4();
      }; break;

      case "datestamp": switch(obj.destination){
        default: values[i] = Date.now();
      }; break;

      default: values[i] = obj.payload[keys[i]];
    }
  }
  return [keysStr.substring(1), placeholdersStr.substring(1), values];
}
*/

}