<?php namespace App\Controllers;
use App\Models\CarsModel;
define("IMG_PATH", "D:/xampp/htdocs/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($usr);
		$statuses=$carsModel->get_car_status();
		$brands=$carsModel->get_client_brands($usr);
		//var_dump($cars);exit;
		
		
		$data['filter_brand']=$brands;
		$data['filter_status']=$statuses;
		
		$data['brands']=$brands;
		$data['statuses']=$statuses;
		$data['cars']=$cars;
		echo view('cars/index', $data);
       
		 
    }
	
   
   
   public function edit($code = '') {
	    //var_dump("edit");exit;
		
		$data['data']='';
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     echo "no user";
		 //$this->response->redirect(site_url('/login'));
		 exit;
        }
		$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;
        if ($code) {
			//existing car
			$carobj=$carsModel->get_by_code($code,$usr);
			$carimgs=$carsModel->get_imgs($code);
						
			$data["car"] = $carobj;
			$data["imgs"] = $carimgs;
			$data["code"] = $code;
			$data["edit"] = true;
            $data['title'] = "Edit car";
        }
		else
		{
			//new car
			$code=RandString(9);
			$data["code"]='CAR'.$code;
			
		}	
		if ($this->request->getMethod() != 'post')
		{
			
			echo view('cars/edit',$data);
			
			
        } 
		else 
		{
				
			$data["car"]=null;
			$obj=$this->request->getVar();
			
			////////////////////////////////////////////////////////////////////
			//upload
			////////////////////////////////////////////////////////////////////
			$file_name='';
			
			var_dump($_FILES['img_data']);exit;
			
			if (isset($_FILES['img_data']['name']))
				$file_name = $_FILES['img_data']['name'];
			if ($file_name) 
			{
				$file_name = $_FILES['img_data']['name'];
				$now=date('Y-m-d H:i:s');
				$date=date('d.m.y.G.i.s');
				$new_file_name=$date.$file_name;
				$path= "uploads/".$new_file_name;
				$icnt=0;
				if($file_name !="")
				{
					if(move_uploaded_file($_FILES['img_data']['tmp_name'], $path))
					{
						//set images data
					}
				}
			}
			
			$carsModel->set_values($id,$obj);
            $data["tadd"] = true;
			$this->response->redirect(site_url('/cars'));
        }
    }
	
	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);
		}
		
		$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 '{}';
		exit;
			   
	  // var_dump($_FILES['img_data']);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;
}
