<?php
require_once('wp-load.php');

$csv_file='/mnt/stor3-wc2-dfw1/481873/889973/www.carcreditnation.net/web/content/carcreditnation-dmotor.csv';//'test.csv';//
/*
$ftp_ip='66.45.249.226';
$ftp_username='usworkspace';
$ftp_userpass='WXt53JkHZFTl';
*/

$ftp_ip='ftp.dmotorworks.com';
$ftp_username='dirva266';//
$ftp_userpass='rocky887';


$local_file='carcreditnation-dmotor.csv';
$today=date("mdy");
$dealerid='69648263';
$remote_file='/USED'.$dealerid.'.txt';


$header = array(array('dealer_ID','stock','year','make','model','trim','vin','mileage','price','exterior_color','interior_color','transmission','','description','body type','engine type','drive type','fuel type','other_options','image_url1','video','video source'));

$fp = fopen($csv_file, 'w');
/*
foreach ($header as $fields) {
  //  fputcsv($fp, $fields);
}*/
$datalist = data_to_csv($fp);
write_csv($datalist,$fp);
//chmod($csv_file, 0777); 
fclose($fp);


if (file_exists($csv_file)) {
	ftp_upload_to_remote_server($ftp_ip,$ftp_username,$ftp_userpass,$local_file,$remote_file);
}

function data_to_csv($file){
	
	$args = array('post_type'=>'gtcd' ,'posts_per_page'=>-1 ,'post_status'=>'publish','cat'=>'229,651','meta_query' => array(
				array(
					'key'     => '_statustag',
					'value'   => 'Sold',
					'compare' => '!=',
					),
					),
				);

	$myposts = get_posts( $args );
	foreach ( $myposts as $mypost ) {	
				
						$args = array(
						'numberposts' => 28,
						'order' => 'ASC',
						'post_mime_type' => 'image',
						'post_parent' => $mypost->ID,
						'post_status' => null,
						'post_type' => 'attachment',
					);

				
				$attachments = get_children( $args );
				$images =array();
				$saved = get_post_custom_values('CarsGallery',$mypost->ID);
				
				$saved = explode(',',$saved[0]);
				
				$attachmentimage=wp_get_attachment_image_src($saved[0], 'full');
			
				$images []= $attachmentimage[0];
				
				
				
				if ( $attachments ) {
					foreach ( $attachments as $attachment ) {
						$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'full' );
						if($attachmentimage[0] !=$image_attributes[0])
						$images[]=$image_attributes[0];
					}
				}

				$vehicle=array();
				$mod1 =	get_post_meta($mypost->ID,'mod1',true);
				$mod2 = get_post_meta($mypost->ID, 'mod2', true); 
				$mod3 = get_post_meta($mypost->ID, 'mod3', true); 	
				$mod4 = get_post_meta($mypost->ID, 'mod4', true); 	
				$mod5 = get_post_meta($mypost->ID, 'mod5', true); 	
				
				if(is_serialized($mod1))
					$mod1=unserialize($mod1);
				if(is_serialized($mod2))
					$mod2=unserialize($mod2);
				if(is_serialized($mod3))
					$mod3=unserialize($mod3);	
				if(is_serialized($mod4))
					$mod4=unserialize($mod4);	
				if(is_serialized($mod5))
					$mod5=unserialize($mod5);	
				
				//$makemodel=get_the_terms($mypost->ID, 'makemodel' );
				$model='';
				$make='';
				$makemodel=get_the_terms( $mypost->ID, 'makemodel' );
				if($makemodel[0]->parent!=0)
				{	$model=$makemodel[0]->name;
					$make=$makemodel[1]->name;
				}else if($makemodel[1]->parent!=0)
				{
					$model=$makemodel[1]->name;
					$make=$makemodel[0]->name;
				}

				//echo "<pre>";print_r($mod2);echo "</pre>";
				
				//var_dump($mod2);exit;
				if(isset($mod1['VIN']))
					$vin1= $mod1['VIN'];
				else
					$vin1= $mod1['vin'];
					
				$down_payment	=	(get_post_meta($mypost->ID, 'wp_text_1', true))?get_post_meta($mypost->ID, 'wp_text_1', true):'0';		
				$weekly_payment	=	(get_post_meta($mypost->ID, 'wp_text_2', true))? get_post_meta($mypost->ID, 'wp_text_2', true):'0';	
				$price1			=	(get_post_meta($mypost->ID, 'wp_text_4', true))?get_post_meta($mypost->ID, 'wp_text_4', true):'0';	
				$price	='0';
				if($down_payment){
					$price =$down_payment+$price1;
				}
				$dealerid='69648263';
				$vehicle[0]	=	$dealerid ;//($mod4['ID'])?$mod4['ID']:''; dealer id
				$vehicle[1]	=	($mod1['stock'])?$mod1['stock']:'';  // 
				$vehicle[2]	= 	($mod1['year'])?$mod1['year']:'';
				$vehicle[3]	= 	($mod1['make'])?$mod1['make']:$make;
				$vehicle[4]	= 	($mod1['model'])?$mod1['model']:$model;
				$vehicle[5]	=	($mod1['trim'])?$mod1['trim']:'';
				$vehicle[6]	= 	 $vin1;
				//$vehicle[6]	=	'';//$mod3['VEHICLE_STYLE'];//body style
				$vehicle[7]	=	($mod1['miles'])?$mod1['miles']:'';		//$mod1['transmission'];	
				$vehicle[8]	=	 ($price>0)?$price:'0';//price		
				$vehicle[9]	=	($mod1['exterior'])?$mod1['exterior']:'';	
				$vehicle[10]=	($mod1['interior'])?$mod1['interior']:'';	
				$vehicle[11]=	$mod1['transmission'];	//transmission	
				$vehicle[12]=	'';	//Images	
				$vehicle[13]=	($mod1['comment_area'])?$mod1['comment_area']:''; //Description	
				$vehicle[14]=	($mod1['vehicletype'])?$mod1['vehicletype']:'';//Body type
				
				$engsizenew=  ($mod2['enginesize'])?$mod2['enginesize'].'L':'';
				$cylindersnew =  ($mod2['cylinders'])?$mod2['cylinders'].'Cyl':'';
				$vehicle[15]=	($mod2['enginesize'])?$engsizenew.' '.$cylindersnew:'';
				$vehicle[16]=	($mod1['drive'])?$mod1['drive']:'';; //Drive Type
				$vehicle[17]=	($mod2['enginetype'])?$mod2['enginetype']:''; //Fuel Type
				$mod3keys=array_keys($mod3);
				$features= get_the_terms( $mypost->ID, 'features' );
				$myoptions= array();
				foreach($features as $feature){
					 $myoptions[]= $feature->name;
				}
				$options_new= 	implode( ";", $myoptions );
				$vehicle[18]=	($options_new)?$options_new:'';		//Options	
				//$vehicle[19]=	 '';//'NULL';		//Image URLS	
				$k=0;
				$vehicle_images= null;
				foreach($images as $url)		
					{	if($k<27)
						$vehicle_images .=$url.';';
						else
						 break;
					 $k++;
					}
				$vehicle[19]=  rtrim($vehicle_images, ";");
				$vehicle[20]=	 get_post_meta($mypost->ID, 'video_meta_box_videoid', true); //Video URLs		
				$vehicle[21]=	''; //Video Source		

				$data[]=array($vehicle);
			
		}
		return $data;
	
}

function write_csv($datalist,$file){

	for ($i=0;$i<count($datalist);$i++){	
	//for ($i=0;$i<10;$i++){ //Demo 10 Lines for testing
		foreach ($datalist[$i] as $line)
		{
				 //  array_walk($line, create_function('&$str', '$str = "\"$str\"";'));
			//	$line = array_map('strval', $line);
					//fputcsv($file,array_map(encodeFunc, $line),',',chr(0));
				
			//fputcsv($file,$line,',');
			//my_fputcsv($file,$line,',','"', $escape = '\\');
			$line =implode( "*-,*-", $line );
			$line = str_replace('"', "", $line);
			$line= '*-'.$line.'*-';
			$line = str_replace('*-', '"', $line);
			$line = str_replace(';', ',', $line);
			fwrite($file, $line);
			fwrite($file, "\n");
			
			
		}
	}
}



function ftp_upload_to_remote_server($ftp_ip,$ftp_username,$ftp_userpass,$local_file,$remote_file){
		// connect and login to FTP server
			$ftp_server 	= $ftp_ip;
			$ftp_conn 		= ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
			$login 			= ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

			// $file = $local_file;
 $file = '/mnt/stor3-wc2-dfw1/481873/889973/www.carcreditnation.net/web/content/'.$local_file;
			ftp_pasv($ftp_conn, true);
		// upload file
			if (ftp_put($ftp_conn, $remote_file, $file, FTP_ASCII))
			  {
			  echo "Successfully uploaded: $file. at $ftp_conn ";
			  }
			else
			  {
			  echo "Error uploading $file.";
			  }

			// close connection
			ftp_close($ftp_conn);
}
?>