<?php namespace App\Controllers;
use App\Models\CarsModel;
use App\Models\AdditionalsModel;
define("IMG_PATH", "/home/zadio/cars.zadio.bg/zadio/public/uploads/cars_img");


class CarsController extends BaseController
{
	

   public function index() {

		//var_dump("index");exit;
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		$brand='';
		$status='';
		$role=$session->get('role');
		$data = ['data' => ''];
		$carsModel = new CarsModel();
		$cars=$carsModel->get_all_cars();
		$statuses=$carsModel->get_car_status();
		$brands=$carsModel->get_brands();
		//var_dump($cars);exit;
		
		for($j=0;$j<count($cars);$j++)
		{
			$imgs=$carsModel->get_imgs(($cars[$j])['code']);
			$cnt=count($imgs);
			if($cnt>0)
			{
				($cars[$j])['img']=($imgs[0])['url'];
			}
			else
				($cars[$j])['img']="-";
			
		}
		//var_dump($cars);exit;
		if ($this->request->getMethod()== 'POST')
		{
			
			//set filters
			
			
        }
		
		$data['filter_brand']='';
		$data['filter_status']='';
		
		$data['brands']=$brands;
		$data['statuses']=$statuses;
		$data['cars']=$cars;

		$db = db_connect();
		$query = $db->query('SELECT COUNT(*) as inactive_count FROM cars WHERE status=1');
		$inactiveCars = $query->getRowArray();
		$data['new_cars'] = $inactiveCars['inactive_count'];

		echo view('cars/index', $data);
       
		 
    }

	public function getCarsByStatus($status){
		if ($this->request->isAJAX() && session()->get('id') > 0) {

			$model = new CarsModel();

			if ($status == 'All') {
				$cars = $model->get_all_cars();
			}
			else{
				$cars = $model->getCarsByStatus($status);
			}
			for($j=0;$j<count($cars);$j++)
			{
				$imgs=$model->get_imgs(($cars[$j])['code']);
				$cnt=count($imgs);
				if($cnt>0)
				{
					($cars[$j])['img']=($imgs[0])['url'];
				}
				else
					($cars[$j])['img']="-";
				
			}

			return $this->response->setJSON([
				'cars' => $cars,
				'count' => count($cars)
			]);
		}
		return $this->response->setStatusCode(400, 'Bad Request');

	}
	
	public function cardetails($code){
        
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		
		$data = ['data' => ''];
		$carsModel = new CarsModel();
		$data['car']=$carsModel->get_by_code($code);
		$carimgs=$carsModel->get_imgs($code);
		$data['imgs']=$carimgs;
		//var_dump($data['car']);exit;
		echo view('cars/cardetails',$data);
	}
    
    	
	
   public function edit($code = '') {
	    //var_dump("edit");exit;
		//echo "Post";
		$data['data']='';
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     echo "no user";
		 //$this->response->redirect(site_url('/login'));
		 exit;
        }
		$data['models']=array();
		
		$carsModel = new CarsModel();
		$statuses=$carsModel->get_car_status();
		$brands=$carsModel->get_brands();
		$countries=$carsModel->get_country();
		$data['brands']=$brands;
		$data['statuses']=$statuses;
		$data['countries']=$countries;
		$data["car"]=null;
		$data['title'] = "Edit car";
        $data["code"] = $code;
        $data["edit"] = false;
		//Get form json_decode
		
		$db = db_connect();
		$sqlstr="SELECT  `json`  FROM `additionals_form` limit 1";
		$query=$db->query($sqlstr);
		$addArr=$query->getResult('array');
		$obj=$addArr[0];
		
		$data['additionals_form']=$obj['json'];
		//var_dump($data['additionals_form']);exit;
				
        if ($code) {
			//existing car
			$data["code"] = $code;
			$data["edit"] = true;
			$data['title'] = "Edit car";
			
			$carobj=$carsModel->get_all_by_code($code);
			if(count($carobj)>0)
			{
				$data["car"] = $carobj[0];
				$carimgs=$carsModel->get_imgs($code);
				$crtbrand=($carobj[0])['brand'];
				$sqlstr="SELECT  `model_name`  FROM `car_model` WHERE  `brand`='".$crtbrand."' and active=1";
				$query=$db->query($sqlstr);
			
				$models=$query->getResult('array');
				$data['models']=$models;
				$data["car"] = $carobj[0];
				$data["imgs"] = $carimgs;
			}
			else
			{	
				$models=array();
				
			}
				
        }
		else
		{
			//new car
			$data['models']=array();
			$code=RandString(9);
			$data["code"]='CAR'.$code;
			
		}	
		if ($this->request->getMethod() != 'POST')
		{
			
			echo view('cars/edit',$data);
			
        } 
		else 
		{
			if($this->request->getVar('status')==3)
				$status=3;
			else
				$status=0;
			//SAVE primary details
			$newData = [
			'code'=> $code,
			'price_bgn' => $this->request->getVar('price_bgn'),
			'brand' => $this->request->getVar('brand'),
			'model' => $this->request->getVar('model'),
			'model_dec' => $this->request->getVar('model_dec'),
			'body_type' => $this->request->getVar('body_type'),
			'steering_whell' => $this->request->getVar('steering_whell'),
			'cubic_capacity' => $this->request->getVar('cubic_capacity'),
			'engine_power_kw' => $this->request->getVar('engine_power_kw'),
			'engine_power_hp' => $this->request->getVar('engine_power_hp'),
			'fuel' => $this->request->getVar('fuel'),
			'emission_standard' => $this->request->getVar('emission_standard'),
			'date_manufacture' => $this->request->getVar('date_manufacture'),
			'gear_box' => $this->request->getVar('gearbox'),
			'drivetrain' => $this->request->getVar('drivetrain'),
			'km' => $this->request->getVar('km'),
			'vin' => $this->request->getVar('vin'),
			'technical_status' => $this->request->getVar('technical_status'),
			'registered' => $this->request->getVar('registered'),
			'country_of_origin' => $this->request->getVar('country_of_origin'),
			'notes' => $this->request->getVar('notes'),
			'additionals' => $this->request->getVar('additionals'),
			'status'=>$status,
			'updated_at' =>date('Y-m-d H:i:s')
			];
			
			//var_dump($newData);exit;
			$carsModel->save_data($newData);
			
			//SEND mail
			if($status==1)
			{

				// TODO: Discuss if approving a car is actually implemented and then uncomment this code.
				// // Prepare dynamic data
				// $email_data = [
				// 	'carbrand'    => $this->request->getVar('brand'),
				// 	'code'     => $code,
				// 	'carvin'      => $this->request->getVar('vin'),
				// 	'user_car_url' => 'https://cars.zadio.bg/cars/edit/' . $code,
				// ];

				// $msg = view('emails/car_publishing_approved', $email_data);
				
				// // Send email to user
				// $email = service('email');
				// $email->setTo($this->request->getVar('email'));
				// $email->setSubject('Car publishing approved!');
				// $email->setMessage($msg);
				// $email->send();



				$libpath=realpath(dirname(__DIR__) . '/..');
				include_once $libpath.'/send_smtp.php';
				$msg='Ad code:' .$code.'<br>';
				sendMyMsg('edi.hermann@lemonbyte.ro','cars@zadio.bg','New ad publish request in cars.zadio.bg',$msg);
				sendMyMsg('cars@zadio.bg','cars@zadio.bg','New ad publish request in cars.zadio.bg',$msg);
			}
			
			$this->response->redirect(site_url('/cars/edit/'.$code));
			session()->setFlashdata('success', 'Car data was saved.');
			//echo view('cars/edit',$data);
        }
    }
	
	public function additionals($code='')
    {
	    $data['data']='';
		$session = session();
		$usr = session()->get('id');
		$model = new AdditionalsModel();
		
        if (!$usr>0) 
		{
	     echo "no user";
		 //$this->response->redirect(site_url('/login'));
		 exit;
        }
		if(!$code)
		{
			exit;
		}
        $data["code"] = $code;
		if ($this->request->getMethod() == 'POST') 
		{
			$fieldsArr=$this->request->getVar();
			//var_dump($this->request->getVar());
			$obj=array();
			foreach ($fieldsArr as $key => $value)
			{
				if($value)
					array_push($obj, array($key=>$value));
				
			}
			//var_dump($obj);
			//exit;
			
			$newData = [
			'car_code'=> $code,
			'client_id'=> $usr,
			'additionals' => json_encode($obj),
			'updated_at'=>date('Y-m-d H:i:s')
			];
			
							
			$model->save_data($newData);
		}	
        
   }
   
   	
	public function brandmodels(){
        
		//log_message('error', 'Ajax call');
        $brand=$this->request->getVar('brand');
		log_message('error', 'Value of brand is '.$brand);
		
		$db = db_connect();
		$sqlstr="SELECT  `model_name`  FROM `car_model` WHERE  `brand`='$brand' and active=1";
		log_message('error',$sqlstr);
		$query=$db->query($sqlstr);
		
		echo(json_encode($query->getResult('array')));
		exit;
	}
	
    public function uploadimg($code='')
    {
	    //1.Create folder if not exists
	   
	    $dirfile=IMG_PATH.'/'.$code;
		if (!file_exists($dirfile)) {
			mkdir($dirfile, 0777, true);
		}
		//echo "{'error':'".$dirfile."'}";
		//exit;
		$db = db_connect();
	   
	    //2.upload files
		$sort=0;
		foreach($_FILES as $file)
		{
			$date=date('dmyGis');
			$new_file_name=$date.$file["name"];
			
		    //echo $file['tmp_name'].'</br>'; 
			$traget_path=$dirfile."/".$file["name"];
			$short_path= $code."/".$file["name"];
			if(move_uploaded_file($file['tmp_name'], $dirfile."/".$file["name"]))
		    {
		    //3.insert into car_images
				$sort=$sort+1;
				$sqlstr="INSERT INTO `car_images` (`car_code`, `url`, `sort`) VALUES ( '$code','$short_path',$sort )";
				$db->query($sqlstr);
				$sort=$sort+1;
			}
			else
			{
				$retval=  array('error'=>'Upload fail');
				echo json_encode($retval);
				exit;
			}
		
		}
		/*   
		  $retval=
		   array(
				'error'=>'An error exception message if applicable',
				'initialPreview'=> array(),
				'initialPreviewConfig'=> array(),
				'initialPreviewThumbTags'=> array(),
				'append'=> true // whether to append content to the initial preview (or set false to overwrite)
			);
	
		*/
		
		//echo "{'error': 'You are not allowed to upload such a file.'}";
		echo "{}";
		exit;
			   
	  // var_dump($_FILES['img_data']);exit;
	   
   }
   
   public function delimg($id)
   {
	   if($id>0 and is_numeric($id))
	   {
			$db = db_connect();
			$sqlstr="DELETE FROM `car_images` WHERE id=$id";
			$db->query($sqlstr);
			echo "{}";
			exit;
	   }
   }
	
   public function askremove($id = -1) {
		$data = [];
		$data['data']='';
		$orderModel = new OrderModel();
        $crtord=$orderModel->get_by_id($id);
        $data["id"] = $crtord["id"];
        $data["controller"] = "orders";
        $data["desc"] = $crtord["order_num"];
		
		
		echo view('orders/askremove', $data);
		
			
		
    }
	public function remove($id = -1) {
		$orderModel = new OrderModel();
       		
        if ($orderModel->remove($id)) {
            $this->response->redirect(site_url('/orders'));
			
        }
    }
}



function RandString($length = 10) {
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
}
