<?php
/*
Plugin Name: Auction product Upload
Plugin URI: 
Description: A plugin built by bddwauction(T.S.).
Version: 1.0
Author: bddwauction(T.S.)
Author URI: https://bddwauction.com
*/
session_start();
 
 
global $auction_product_csv_version; // version of your plugin
global $wpdb;
global $siteURL;   
 
$siteURL=get_option('siteurl'); // website URl
$auction_product_csv_version = '1.0'; // version of your plugin 
register_activation_hook( __FILE__,  'tbl_auction_product_csv_install' );  // Instal your plugin

function tbl_auction_product_csv_install(){ 
global $auction_product_csv_version; // version of your plugin
global $wpdb;
global $siteURL; // website URl 
	
//================ Create the table =============================//

 					
							   
//===============Check if the update is available=========================//
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $create_company_sql );
add_option( "product_csv_auction_db_version", $auction_product_csv_version );
//===============End checking update======================================//
 
}

############################ Display in Admin ###########################

add_action('admin_menu', 'product_csv_management');  // add the tab in left panel of Admin

function product_csv_management(){
	 	
	 
	 
    add_menu_page('Auction Product CSV', 'Auction Product CSV', 'administrator', 'product-csv', 'add_product_csv');
	 
 
      
	function add_product_csv(){
			
		
			 function Generate_Featured_Image( $image_url, $post_id  ){
			    $upload_dir = wp_upload_dir();
			    $image_data = file_get_contents($image_url);
			    $filename = basename($image_url);
			    if(wp_mkdir_p($upload_dir['path'])){
                $file = $upload_dir['path'] . '/' . $filename;
				copy($file,$upload_dir['path'] . '/' .$post_id. $filename);	
				$file = $upload_dir['path'] . '/' .$post_id. $filename;
				$filename=$post_id. $filename;
				}
			    else {
			    $file = $upload_dir['basedir'] . '/' . $filename;
			    file_put_contents($file, $image_data);
			     }
				
			    $wp_filetype = wp_check_filetype($filename, null );
			    $attachment = array(
			        'post_mime_type' => $wp_filetype['type'],
			        'post_title' => sanitize_file_name($filename),
			        'post_content' => '',
			        'post_status' => 'inherit'
			    );
				
			    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
			    require_once(ABSPATH . 'wp-admin/includes/image.php');
			    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
			    $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
			    $res2= set_post_thumbnail( $post_id, $attach_id );
			}
		 function Generate_Gallery_Image( $image_url, $post_id  ){
			    $upload_dir = wp_upload_dir();
			    $image_data = file_get_contents($image_url);
			    $filename = basename($image_url);
			    if(wp_mkdir_p($upload_dir['path'])){
				 $file = $upload_dir['path'] . '/' . $filename;
				copy($file,$upload_dir['path'] . '/' .$post_id. $filename);	
				$file = $upload_dir['path'] . '/' .$post_id. $filename;
				$filename=$post_id. $filename;
				 }
				else   {  $file = $upload_dir['basedir'] . '/' . $filename;
			     file_put_contents($file, $image_data);
				}
			    $wp_filetype = wp_check_filetype($filename, null );
			    $attachment = array(
			        'post_mime_type' => $wp_filetype['type'],
			        'post_title' => sanitize_file_name($filename),
			        'post_content' => '',
			        'post_status' => 'inherit'
			    );
			    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
				 
			    require_once(ABSPATH . 'wp-admin/includes/image.php');
			    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
			    $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
			    $res2= set_post_thumbnail( $post_id, $attach_id );
				return $attach_id;
			}	  
		 
		global $auction_product_csv_version; // version of your plugin
		global $wpdb;
		global $siteURL; // website URl 
		$target_path = "../auction_csv/";
		if(isset($_POST['btn_upload'])){
		if(!empty($_FILES['cfile']['name'])){
			
			  
			  $newfname = time()."auction_csv.csv";
			  $filext = array_pop(explode(".",$_FILES['cfile']['name']));
			
			if($filext == "csv"){
				
				move_uploaded_file($_FILES['cfile']['tmp_name'], $target_path.$newfname) ; 
				if (!file_exists('../../'.date('Y').'/'.date('m'))) {
				    mkdir('../../'.date('Y').'/'.date('m'), 0777, true);
				}
				  
				$handle = fopen($target_path.$newfname,"r");
				$heading = true;
				$i=1;
				while (($data = fgetcsv($handle, 10000, ",")) !== FALSE){
					
					if($i>1){
					 // echo "<pre>"; print_r($data); echo "</pre>";  
					
					
				    $sku = trim($data['0']);
					$name = trim($data['1']); 
				    $shortdescription =   $data['2'];
				    $condition =   trim($data['3']); 
					$finish =   trim($data['4']); 
					$dimention =   $data['5'];
					$qty =   $data['6'];
				    $category =   trim($data['9']);
                    $disclaimer =  trim($data['8']);
                    $eprice =   trim($data['7']);
					$price = $data['10'];
					$start_price = $data['11'];
					$bid_increment = $data['12']; 
				    $reserved_price =   $data['13']; 
					$dates_from =   $data['14']; 
					$dates_to =   $data['15']; 
					$photo =   $data['16'];
					 
					$category_det = get_term_by('name', $category, 'product_cat',OBJECT);
				    $timeext=time();
					 
					$term_id = $category_det->term_id;
					$term_taxonomy_id =  $category_det->term_taxonomy_id;
					
					$path_parts=pathinfo($photo);
					$file_name = '/wp-content/uploads/'.date('Y').'/'.date('m').'/bddw'.$timeext.'.'.$path_parts['extension']; 
                    $newfilefull = $_SERVER['DOCUMENT_ROOT'] . $file_name;
				    $newfile = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/'.date('Y').'/'.date('m').'/bddw'.$timeext .'-150x150.'.$path_parts['extension'];
					
					
					  $my_post = array();
					  $my_post['post_title'] = $name;
					  $my_post['post_content'] = '<h5></h5><p>'.$shortdescription.'</p><h5>RETAIL VALUE IN PERFECT CONDITION: </h5><p>'.$eprice.'</p><h5></h5><p>'.$disclaimer.'</p>';
					  $my_post['post_excerpt'] = $shortdescription;
					  $my_post['post_type'] =  'product';
					  $my_post['post_status'] = 'pending';
					  $my_post['post_author'] = 1;
					 // $my_post['post_category'] = array($term_id); 
					 
					    $addedpost_id = wp_insert_post( $my_post, $wp_error  ); 
					  
					
					add_post_meta( $addedpost_id, '_tax_status', 'taxable', true );
					add_post_meta( $addedpost_id, '_manage_stock', 'yes', true );
					add_post_meta( $addedpost_id, '_backorders', 'no', true );
					add_post_meta( $addedpost_id, '_sold_individually','yes', true );
					add_post_meta( $addedpost_id, '_virtual', 'no', true );
					add_post_meta( $addedpost_id, '_downloadable', 'no', true );
					add_post_meta( $addedpost_id, '_download_limit', '-1', true );
					add_post_meta( $addedpost_id, '_download_expiry', '-1', true );   
					add_post_meta( $addedpost_id, '_stock_status', 'instock', true );   
					add_post_meta( $addedpost_id, '_stock', '1', true );
					add_post_meta( $addedpost_id, '_product_version', '3.6.5', true ); 
					add_post_meta( $addedpost_id, '_price', $price, true );
					add_post_meta( $addedpost_id, '_regular_price', $price, true ); 
					add_post_meta( $addedpost_id, '_auction_item_condition', 'new', true ); 
					add_post_meta( $addedpost_id, '_auction_type', 'normal', true ); 
                    add_post_meta( $addedpost_id, '_auction_sealed', 'no', true );
                    add_post_meta( $addedpost_id, '_auction_proxy', 'yes', true ); 		
					add_post_meta( $addedpost_id, '_auction_start_price', $start_price, true ); 
					add_post_meta( $addedpost_id, '_auction_bid_increment', $bid_increment, true );
                    add_post_meta( $addedpost_id, '_auction_reserved_price', $reserved_price, true ); 
					add_post_meta( $addedpost_id, '_sku', $sku, true ); 
                    add_post_meta( $addedpost_id, '_auction_dates_from',date("Y-m-d H:i",strtotime($dates_from)), true );
                    add_post_meta( $addedpost_id, '_auction_dates_to', date("Y-m-d H:i",strtotime($dates_to)), true ); 					 
					$wpdb->query("INSERT INTO ".$wpdb->prefix."term_relationships (object_id,term_taxonomy_id) VALUES ('$addedpost_id','$term_taxonomy_id')");
					$wpdb->query("INSERT INTO ".$wpdb->prefix."term_relationships (object_id,term_taxonomy_id) VALUES ('$addedpost_id','16')");
					
					$productgalleyid='';
					
					if($data['17']!=""){
					  
					  $path_parts14=trim($data['17']); 
					   
					  $productgalleyid.=Generate_Gallery_Image($path_parts14,$addedpost_id).',';
					 
					}
                    if($data['18']!=""){
					 
					  $path_parts15=trim($data['18']); 
					 
					$productgalleyid.=Generate_Gallery_Image($path_parts15,$addedpost_id).',';
					 
					}
                   if($data['19']!=""){
					  
					  $path_parts16=trim($data['19']);	 
					  
					$productgalleyid.=Generate_Gallery_Image($path_parts16,$addedpost_id).',';
					 
					}
                   if($data['20']!=""){
					   
					  $path_parts17=trim($data['20']);	 
					 
					$productgalleyid.=Generate_Gallery_Image($path_parts17,$addedpost_id).',';
					 
					}
                   if($data['21']!=""){
					 
					  $path_parts18=trim($data['21']);	 
					 
					$productgalleyid.=Generate_Gallery_Image($path_parts18,$addedpost_id).',';
					 
					}
                   if($data['22']!=""){
					   
					  $path_parts19=trim($data['22']);	 
				 
					$productgalleyid.=Generate_Gallery_Image($path_parts19,$addedpost_id).',';
					 
					}
					if($data['23']!=""){
					   
					  $path_parts20=trim($data['23']);	 
					 
					$productgalleyid.=Generate_Gallery_Image($path_parts20,$addedpost_id).',';
					 
					}
                    if($data['24']!=""){
					   
					  $path_parts21=trim($data['24']); 
					 
					$productgalleyid.=Generate_Gallery_Image($path_parts21,$addedpost_id).',';
					 
					}	
					 
					 
                    Generate_Featured_Image( $photo,   $addedpost_id ); 
 
					 
                 add_post_meta( $addedpost_id, '_product_image_gallery', rtrim($productgalleyid, ','), true ); 			  
				} $i++;}

                   echo '<p style="color:green;"><br>'.($i-2)." Products  added.</p>";
                   $_SESSION['msg2'] = ($i-2)." Products added.";
			
			}										
			else{
				echo '<p style="color:red;"><br> Choose Csv file to upload' ;
			}
				 
	
		}
		else {
			echo  '<p style="color:red;"><br>Please Upload csv file</p>';
			
		}
		//exit;
		
	}
 
 
 
  echo '<div class="wrap nosubsub">
 
<h2>IMPORT AUCTION PRODUCT VIA CSV</h2> 
  <table width="100%" border="0" cellspacing="5" cellpadding="0" class="wp-list-table widefat fixed">
  <tr>
  <td colspan="5"> 
			<div align="center" id="msg" style="background-color:#56924C; width:200px;height:25px;display:none;font-weight:bold;color:#fff;">  		</div>
		</td></tr><tr><td align="left" colspan="5">
		<form method="post" action="" name="ff" enctype="multipart/form-data">  
		 <table border="0" width="100%" cellspacing="0" cellpadding="4" align="center" class="htext">
                 
              
                <tr>
                  <td width="" align="left">Browse CSV File for Update:*</td>
                  <td width="" align="left">
				  	<input  type="file" name="cfile" class="inputbox"/>
				  </td>
                </tr>
				
				 
				
				<tr>
                  <td width="" align="left">Download Sample CSV File:</td>
                  <td width="" align="left">
				  	<a href="'.$siteURL.'/wp-content/plugins/auction-product-upload/download.php?filename=auction-product" style="text-decoration:none;">Download CSV</a>
				  </td>
                </tr>
                
                <tr>
                   <td width="" align="left"><input type="submit" name="btn_upload" value="Upload" class="button button-primary button-large"/></td>
                </tr> 
				                     
             </table>
           </form>
		</td></tr></table>
		</div> ';
    }
 
	
	
}