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

class Getvehiclebyvin extends BaseController{
    private $dbHandle;

    public function index(){
        $this->dbHandle = \Config\Database::connect();
        $dataToReturn = [];
        $dataToReturn['load'] = [];
        $modules = [];

        $vin = str_replace(['O','I','-'], ['0','1',''],strtoupper($this->request->getVar('vin')));
        $vl = strlen($vin);

        $dataToReturn['dvin'] = $vin;

        if( $vl == 17){

            //build the 4 types of the vin family
            $m10h = substr($vin,0,8)."*".substr($vin,9,1);
            $m10p = substr($vin,0,10);
            $m9p = substr($vin,0,9);
            $m8p = substr($vin,0,8);

            //find the first matching vfam
            $q10h = "(vfamlen=10 and vfam='".$m10h."')";
            $q10 = "(vfamlen=10 and vfam='".$m10p."')";
            $q9 = "(vfamlen=9 and vfam='".$m9p."')";
            $q8 = "(vfamlen=8 and vfam='".$m8p."')";
            
            //get the first matched vfam
            $R0 = $this->dbHandle->query("select vfam from `3V_supplementary` where {$q10h} or {$q10} or {$q9} or {$q8} order by vfam desc limit 1");
            if( $R0->getNumRows()>0 ){
                $matchfam = $R0->getResultArray()[0]['vfam'];
                
                $R = $this->dbHandle->query("select vfam, vfamlen, modulesub, module, make, makecode, model, modelcode, vinyear as 'year', engine, englayout, fueltypeprimary, displacementcc, enginecylinders, engdesc, genfr, gento, yearpos, bodytype, seats, doors 
                from `3V_supplementary` where vfam='{$matchfam}' group by `modulesub`, `module`, `vfam`, `vfamlen`, `make`, `makecode`, `model`, `modelcode`, `vinyear`, `engine`, `englayout`, `fueltypeprimary`, `displacementcc`, `enginecylinders`, `engdesc`, `genfr`, `gento`, `yearpos`, `bodytype`, `seats`, `doors` 
                order by vfamlen DESC, module ASC");
                
            }else{
                
                //ERROR - VIN NOT FOUND
                $dataToReturn['status'] = 3;
                $dataToReturn['extra'] = "na_vin";
                $dataToReturn['load'] = ["vin"=>$vin];
                $this->downloadVINInfo($vin);
                return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
            }

        } else if( $vl >= 7 && $vl <= 14){

            //build the types of the vin family
            $m7p = substr($vin,0,7);
            $m6p = substr($vin,0,6);
            $m5p = substr($vin,0,5);
            $m4p = substr($vin,0,4);
            $m3p = substr($vin,0,3);

            //find the first matching vfam
            $q7 = "(vfamlen=7 and (vfam='".$m7p."'))";
            $q6 = "(vfamlen=6 and (vfam='".$m6p."'))";
            $q5 = "(vfamlen=5 and (vfam='".$m5p."'))";
            $q4 = "(vfamlen=4 and (vfam='".$m4p."'))";
            $q3 = "(vfamlen=3 and (vfam='".$m3p."'))";
            
            //get the first matched vfam
            $R0 = $this->dbHandle->query("select vfam from `3V_supplementary` where {$q7} or {$q6} or {$q5} or {$q4} or {$q3} order by vfam desc limit 1");
            if( $R0->getNumRows()>0 ){
                $matchfam = $R0->getResultArray()[0]['vfam'];
                
                $R = $this->dbHandle->query("select vfam, vfamlen, modulesub, module, make, model, vinyear as 'year', engine, englayout, fueltypeprimary, displacementcc, enginecylinders, engdesc, genfr, gento, yearpos, bodytype, seats, doors 
                from `3V_supplementary` where vfam='{$matchfam}' group by `modulesub`, `module`, `vfam`, `vfamlen`, `make`, `model`, `vinyear`, `engine`, `englayout`, `fueltypeprimary`, `displacementcc`, `enginecylinders`, `engdesc`, `genfr`, `gento`, `yearpos`, `bodytype`, `seats`, `doors` 
                order by vfamlen DESC, module ASC");
                
            }else{
                
                //ERROR - VIN NOT FOUND
                $dataToReturn['status'] = 3;
                $dataToReturn['extra'] = "na_vin";
                $dataToReturn['load'] = ["vin"=>$vin];
                $this->downloadVINInfo($vin);
                return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
            }

        } else {

            //ERROR
            $dataToReturn['status'] = 1;
            $dataToReturn['extra'] = "Incorrect VIN Length";
            return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
        }
            
        if( $R->getNumRows()>0 ){
            $dataToReturn['status'] = 0;

            foreach($R->getResultArray() as $W){
                $modules[] = $W['module'];
                $module = $W['module'];
                $vfam = $W['vfam'];
                $yearpos = $W['yearpos'];
                $genfr = $W['genfr'];
                $gento = $W['gento'];
                $modulesub = $W['modulesub'];
                $W['years'] = [];
                
                $W['photo'] = $this->getPhoto(strtolower($W['modulesub']), $W['vfam']);
                
                switch(strtolower($W['module'])){
                    case "mo":
                        $yearfound = false;
                        $yearsym = substr($vin, $yearpos-1, 1);
                        $R2 = $this->dbHandle->query("select `year` from `3V_moyear` where `yearsym` = '{$yearsym}' and (`year` >= '{$genfr}' and `year` <= '{$gento}')");
                        
                        if( $R2->getNumRows()>0 ){
                            $yearfound = true;
                            $W2 = $R2->getResultArray()[0];
                            $W['years'][] = ["year" => $W2['year']];
                        }
                        
                        if(!$yearfound){
                            //use the applicable range
                            for($i = $genfr; $i <= $gento; $i++){
                                $W['years'][] = ["year" => $i];
                            }
                        }
                        break;
                    
                    case "ma":
                        $yearfound = false;
                        $series = str_replace($vfam,"",$vin);
                        $series = str_replace("-","",$series);

                        if( substr($modulesub, 0, 3) === "shc") $dataToReturn['dvin'] = $vfam .'-'. $series;
                        
                        $R2 = $this->dbHandle->query("select `year` from `3V_mayt` where (`serialfr` <= '{$series}' and `serialto` >= '{$series}') and `vfam` = '{$vfam}' and `modulesub` = '{$modulesub}' and `year` > 0");
                        if( $R2->getNumRows()>0 ){
                            $yearfound = true;
                            $W2 = $R2->getResultArray()[0];
                            $W['years'][] = ["year" => $W2['year']];
                        }
                        
                        if(!$yearfound){
                            //get the applicable range
                            $R2 = $this->dbHandle->query("select `genfr`, `gento` from `3V_mayt` where `vfam` = '{$vfam}' and `genfr` > 0");
                            if( $R2->getNumRows()>0 ){
                                $yearfound = true;
                                $W2 = $R2->getResultArray()[0];
                                for($i = $W2['genfr']; $i <= $W2['gento']; $i++){
                                    $W['years'][] = ["year" => $i];
                                }
                            }
                        }
                        break;
                }
                
                $dataToReturn['load'][] = $W;
            }

            $dataToReturn['modules'] = $modules;
            
        }else{
            
            //ERROR - VIN NOT FOUND
            $dataToReturn['status'] = 3;
            $dataToReturn['extra'] = "na_vin";
            $dataToReturn['load'] = ["vin"=>$vin];
            $this->downloadVINInfo($vin);
            return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
        }

        return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
    }

    private function getPhoto($source, $ref){
        $pic = str_replace('.jpg', '', $ref);
        $photo = base_url("assets/vphotos/{$source}/nophoto.jpg");

        $potfile = "/home/omvparts/public_html/assets/vphotos/{$source}/{$pic}.jpg";
        if(file_exists($potfile)){
            $photo = base_url("assets/vphotos/{$source}/{$pic}.jpg");
        }
        return $photo;
    }
    
    private function downloadVINInfo($vin){
        //check if necessary first
        if($this->dbHandle->query("select vin from `api1` where customervin = '{$vin}' limit 1")->getNumRows() < 1){
            $url = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/".$vin."?format=json";
    		$dat = [];
    		$res = json_decode($this->callAPI('GET', $url, json_encode($dat)), true)['Results'][0];
    		
    		$data = [
    		    "customervin"                           => $vin,
                "ABS"                                   => $res["ABS"],
                "ActiveSafetySysNote"                   => $res["ActiveSafetySysNote"],
                "AdaptiveCruiseControl"                 => $res["AdaptiveCruiseControl"],
                "AdaptiveDrivingBeam"                   => $res["AdaptiveDrivingBeam"],
                "AdaptiveHeadlights"                    => $res["AdaptiveHeadlights"],
                "AdditionalErrorText"                   => $res["AdditionalErrorText"],
                "AirBagLocCurtain"                      => $res["AirBagLocCurtain"],
                "AirBagLocFront"                        => $res["AirBagLocFront"],
                "AirBagLocKnee"                         => $res["AirBagLocKnee"],
                "AirBagLocSeatCushion"                  => $res["AirBagLocSeatCushion"],
                "AirBagLocSide"                         => $res["AirBagLocSide"],
                "AutoReverseSystem"                     => $res["AutoReverseSystem"],
                "AutomaticPedestrianAlertingSound"      => $res["AutomaticPedestrianAlertingSound"],
                "AxleConfiguration"                     => $res["AxleConfiguration"],
                "Axles"                                 => $res["Axles"],
                "BasePrice"                             => $res["BasePrice"],
                "BatteryA"                              => $res["BatteryA"],
                "BatteryA_to"                           => $res["BatteryA_to"],
                "BatteryCells"                          => $res["BatteryCells"],
                "BatteryInfo"                           => $res["BatteryInfo"],
                "BatteryKWh"                            => $res["BatteryKWh"],
                "BatteryKWh_to"                         => $res["BatteryKWh_to"],
                "BatteryModules"                        => $res["BatteryModules"],
                "BatteryPacks"                          => $res["BatteryPacks"],
                "BatteryType"                           => $res["BatteryType"],
                "BatteryV"                              => $res["BatteryV"],
                "BatteryV_to"                           => $res["BatteryV_to"],
                "BedLengthIN"                           => $res["BedLengthIN"],
                "BedType"                               => $res["BedType"],
                "BlindSpotIntervention"                 => $res["BlindSpotIntervention"],
                "BlindSpotMon"                          => $res["BlindSpotMon"],
                "BodyCabType"                           => $res["BodyCabType"],
                "BodyClass"                             => $res["BodyClass"],
                "BrakeSystemDesc"                       => $res["BrakeSystemDesc"],
                "BrakeSystemType"                       => $res["BrakeSystemType"],
                "BusFloorConfigType"                    => $res["BusFloorConfigType"],
                "BusLength"                             => $res["BusLength"],
                "BusType"                               => $res["BusType"],
                "CAN_AACN"                              => $res["CAN_AACN"],
                "CIB"                                   => $res["CIB"],
                "CashForClunkers"                       => $res["CashForClunkers"],
                "ChargerLevel"                          => $res["ChargerLevel"],
                "ChargerPowerKW"                        => $res["ChargerPowerKW"],
                "CombinedBrakingSystem"                 => $res["CombinedBrakingSystem"],
                "CoolingType"                           => $res["CoolingType"],
                "CurbWeightLB"                          => $res["CurbWeightLB"],
                "CustomMotorcycleType"                  => $res["CustomMotorcycleType"],
                "DaytimeRunningLight"                   => $res["DaytimeRunningLight"],
                "DestinationMarket"                     => $res["DestinationMarket"],
                "DisplacementCC"                        => $res["DisplacementCC"],
                "DisplacementCI"                        => $res["DisplacementCI"],
                "DisplacementL"                         => $res["DisplacementL"],
                "Doors"                                 => $res["Doors"],
                "DriveType"                             => $res["DriveType"],
                "DriverAssist"                          => $res["DriverAssist"],
                "DynamicBrakeSupport"                   => $res["DynamicBrakeSupport"],
                "EDR"                                   => $res["EDR"],
                "ESC"                                   => $res["ESC"],
                "EVDriveUnit"                           => $res["EVDriveUnit"],
                "ElectrificationLevel"                  => $res["ElectrificationLevel"],
                "EngineConfiguration"                   => $res["EngineConfiguration"],
                "EngineCycles"                          => $res["EngineCycles"],
                "EngineCylinders"                       => $res["EngineCylinders"],
                "EngineHP"                              => $res["EngineHP"],
                "EngineHP_to"                           => $res["EngineHP_to"],
                "EngineKW"                              => $res["EngineKW"],
                "EngineManufacturer"                    => $res["EngineManufacturer"],
                "EngineModel"                           => $res["EngineModel"],
                "EntertainmentSystem"                   => $res["EntertainmentSystem"],
                "ErrorCode"                             => $res["ErrorCode"],
                "ErrorText"                             => $res["ErrorText"],
                "ForwardCollisionWarning"               => $res["ForwardCollisionWarning"],
                "FuelInjectionType"                     => $res["FuelInjectionType"],
                "FuelTankMaterial"                      => $res["FuelTankMaterial"],
                "FuelTankType"                          => $res["FuelTankType"],
                "FuelTypePrimary"                       => $res["FuelTypePrimary"],
                "FuelTypeSecondary"                     => $res["FuelTypeSecondary"],
                "GCWR"                                  => $res["GCWR"],
                "GCWR_to"                               => $res["GCWR_to"],
                "GVWR"                                  => $res["GVWR"],
                "GVWR_to"                               => $res["GVWR_to"],
                "KeylessIgnition"                       => $res["KeylessIgnition"],
                "LaneCenteringAssistance"               => $res["LaneCenteringAssistance"],
                "LaneDepartureWarning"                  => $res["LaneDepartureWarning"],
                "LaneKeepSystem"                        => $res["LaneKeepSystem"],
                "LowerBeamHeadlampLightSource"          => $res["LowerBeamHeadlampLightSource"],
                "Make"                                  => $res["Make"],
                "MakeID"                                => $res["MakeID"],
                "Manufacturer"                          => $res["Manufacturer"],
                "ManufacturerId"                        => $res["ManufacturerId"],
                "Model"                                 => $res["Model"],
                "ModelID"                               => $res["ModelID"],
                "ModelYear"                             => $res["ModelYear"],
                "MotorcycleChassisType"                 => $res["MotorcycleChassisType"],
                "MotorcycleSuspensionType"              => $res["MotorcycleSuspensionType"],
                "NCSABodyType"                          => $res["NCSABodyType"],
                "NCSAMake"                              => $res["NCSAMake"],
                "NCSAMapExcApprovedBy"                  => $res["NCSAMapExcApprovedBy"],
                "NCSAMapExcApprovedOn"                  => $res["NCSAMapExcApprovedOn"],
                "NCSAMappingException"                  => $res["NCSAMappingException"],
                "NCSAModel"                             => $res["NCSAModel"],
                "NCSANote"                              => $res["NCSANote"],
                "NonLandUse"                            => $res["NonLandUse"],
                "Note"                                  => $res["Note"],
                "OtherBusInfo"                          => $res["OtherBusInfo"],
                "OtherEngineInfo"                       => $res["OtherEngineInfo"],
                "OtherMotorcycleInfo"                   => $res["OtherMotorcycleInfo"],
                "OtherRestraintSystemInfo"              => $res["OtherRestraintSystemInfo"],
                "OtherTrailerInfo"                      => $res["OtherTrailerInfo"],
                "ParkAssist"                            => $res["ParkAssist"],
                "PedestrianAutomaticEmergencyBraking"   => $res["PedestrianAutomaticEmergencyBraking"],
                "PlantCity"                             => $res["PlantCity"],
                "PlantCompanyName"                      => $res["PlantCompanyName"],
                "PlantCountry"                          => $res["PlantCountry"],
                "PlantState"                            => $res["PlantState"],
                "PossibleValues"                        => $res["PossibleValues"],
                "Pretensioner"                          => $res["Pretensioner"],
                "RearAutomaticEmergencyBraking"         => $res["RearAutomaticEmergencyBraking"],
                "RearCrossTrafficAlert"                 => $res["RearCrossTrafficAlert"],
                "RearVisibilitySystem"                  => $res["RearVisibilitySystem"],
                "SAEAutomationLevel"                    => $res["SAEAutomationLevel"],
                "SAEAutomationLevel_to"                 => $res["SAEAutomationLevel_to"],
                "SeatBeltsAll"                          => $res["SeatBeltsAll"],
                "SeatRows"                              => $res["SeatRows"],
                "Seats"                                 => $res["Seats"],
                "SemiautomaticHeadlampBeamSwitching"    => $res["SemiautomaticHeadlampBeamSwitching"],
                "Series"                                => $res["Series"],
                "Series2"                               => $res["Series2"],
                "SteeringLocation"                      => $res["SteeringLocation"],
                "SuggestedVIN"                          => $res["SuggestedVIN"],
                "TPMS"                                  => $res["TPMS"],
                "TopSpeedMPH"                           => $res["TopSpeedMPH"],
                "TrackWidth"                            => $res["TrackWidth"],
                "TractionControl"                       => $res["TractionControl"],
                "TrailerBodyType"                       => $res["TrailerBodyType"],
                "TrailerLength"                         => $res["TrailerLength"],
                "TrailerType"                           => $res["TrailerType"],
                "TransmissionSpeeds"                    => $res["TransmissionSpeeds"],
                "TransmissionStyle"                     => $res["TransmissionStyle"],
                "Trim"                                  => $res["Trim"],
                "Trim2"                                 => $res["Trim2"],
                "Turbo"                                 => $res["Turbo"],
                "VIN"                                   => $res["VIN"],
                "ValveTrainDesign"                      => $res["ValveTrainDesign"],
                "VehicleDescriptor"                     => $res["VehicleDescriptor"],
                "VehicleType"                           => $res["VehicleType"],
                "WheelBaseLong"                         => $res["WheelBaseLong"],
                "WheelBaseShort"                        => $res["WheelBaseShort"],
                "WheelBaseType"                         => $res["WheelBaseType"],
                "WheelSizeFront"                        => $res["WheelSizeFront"],
                "WheelSizeRear"                         => $res["WheelSizeRear"],
                "WheelieMitigation"                     => $res["WheelieMitigation"],
                "Wheels"                                => $res["Wheels"],
                "Windows"                               => $res["Windows"]
    		];
    		
    		$this->dbHandle->table('api1')->insert($data);
        }
	}
    
    private function callAPI($method, $url, $dat){
		$C = curl_init();
		switch($method){
		    case "GET":
			curl_setopt($C, CURLOPT_HTTPGET, 1);
			//if($dat) curl_setopt($C, CURLOPT_POSTFIELDS, $dat);
			break;
			
		    case "POST":
			curl_setopt($C, CURLOPT_POST, 1);
			if($dat) curl_setopt($C, CURLOPT_POSTFIELDS, $dat);
			break;

			case "PUT":
			curl_setopt($C, CURLOPT_CUSTOMREQUEST, "PUT");
			if($dat) curl_setopt($C, CURLOPT_POSTFIELDS, $dat);			 					
			break;

			default:
			if($dat) $url = sprintf("%s?%s", $url, http_build_query($dat));
		}

		curl_setopt($C, CURLOPT_URL, $url);
// 		curl_setopt($C, CURLOPT_HTTPHEADER, [
// 			'Authorization: Bearer my_live_sqe1z4089gahj',
// 			'Content-Type: application/json',
// 			'Cache-Control: no-cache'
// 		]);
		curl_setopt($C, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($C, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		
		$res = curl_exec($C); if(!$res){ die("Connection Failure"); }
		curl_close($C);
		return $res;
	}
}