<?php

class SBDQcopd_BulkImport
{

    function __construct()
    {
        //Add a menu in admin panel to link Import Export
        add_action('admin_menu', array($this, 'qcpd_info_menu'));
    }

    public $post_id;

    //Callback function for Import Export Menu
    function qcpd_info_menu()
    {
        add_submenu_page(
            'edit.php?post_type=pd',
            esc_html('Bulk Import'),
            esc_html('Import/Export'),
            'manage_options',
            'qcpd_bimport_page',
            array(
                $this,
                'qcpd_bimport_page_content'
            )
        );
    }

    function qcpd_bimport_page_content()
    {
        ?>
        <div class="wrap">

            <div id="poststuff">

                <div id="post-body" class="metabox-holder columns-3">

                    <div id="post-body-content" style="padding: 50px;box-sizing: border-box;box-shadow: 0 8px 25px 3px rgba(0,0,0,.2);background: #fff;">

                        <u>
                            <h1>Bulk Export/Import</h1>
                        </u>

                        <div>
                            
                            <p style="color: red; padding: 15px;">
								<strong>Please Note:</strong> The Export Import Feature is still in Beta. We have been testing the feature extensively and it works great. However, before performing any sort of Imports, it is strongly recommended that you take a full backup of your website database first. So that if something went wrong during the import, you can revert and no data is lost.
							</p>
							<hr>
							<p>
                                <strong>Sample CSV File:</strong>
                                <a href="<?php echo QCSBD_ASSETS_URL . '/file/sample-csv-file.csv'; ?>" target="_blank">
                                    Download
                                </a>
                            </p>

                            <p><strong>NOTES:</strong></p>

                            <p>
                                <ol>
                                    <li>Attached file should be a plain CSV file.</li>
                                    <li>File must be prepared as per provided sample CSV file or as per the exported CSV file.</li>
	                                <li>To add new items, Export your Lists. Edit the CSV file and add the new items to the relevant lists as needed. Import the CSV back using the button: Delete Existing Items the Add New Items. </li>
                                </ol>
                            </p>
                            
	                        <p>For first time Import, we recommend, creating the Lists manually with 2/3 items in each list. Then follow the point no. 3 above.</p>
                        </div>
						<hr>
						<div style="padding: 15px; margin: 20px 0;" id="pd-export-container">

							<h3><u>Export to a CSV File</u></h3>

	                        <p>
	                        	<strong><u>Option Details:</u></strong>
	                        </p>
	                        <p>
	                        	Export button will create a downloadable CSV file with all of your existing SBD lists and its elements.
	                        </p>

							<a class="button-primary" href="<?php echo admin_url( 'admin-post.php?action=pdprint.csv' ); ?>">Export SBD Data</a>

                        </div>
						<hr>

                        <div style="padding: 15px; margin: 10px 0;">

                        <h3><u>Import from a CSV File</u></h3>

                        <p><strong><u>Importing in Another Website:</u></strong> Please note that uploaded images for list items &amp; categories will not be copied if you import the full CSV to another WordPress installation.</p>

                        <p>
                        	<strong><u>Option Details:</u></strong>
                        </p>
                        <p>
                        	In both of the below cases, attached CSV file must be identical as per the provided format or as per the exported format.
                        </p>
                        <p>
                        	<strong><u>Add New Items: </u></strong>
                        	This option will add new lists and its elements from the CSV file. No lists or its elements get's deleted or updated by this option. If there exist any lists with the same title as CSV lines, then duplicate lists will get created during import.
                        </p>
                        <p>
                        	<strong><u>Delete Existing Items then Add New Items: </u></strong>
                        	This option will first delete ALL the existing SBD lists and its elements [without attached images] from the database, then it attempts to import lists and elements from the attached CSV file. This option is suitable for editing list elements. If you follow this option for a single site, then all previously attached images will get relinked.
                        </p>

                        <!-- Handle CSV Upload -->

                        <?php

                        //Generate a 5 digit random number based on microtime
                        $randomNum = substr(sha1(mt_rand() . microtime()), mt_rand(0,35), 5);


                        /*******************************
                         * If Add New or Delete then Add New button was pressed
                         * then proceed for further processing
                         *******************************/
                        if( !empty($_POST) && isset($_POST['upload_csv']) || !empty($_POST) && isset($_POST['delete_upload_csv']) ) 
                        {

                        	//First check if the uploaded file is valid
                        	$valid = true;
                        	
                        	$allowedTypes = array(
                        			'application/vnd.ms-excel',
                        			'text/comma-separated-values', 
                        			'text/csv', 
                        			'application/csv', 
                        			'application/excel', 
                        			'application/vnd.msexcel', 
                        			'text/anytext',
                        			'application/octet-stream',
                        		);
							//echo $_FILES['csv_upload']['type'];exit;
                        	if( !in_array($_FILES['csv_upload']['type'], $allowedTypes) ){
                        		$valid = false;
                        	}

                        	if( ! $valid ){
                        		echo "Status: Invalid file type.";
                        	}
                            
                            //If the file is valid and delete button was pressed
                            if( $valid && !empty($_POST) && isset($_POST['delete_upload_csv']) )
                            {
                            	
                            	$allposts = get_posts( 'numberposts=-1&post_type=pd&post_status=any' );

								foreach( $allposts as $postinfo ) 
								{
								    delete_post_meta( $postinfo->ID, 'qcpd_list_conf' );
								    delete_post_meta( $postinfo->ID, 'qcpd_list_item01' );
								    delete_post_meta( $postinfo->ID, 'pd_add_block' );

								    wp_delete_post( $postinfo->ID, true );
								}

                            }

                            //If the file is valid and client is logged in
                            if ( $valid && function_exists('is_user_logged_in') && is_user_logged_in() ) 
							{

                                $tmpName = $_FILES['csv_upload']['tmp_name'];
								
								if( $tmpName != "" )
								{
								
									$file = fopen($tmpName, "r");
                                    $flag = true;
									
									//Reading file and building our array
									
									$baseData = array();

									$count = 0;

									$laps = 1;

									$mapapi = 'AIzaSyBACyZ4vA8pQybj9ZdZP-J5zQHqfQkqOXY';
									if(pd_ot_get_option('pd_map_api_key')!=''){
										$mapapi = pd_ot_get_option('pd_map_api_key');
									}
									
									//Read fields from CSV file and dump in $baseData
									while(($data = fgetcsv($file)) !== FALSE) 
									{
										$temp_laps = $laps;
										if ($flag) {
											$flag = false;
											continue;
										}

										$glat = trim($data[7]);
										$glon = trim($data[8]);
										if(isset($_POST['genlatlon']) && $_POST['genlatlon']!=''){



											/*$mapapi = 'AIzaSyBACyZ4vA8pQybj9ZdZP-J5zQHqfQkqOXY';
											if(pd_ot_get_option('pd_map_api_key')!=''){
												$mapapi = pd_ot_get_option('pd_map_api_key');
											}

											$url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($data[6]).'&sensor=false&key='.$mapapi;
											$coordinates = sld_get_web_page($url);
											
											$coordinates = json_decode($coordinates);
											
											if(isset($coordinates->status) and $coordinates->status=='OK'){
												$glat = $coordinates->results[0]->geometry->location->lat;
												$glon = $coordinates->results[0]->geometry->location->lng;
											}*/

											if(isset($_POST['sbd_map_name']) && $_POST['sbd_map_name'] == 'openstreet_map'){

												// url encode the address
											    $address = urlencode($data[6]);

											    $url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";

											    // get the json response
											    $resp_json = sld_get_web_page($url);

											    // decode the json
											    $resp = json_decode($resp_json, true);

											    if(!empty($resp)){
											    	$glat = $resp[0]['lat'];
													$glon = $resp[0]['lon'];
											    }


											}else{

												$mapapi = 'AIzaSyBACyZ4vA8pQybj9ZdZP-J5zQHqfQkqOXY';
												if(pd_ot_get_option('pd_map_api_key')!=''){
													$mapapi = pd_ot_get_option('pd_map_api_key');
												}

												$url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($data[6]).'&sensor=false&key='.$mapapi;
												$coordinates = sld_get_web_page($url);
												
												$coordinates = json_decode($coordinates);
												
												if(isset($coordinates->status) and $coordinates->status=='OK'){
													$glat = $coordinates->results[0]->geometry->location->lat;
													$glon = $coordinates->results[0]->geometry->location->lng;
												}

											}


											
											
										}

										if( isset($data[49]) && $data[49] != '' ){
											$laps = $data[49];
										}
										
										$baseData[$data[0]][] = array(
											'list_id' => trim($data[0]),
											'list_title' => sanitize_text_field((trim($data[1]))),
											'qcpd_item_title' => sanitize_text_field((trim($data[2]))),
											'qcpd_item_link' => trim($data[3]),
											'qcpd_item_phone' => trim($data[4]),
											
											'qcpd_item_location' => sanitize_text_field((trim($data[5]))),
											'qcpd_item_full_address' => sanitize_text_field((trim($data[6]))),
											
											
											'qcpd_item_latitude' => trim($glat),
											'qcpd_item_longitude' => trim($glon),
											
											
											'qcpd_item_email' => trim($data[9]),
											'qcpd_item_twitter' => trim($data[10]),
											'qcpd_item_linkedin' => trim($data[11]),
											'qcpd_item_facebook' => trim($data[12]),
											'qcpd_item_yelp' => trim($data[13]),
											'qcpd_item_business_hour' => trim($data[14]),
											
											'qcpd_item_nofollow' => trim($data[15]),
											'qcpd_item_newtab' => trim($data[16]),
											'qcpd_item_subtitle' => sanitize_text_field((trim($data[17]))),
											'qcpd_fa_icon' => sanitize_text_field((trim($data[18]))),
											'qcpd_use_favicon' => trim($data[19]),
											'qcpd_item_img' => trim($data[20]),
											'qcpd_item_img_title' => trim($data[21]),
											'qcpd_item_img_link' => trim($data[22]),
											'qcpd_upvote_count' => trim($data[23]),
											'attached_terms' => trim($data[24]),
											'qcpd_entry_time' => date("Y-m-d H:i:s"),
											'qcpd_timelaps' => $laps,
											'qcpd_description'=> trim($data[40]),
											'qcpd_new'=> trim($data[41]),
											'qcpd_featured'=> trim($data[42]),
											'qcpd_tags'=> trim($data[43]),
											'qcpd_field_1'=> trim($data[44]),
											'qcpd_field_2'=> trim($data[45]),
											'qcpd_field_3'=> trim($data[46]),
											'qcpd_field_4'=> trim($data[47]),
											'qcpd_field_5'=> trim($data[48]),
											'list_border_color' => trim($data[25]),
											'list_bg_color' => trim($data[26]),
											'list_bg_color_hov' => trim($data[27]),
											'list_txt_color' => trim($data[28]),
											'list_txt_color_hov' => trim($data[29]),
											'list_subtxt_color' => trim($data[30]),
											'list_subtxt_color_hov' => trim($data[31]),
											'item_bdr_color' => trim($data[32]),
											'item_bdr_color_hov' => trim($data[33]),
											'list_title_color' => trim($data[34]),
											'filter_background_color' => trim($data[35]),
											'filter_text_color' => trim($data[36]),
											'add_block_text' => sanitize_text_field((trim($data[37]))),
											'menu_order' => trim($data[38]),
											'post_status' => trim($data[39]),
										);

										$laps = $temp_laps;

										$count++;
										$laps++;

									}
									
									fclose($file);
									
									//Inserting Data from our built array
									
									$keyCounter = 0;
									$metaCounter = 0;
									
									global $wpdb;

									//Sort $baseData numerically
									ksort($baseData, SORT_NUMERIC);
									
									
									
									//Parse $baseData and insert in the database
									foreach( $baseData as $key => $data ){
									
										
										//Check menu order for current SLD post, set 0 if empty
										$menu_order_val = isset($data[0]['menu_order']) ? $data[0]['menu_order'] : 0;

										//Grab current LIST title
										$post_title = (isset($data[0]['list_title']) && $data[0]['list_title'] != "" ) ? $data[0]['list_title'] : '';

										$post_id = (isset($data[0]['list_id']) && $data[0]['list_id'] != "" ) ? $data[0]['list_id'] : '';
										
										//Grab current LIST status, set 'publish' if empty
										$post_status = (isset($data[0]['post_status']) && $data[0]['post_status'] != "" ) ? $data[0]['post_status'] : 'publish';

										//If $post_title is empty, then go for next iteration
										if( $post_title == '' ){
											continue;
										}
										
										$existing_list = false;
										//Existing post array
										if(!empty(get_post($post_id))){
											$newest_post_id = $post_id;
											$existing_list = true;
										}else{
											//Build post array and insert as new POST
											$post_arr = array(
												'post_title' => trim($post_title),
												'post_status' => $post_status,
												'post_author' => get_current_user_id(),
												'post_type' => 'pd',
												'menu_order' => $menu_order_val,
											);

											wp_insert_post($post_arr);

											//Get the newest post ID, that we just inserted
											$newest_post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_type = 'pd' ORDER BY ID DESC LIMIT 1");
										}
										
										
										
										
										

										$attachedTerms = '';

										$innerListCounter = 0;

										$configArray = array();
										$addBlockArray = array();

										//Add list meta fields. i.e. list items and configs
										foreach( $data as $k => $item ){

											if( $innerListCounter == 0 && $existing_list===false)
											{
												$attachedTerms = $item['attached_terms'];

												$configArray['list_border_color'] = $item['list_border_color'];
												$configArray['list_bg_color'] = $item['list_bg_color'];
												$configArray['list_bg_color_hov'] = $item['list_bg_color_hov'];
												$configArray['list_txt_color'] = $item['list_txt_color'];
												$configArray['list_txt_color_hov'] = $item['list_txt_color_hov'];
												$configArray['list_subtxt_color'] = $item['list_subtxt_color'];
												$configArray['list_subtxt_color_hov'] = $item['list_subtxt_color_hov'];
												$configArray['item_bdr_color'] = $item['item_bdr_color'];
												$configArray['item_bdr_color_hov'] = $item['item_bdr_color_hov'];
												$configArray['list_title_color'] = $item['list_title_color'];
												$configArray['filter_background_color'] = $item['filter_background_color'];
												$configArray['filter_text_color'] = $item['filter_text_color'];

												$addBlockArray['add_block_text'] = $item['add_block_text'];

												add_post_meta(
													$newest_post_id, 
													'qcpd_list_conf', array(
														'list_border_color' => $item['list_border_color'],
														'list_bg_color' => $item['list_bg_color'],
														'list_bg_color_hov' => $item['list_bg_color_hov'],
														'list_txt_color' => $item['list_txt_color'],
														'list_txt_color_hov' => $item['list_txt_color_hov'],
														'list_subtxt_color' => $item['list_subtxt_color'],
														'list_subtxt_color_hov' => $item['list_subtxt_color_hov'],
														'item_bdr_color' => $item['item_bdr_color'],
														'item_bdr_color_hov' =>  $item['item_bdr_color_hov'],
														'list_title_color' =>  $item['list_title_color'],
														'filter_background_color' =>  $item['filter_background_color'],
														'filter_text_color' =>  $item['filter_text_color'],
													)
												);

												add_post_meta(
													$newest_post_id, 
													'pd_add_block', array(
														'add_block_text' =>  $item['add_block_text'],
													)
												);

												$innerListCounter++;
											}

											$attachment_id = "";
											
											$attachmentId = ($item['qcpd_item_img']);
											
											if( $attachmentId != "" && wp_get_attachment_url( $attachmentId ) ){
											  $attachment_id = $attachmentId;
											}

											if( $attachmentId != '' ){
												$image = wp_get_attachment_metadata( $attachmentId );

												$imageTitle = isset( $image['file'] ) ? $image['file'] : '';

												if( $imageTitle != trim($item['qcpd_item_img_title']) ){
													$attachment_id = "";
												}
											}

											if( isset($_POST['genlatlon']) ){


												if(isset($_POST['sbd_map_name']) && $_POST['sbd_map_name'] == 'openstreet_map'){

													// url encode the address
												    $address = urlencode($item['qcpd_item_full_address']);

												    $url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";

												    // get the json response
												    $resp_json = sld_get_web_page($url);

												    // decode the json
												    $resp = json_decode($resp_json, true);

													$item['qcpd_item_latitude'] = $resp[0]['lat'];
													$item['qcpd_item_longitude'] = $resp[0]['lon'];

												}else{

													if( !isset($item['qcpd_item_latitude']) || !isset($item['qcpd_item_longitude']) || empty($item['qcpd_item_latitude']) || empty($item['qcpd_item_longitude']) ){
														if( !empty($item['qcpd_item_full_address']) ){

															$mapapi = 'AIzaSyBACyZ4vA8pQybj9ZdZP-J5zQHqfQkqOXY';
															if(pd_ot_get_option('pd_map_api_key')!=''){
																$mapapi = pd_ot_get_option('pd_map_api_key');
															}

															$address_to_lat_lang = sbd_get_lat_long_from_address($item['qcpd_item_full_address'], $mapapi);
															$item['qcpd_item_latitude'] = $address_to_lat_lang['lat'];
															$item['qcpd_item_longitude'] = $address_to_lat_lang['lng'];
															// error_log('lat '.$item['qcpd_item_latitude']);
															// error_log('lng '.$item['qcpd_item_longitude']);
														}
													}

												}

												
											}
											
											add_post_meta(
												$newest_post_id, 
												'qcpd_list_item01', array(
													'qcpd_item_title' 	=> $item['qcpd_item_title'],
													'qcpd_item_link' => $item['qcpd_item_link'],
													
													'qcpd_item_subtitle' => $item['qcpd_item_subtitle'],
													'qcpd_item_phone' => $item['qcpd_item_phone'],
													'qcpd_item_location' => $item['qcpd_item_location'],
													'qcpd_item_full_address' => $item['qcpd_item_full_address'],
													'qcpd_item_latitude' => $item['qcpd_item_latitude'],
													'qcpd_item_longitude' => $item['qcpd_item_longitude'],
													'qcpd_item_email' => $item['qcpd_item_email'],
													'qcpd_item_twitter' => $item['qcpd_item_twitter'],
													'qcpd_item_linkedin' => $item['qcpd_item_linkedin'],
													'qcpd_item_facebook' => $item['qcpd_item_facebook'],
													'qcpd_item_yelp' => $item['qcpd_item_yelp'],
													'qcpd_item_business_hour' => $item['qcpd_item_business_hour'],
													
													'qcpd_item_nofollow' => $item['qcpd_item_nofollow'],
													'qcpd_item_newtab' => $item['qcpd_item_newtab'],
													'qcpd_fa_icon' => $item['qcpd_fa_icon'],
													'qcpd_use_favicon' => $item['qcpd_use_favicon'],
													'qcpd_item_img' => $attachment_id,
													'qcpd_upvote_count' => $item['qcpd_upvote_count'],
													'qcpd_entry_time' =>  $item['qcpd_entry_time'],
													'qcpd_timelaps' =>  $item['qcpd_timelaps'],
													'qcpd_item_img_link' =>  $item['qcpd_item_img_link'],
													'qcpd_description' =>  $item['qcpd_description'],
													'qcpd_new' =>  $item['qcpd_new'],
													'qcpd_featured' =>  $item['qcpd_featured'],
													'qcpd_tags' =>  $item['qcpd_tags'],
													'qcpd_field_1' =>  $item['qcpd_field_1'],
													'qcpd_field_2' =>  $item['qcpd_field_2'],
													'qcpd_field_3' =>  $item['qcpd_field_3'],
													'qcpd_field_4' =>  $item['qcpd_field_4'],
													'qcpd_field_5' =>  $item['qcpd_field_5'],
												)
											);
											
											$metaCounter++;
											
										} //end of inner-foreach
										
										$keyCounter++;

										//Relate terms, if exists
										if( $attachedTerms !== '' )
										{
											
											$termIds = array();

											$postTerms = explode(',', $attachedTerms);

											foreach ($postTerms as $term ) {

												$termId = intval(trim($term));

												if( term_exists($termId, 'pd_cat') )
												{
													array_push($termIds, $termId);
												}
											}

											wp_set_post_terms( $newest_post_id, $termIds, 'pd_cat' );

										}
									
									} //end of outer-foreach

									//Display iteration result
									if( ( isset($keyCounter) && $keyCounter > 0 ) && ( isset($metaCounter) && $metaCounter > 0 ) ){

										echo  '<div><span style="color: red; font-weight: bold;">'.esc_html('RESULT:').'</span> <strong>'.$keyCounter.'</strong> '.esc_html('entry with').' <strong>'.$metaCounter.'</strong> '.esc_html('element(s) was made successfully.').' </div>';
									}
								
							    }
								else
								{
								   echo esc_html("Status: Please upload a valid CSV file.", "qc-pd");
								}

                            }

                        } 
                        else 
                        {
							//echo "Attached file is invalid!";
                        }

                        ?>
                            
                            <p>
                                <strong>
                                    <?php echo __('Upload a CSV file here to Import: '); ?>
                                </strong>
                            </p>

                            <form name="uploadfile" id="uploadfile_form" method="POST" enctype="multipart/form-data" action="" accept-charset="utf-8">
                                
                                <?php wp_nonce_field('qcpd_import_nonce', 'qc-pd'); ?>

                                <p>
                                    <?php echo __('Select file to upload') ?>
                                    <input type="file" name="csv_upload" id="csv_upload" size="35" class="uploadfiles"/>
                                </p>
								<p style="color:red;">**CSV File & Characters must be saved with UTF-8 encoding**</p>
								<p>
                                    <?php echo __('Generate Latitude & Longitude') ?>
                                    <input type="checkbox" name="genlatlon" id="genlatlon" value="1" />
                                </p>
								<p>
                                   <span> Latitude & Longitude for</span>
									<input type="radio" id="google_map" name="sbd_map_name" value="google_map" checked>
									<label for="google_map"> <b><?php echo __('Google Map') ?></b></label>
								
									<input type="radio" id="openstreet_map" name="sbd_map_name" value="openstreet_map">
									<label for="openstreet_map"> <b><?php echo __('OpenStreet Map') ?></b></label>
                                </p>
								<p style="color:red;">**Please select the option you choose in the general settings**</p>
								
								<p style="color:red;"></p>
                                <p>
                                    <input class="button-primary pd-add-as-new" type="submit" name="upload_csv" id="" value="<?php echo __('Add New Items') ?>"/>

                                    <input class="button-primary delete-old" type="submit" name="delete_upload_csv" id="" value="<?php echo __('Delete Existing Items then Add New Items') ?>"/>
                                </p>
								

                            </form>

                        </div>

                        <div style="padding: 15px 10px; border: 1px solid #ccc; text-align: center; margin-top: 20px;">
                            Crafted By: <a href="http://www.quantumcloud.com" target="_blank">Web Design Company</a> -
                            QuantumCloud
                        </div>

                    </div>
                    <!-- /post-body-content -->

                </div>
                <!-- /post-body-->

            </div>
            <!-- /poststuff -->


        </div>
        <!-- /wrap -->

        <?php
    }
}

new SBDQcopd_BulkImport;


// function to get latitude and longitude the address
function sbd_get_lat_long_from_address($address, $api_key) {
   $array = array();
   $address = str_replace(' ', '+', $address);
   $geo_request = wp_remote_get('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.$api_key);
   	//error_log($geo);

   $geo_body = wp_remote_retrieve_body($geo_request);

   // We convert the JSON to an array
   $geo = json_decode($geo_body, true);

   // If everything is cool
   if ($geo['status'] = 'OK') {
      $latitude = $geo['results'][0]['geometry']['location']['lat'];
      $longitude = $geo['results'][0]['geometry']['location']['lng'];
      $array = array('lat'=> $latitude ,'lng'=>$longitude);
   }

   return $array;
}

function sbd_download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    /*header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");*/

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

function sbd_array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }

   ob_start();

   $df = fopen("php://output", 'w');

   $titles = array('List ID', 'List Title', 'Item Title', 'Link', 'Phone' , 'Location' , 'Full Address' , 'Latitude' , 'Longitude' , 'Email' , 'Twitter' , 'Linkedin' , 'Facebook' , 'Yelp' , 'Business Hour' , 'No Follow', 'New Tab', 'Sub Title', 'FA Icon Class', 'Use Favicon', 'Attachment ID', 'Attachment Title', 'Direct/External Image Link', 'Upvotes', 'Terms', 'List Holder Color', 'Item Background Color', 'Item Background Color (Hover)', 'Item Text Color', 'Item Text Color (Hover)', 'Item Sub Text Color', 'Item Sub Text Color (Hover)', 'Item Border Color', 'Item Border Color (Hover)','List Title Color','Filter Button Background Color','Filter Button Text Color', 'Ad Content', 'List Order', 'Post Status', 'Long Description', 'Mark item as New( Support: 0, 1)', 'Mark item as featured( Support: 0, 1)', 'Tags', 'Custom Field 1', 'Custom Field 2', 'Custom Field 3', 'Custom Field 4', 'Custom Field 5', 'Item ID');

   
   fputcsv($df, $titles);

   foreach ($array as $row) {
      fputcsv($df, $row);
   }

   fclose($df);

   return ob_get_clean();
}

add_action( 'admin_post_pdprint.csv', 'pd_export_print_csv' );

function pd_export_print_csv()
{
    global $wpdb;

    if ( ! current_user_can( 'manage_options' ) )
        return;

    $args = array(
		'post_type' => 'pd',
		'posts_per_page' => -1,
		'orderby' => 'id',
		'order' => 'ASC',
	);

    //Build the array first
    $export_query = new WP_Query( $args );

    $childArray = array();
    
	if ( $export_query->have_posts() ) 
	{

		$childArray = array();

		while ( $export_query->have_posts() ) 
		{
			$export_query->the_post();

			$post_title = get_the_title();

			$list_id = get_the_ID();

			$menu_order = get_post_field( 'menu_order', get_the_ID() );

			$post_status = get_post_status( get_the_ID() );

			$lists = get_post_meta( get_the_ID(), 'qcpd_list_item01' );

			$config = get_post_meta( get_the_ID(), 'qcpd_list_conf' );

			$addBlock = get_post_meta( get_the_ID(), 'pd_add_block' );

			$add_content = "";

			if( count($addBlock) > 0 )
			{
				$add_content = $addBlock[0]['add_block_text'];
			}
			
			$config_exists = false;

			if( count($config) > 0 )
			{
				$config_exists = true;
			}

			$terms = array();

			$terms = get_the_terms( get_the_ID(), 'pd_cat' );

			$termArray = array();
			$attachedTerms = '';

			if( $terms && count($terms) > 0 )
			{

				foreach ( $terms as $term ) 
				{
			        $termArray[] = $term->term_id;
			    }
			                         
			    $attachedTerms = join( ", ", $termArray );
			}

			if( count($lists) > 0 )
			{

				$innerListNumber = 1;

				foreach( $lists as $list )
				{
					$innerArray = array();

					$title = $list['qcpd_item_title'];
					$subtitle = $list['qcpd_item_subtitle'];
					$link = $list['qcpd_item_link'];
					
					$phone = $list['qcpd_item_phone'];
					$location = $list['qcpd_item_location'];
					$full_address = $list['qcpd_item_full_address'];
					$latitude = $list['qcpd_item_latitude'];
					$longitude = $list['qcpd_item_longitude'];
					$email = $list['qcpd_item_email'];
					$twitter = $list['qcpd_item_twitter'];
					$linkedin = $list['qcpd_item_linkedin'];
					$facebook = $list['qcpd_item_facebook'];
					$yelp = $list['qcpd_item_yelp'];
					$business_hour = $list['qcpd_item_business_hour'];

					$nofollow = ( isset($list['qcpd_item_nofollow']) && $list['qcpd_item_nofollow'] != '0' ) ? 1 : 0;
					$newtab = ( isset($list['qcpd_item_newtab']) && $list['qcpd_item_newtab'] != '0' ) ? 1 : 0;
					$qcpd_description = ( isset($list['qcpd_description']) && $list['qcpd_description'] != '' ) ? $list['qcpd_description'] : '';
					$qcpd_new = ( isset($list['qcpd_new']) && $list['qcpd_new'] != '' ) ? $list['qcpd_new'] : 0;
					$qcpd_featured = ( isset($list['qcpd_featured']) && $list['qcpd_featured'] != '' ) ? $list['qcpd_featured'] : 0;
					$qcpd_tags = ( isset($list['qcpd_tags']) && $list['qcpd_tags'] != '' ) ? $list['qcpd_tags'] : '';
					$qcpd_custom_field_1 = ( isset($list['qcpd_field_1']) && $list['qcpd_field_1'] != '' ) ? $list['qcpd_field_1'] : '';
					$qcpd_custom_field_2 = ( isset($list['qcpd_field_2']) && $list['qcpd_field_2'] != '' ) ? $list['qcpd_field_2'] : '';
					$qcpd_custom_field_3 = ( isset($list['qcpd_field_3']) && $list['qcpd_field_3'] != '' ) ? $list['qcpd_field_3'] : '';
					$qcpd_custom_field_4 = ( isset($list['qcpd_field_4']) && $list['qcpd_field_4'] != '' ) ? $list['qcpd_field_4'] : '';
					$qcpd_custom_field_5 = ( isset($list['qcpd_field_5']) && $list['qcpd_field_5'] != '' ) ? $list['qcpd_field_5'] : '';
					$item_id = ( isset($list['qcpd_timelaps']) && $list['qcpd_timelaps'] != '' ) ? $list['qcpd_timelaps'] : '';

					$faIconClass = (isset($list['qcpd_fa_icon']) && trim($list['qcpd_fa_icon']) != "") ? $list['qcpd_fa_icon'] : "";

					$useFavicon = (isset($list['qcpd_use_favicon']) && trim($list['qcpd_use_favicon']) != "0") ? 1 : 0;

					$setImageId = ( isset($list['qcpd_item_img'])  && $list['qcpd_item_img'] != "" ) ? trim($list['qcpd_item_img']) : '';

					$externalImageLink = ( isset($list['qcpd_item_img_link'])  && $list['qcpd_item_img_link'] != "" ) ? trim($list['qcpd_item_img_link']) : '';

					$upvotes = ( isset($list['qcpd_upvote_count'])  && $list['qcpd_upvote_count'] != "" ) ? trim($list['qcpd_upvote_count']) : 0;

					$image = wp_get_attachment_metadata( $setImageId );

					$imageTitle = isset( $image['file'] ) ? $image['file'] : '';

					$innerArray[0] = trim($list_id);
					$innerArray[1] = trim($post_title);
					$innerArray[2] = $title;
					$innerArray[3] = $link;
					
					$innerArray[4] = $phone;
					$innerArray[5] = $location;
					$innerArray[6] = $full_address;
					$innerArray[7] = $latitude;
					$innerArray[8] = $longitude;
					$innerArray[9] = $email;
					$innerArray[10] = $twitter;
					$innerArray[11] = $linkedin;
					$innerArray[12] = $facebook;
					$innerArray[13] = $yelp;
					$innerArray[14] = $business_hour;
					
					$innerArray[15] = $nofollow;
					$innerArray[16] = $newtab;
					$innerArray[17] = $subtitle;
					$innerArray[18] = $faIconClass;
					$innerArray[19] = $useFavicon;
					$innerArray[20] = $setImageId;
					$innerArray[21] = $imageTitle;
					$innerArray[22] = $externalImageLink;
					$innerArray[23] = $upvotes;
					$innerArray[24] = $attachedTerms;

					$innerArray[25] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['list_border_color'] : "";
					$innerArray[26] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['list_bg_color'] : "";
					$innerArray[27] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['list_bg_color_hov'] : "";
					$innerArray[28] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['list_txt_color'] : "";
					$innerArray[29] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['list_txt_color_hov'] : "";
					$innerArray[30] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['list_subtxt_color'] : "";
					$innerArray[31] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['list_subtxt_color_hov'] : "";
					$innerArray[32] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['item_bdr_color'] : "";
					$innerArray[33] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['item_bdr_color_hov'] : "";
					$innerArray[34] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['list_title_color'] : "";
					$innerArray[35] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['filter_background_color'] : "";
					$innerArray[36] = ( $config_exists && $innerListNumber == 1 ) ? $config[0]['filter_text_color'] : "";

					$innerArray[37] = ( $innerListNumber == 1 ) ? $add_content : "";

					$innerArray[38] = ( isset($menu_order) && $menu_order != '' ) ? $menu_order : 0;

					$final_post_status = ( isset($post_status) && $post_status != '' ) ? $post_status : 'publish';

					$innerArray[39] = ( $innerListNumber == 1 ) ? $final_post_status : '';
					$innerArray[40] = $qcpd_description;
					$innerArray[41] = $qcpd_new;
					$innerArray[42] = $qcpd_featured;
					$innerArray[43] = $qcpd_tags;
					$innerArray[44] = $qcpd_custom_field_1;
					$innerArray[45] = $qcpd_custom_field_2;
					$innerArray[46] = $qcpd_custom_field_3;
					$innerArray[47] = $qcpd_custom_field_4;
					$innerArray[48] = $qcpd_custom_field_5;
					$innerArray[49] = $item_id;

					array_push($childArray, $innerArray);

					$innerListNumber++;
				}
			}

		}


		wp_reset_postdata();
	}

	/*echo '<pre>';
		print_r( $childArray );
	echo '</pre>';*/

	sbd_download_send_headers("pd_lists_" . date("Y-m-d") . ".csv");

	$result = sbd_array2csv($childArray);

	print $result;

}
