<?php

class GP_Budgets {

	public static function init() {
		add_action( 'add_meta_boxes_gp_budget', array( __CLASS__,'add_meta_boxes_gp_budget' ) );
		// Add extra columns to budgets
		add_filter( 'manage_gp_budget_posts_columns', array( __CLASS__, 'manage_gp_budget_posts_columns' ) );
		add_filter( 'manage_gp_budget_posts_custom_column', array( __CLASS__, 'manage_gp_budget_posts_custom_column' ), 10, 3 );

		add_action('save_post', array( __CLASS__, 'save_post' ), 1, 2 );

	}

	public static function add_meta_boxes_gp_budget ( $post ) {
		add_meta_box(
				'gp_budget_information',
				__( 'General Details', 'gestion-pymes' ),
				array ( __CLASS__,'render_meta_box_gp_budget_information')
		);
		add_meta_box(
				'gp_budget_items',
				__( 'Budget items', 'gestion-pymes' ),
				array ( __CLASS__,'render_meta_box_gp_budget_items')
		);
		add_meta_box(
				'gp_budget_actions',
				__( 'Actions', 'gestion-pymes' ),
				array ( __CLASS__,'render_meta_box_gp_budget_actions'),
				'gp_budget',
				'side'
		);
	}

	public static function render_meta_box_gp_budget_information () {
		global $post;
	
		$output = "";
		echo '<input type="hidden" name="gp_budget_information" id="gp_budget_information" value="' .
				wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
	
		// Get the location data if its already been entered
		$num = get_post_meta($post->ID, '_gp_budget_number', true);
		$date = get_post_meta($post->ID, '_gp_budget_date', true);
		$tax = get_post_meta($post->ID, '_gp_budget_tax', true);
		$irpf = get_post_meta($post->ID, '_gp_budget_irpf', true);
		$customerID = get_post_meta($post->ID, '_gp_budget_customer', true);
		if ( !$irpf || ( strlen($irpf) <= 0 ) ) {
		    $irpf = 0;
		}
		
		$args = array( 'post_type' => 'gp_customer', 'posts_per_page' => -1, 'post_status' =>'publish' );
		$allCustomers = get_posts( $args );
	
		$select = '<select id="gp_select_customer" name="_gp_budget_customer" class="widefat">';
		if ( is_array( $allCustomers ) && ( sizeof( $allCustomers )>0 ) ) {
			foreach ( $allCustomers as $customer ) {
				$selected = "";
				if ( $customer->ID == $customerID ) {
					$selected = "selected";
				}
				$select .= '<option value="' . $customer->ID . '" ' . $selected . ' >' . get_the_title( $customer->ID ) . '</option>';
			}
		} else {
			$select .= '<option value="">' . __( 'Select one', 'gestion-pymes' ) . '</option>';
		}
		$select .= '</select>';
		 
		$selectTax = '<select name="_gp_budget_tax" class="widefat">';
		$taxes = array();
		$taxes[] = get_option( "gp_settings_vat_1", "0" );
		$taxes[] = get_option( "gp_settings_vat_2", "0" );
		$taxes[] = get_option( "gp_settings_vat_3", "0" );
		foreach ( $taxes as $value ) {
			$selected = "";
			if ( $value == $tax ) {
				$selected = "selected";
			}
			$selectTax .= '<option value="' . $value . '" ' . $selected . ' >' . $value . '</option>';
		}
		$selectTax .= '</select>';
	
		// Echo out the field
		$output .= '<p>' . __( "Number", 'gestion-pymes' ) . '<br><input type="text" name="_gp_budget_number" value="' . $num  . '" class="" /></p>';
		$output .= '<p>' . __( "Date", 'gestion-pymes' ) . '<br><input type="text" readonly class="tfdate" name="_gp_budget_date" value="' . $date  . '" class="widefat" /></p>';
		$output .= '<p>' . __( "TAX", 'gestion-pymes' ) . '<br>' . $selectTax . '</p>';
		$output .= '<p>' . __( "IRPF", 'gestion-pymes' ) . '<br><input type="text" name="_gp_budget_irpf" value="' . $irpf  . '" class="widefat" /></p>';
		$output .= '<p>' . __( "Customer", 'gestion-pymes' ) . '<br>' . $select . '</p>';
		echo $output;
	}
	
	public static function render_meta_box_gp_budget_items () {
		global $post;
	
		$descs = get_post_meta($post->ID, 'gp-budget-desc', true);
		
		$desc = maybe_unserialize( $descs );
		
		$cants = get_post_meta($post->ID, 'gp-budget-cant', true);
		$cant = maybe_unserialize( $cants );
		$prices = get_post_meta($post->ID, 'gp-budget-price', true);
		$price = maybe_unserialize( $prices );

		$output = "";
		$output .= '<div class="table-responsive">
						<table class="gp-budget-items-table grid" id="sort" >
							<thead>
								<tr>
                                    <th></th>
									<th class="gp-budget-table-desc">' . __( 'Description', 'gestion-pymes' ) . '</th>
									<th class="gp-budget-table-cant">' . __( 'Quantity', 'gestion-pymes' ) . '</th>
									<th class="gp-budget-table-price">' . __( 'Price', 'gestion-pymes' ) . '</th>
								</tr>
							</thead>
							<tbody>';

		if ( is_array( $desc ) ) {
			foreach ( $desc as $key => $value ) {
			    $value = esc_attr(stripslashes($value));
			    
				$cant_value = isset($cant[$key])?$cant[$key]:"";
				$price_value = isset($price[$key])?$price[$key]:"";
				$output .= '<tr>
                    <td><span class="ui-icon ui-icon-grip-dotted-vertical" style=""></span></td>
					<td><input type="text" name="gp-budget-desc[]" value="' . $value . '" /></td>
					<td class="right"><input type="text" name="gp-budget-cant[]" value="' . $cant_value . '" /></td>
					<td class="right"><input type="text" name="gp-budget-price[]" value="' . $price_value . '" /></td>
				</tr>';
			}
		} else {
			$output .= '<tr>
                            <td><span class="ui-icon ui-icon-grip-dotted-vertical" style=""></span></td>
							<td><input type="text" name="gp-budget-desc[]" placeholder="Concepto" /></td>
							<td class="right"><input type="text" name="gp-budget-cant[]" placeholder="Cantidad" /></td>
							<td class="right"><input type="text" name="gp-budget-price[]" placeholder="Precio" /></td>
						</tr>';
			$output .= '<tr>
                            <td><span class="ui-icon ui-icon-grip-dotted-vertical" style=""></span></td>
							<td><input type="text" name="gp-budget-desc[]" placeholder="Concepto" /></td>
							<td class="right"><input type="text" name="gp-budget-cant[]" placeholder="Cantidad" /></td>
							<td class="right"><input type="text" name="gp-budget-price[]" placeholder="Precio" /></td>
						</tr>';
			$output .= '<tr>
                            <td><span class="ui-icon ui-icon-grip-dotted-vertical" style=""></span></td>
							<td><input type="text" name="gp-budget-desc[]" placeholder="Concepto" /></td>
							<td class="right"><input type="text" name="gp-budget-cant[]" placeholder="Cantidad" /></td>
							<td class="right"><input type="text" name="gp-budget-price[]" placeholder="Precio" /></td>
						</tr>';
		}
		$output .= '</tbody>
				</table>
			</div>';

		// button
		$output .= '<div style="clear:both;"></div>';
		$output .= '<button id="gp_budget_button_add_item" class="button button-primary button-large" onclick="return false;">' . __( 'Add line', 'gestion-pymes' ) . '</button>';
		echo $output;
	}

	public static function render_meta_box_gp_budget_actions () {
		global $post;

		$output = "";
		$output .= '<div class="gp-actions">';
		$output .= '<form method="post" action="">';
		$output .= '<input type="hidden" name="gp-budget-id" value="' . $post->ID . '" />';
		$output .= '<input type="submit" name="gp-budget-print" class="button button-primary button-large" value="' . __( 'Print', 'gestion-pymes' ) . '" />';
		$output .= '<input type="submit" name="gp-budget-to-invoice" class="button button-primary button-large" value="' . __( 'To Invoice', 'gestion-pymes' ) . '" />';
		$output .= '</form>';
		$output .= '</div>';
		$output .= '<div style="clear:both;"></div>';

		echo $output;
	}

	/**
	 * Budget columns
	 * @param array $column_headers
	 * @return array
	 */
	public static function manage_gp_budget_posts_columns( $column_headers ) {
		$column_headers = array (
				'number' => __( 'Number', 'gestion-pymes' ),
				'title' => __( 'Title', 'gestion-pymes' ),
				'customer' => __( 'Customer', 'gestion-pymes' ),
				'idate' => __( 'Date', 'gestion-pymes' ),
				'total' => __( 'Total', 'gestion-pymes' ) );
		return $column_headers;
	}
	
	/**
	 * Set budget columns value
	 * @param string $column_name
	 * @param int $post_ID
	 */
	public static function manage_gp_budget_posts_custom_column($column_name, $post_ID) {
		switch ( $column_name ) {
			case 'number':
				echo get_post_meta( $post_ID, '_gp_budget_number', true );
				break;
			case 'title':
				echo get_post_meta( $post_ID, 'title', true );
				break;
			case 'customer':
				$customer_id = get_post_meta( $post_ID, '_gp_budget_customer', true );
				$customer_name = get_post_meta( $customer_id, '_gp_customer_name', true );
				echo $customer_name;
				break;
			case 'idate':
				echo get_post_meta( $post_ID, '_gp_budget_date', true );
				break;
			case 'total':
				$total = GestionPymes::getBudgetTotal( $post_ID );
				echo $total . GESTIONPYMES_CURRENCY;
				break;
		}
	}

	public static function admin_action_gp_print_budget () {
	
		$post_id = isset( $_REQUEST['gp-budget-id'] ) ? $_REQUEST['gp-budget-id'] : null;
	
		if ( $post_id ) {
			include_once GESTIONPYMES_CORE_DIR . '/mpdf/mpdf.php';
	
			$budget_number = get_post_meta( $post_id, '_gp_budget_number', TRUE );
	
			$tableVar = GP_PDF_Template::getBudgetContent( $post_id );
			$stylesheet = GP_PDF_Template::getBudgetCSS( $post_id );
	
			$mpdf=new mPDF();
	
			$mpdf->SetHTMLFooter( GP_PDF_Template::getBudgetFooterContent( $post_id ) );
	
			$mpdf->WriteHTML($stylesheet,1);
			$mpdf->WriteHTML($tableVar,2);
			$mpdf->Output( __( 'budget-', 'gestion-pymes' ) . $budget_number . '.pdf','D');
			exit;
		}
	}

	public static function save_post ( $post_id, $post ) {
		global $wpdb;
	
		// Is the user allowed to edit the post or page?
		if ( !current_user_can( 'edit_post', $post->ID )) {
			return $post->ID;
		}
	
		if ( $post->post_type == 'revision' ) {
			return; // Don't store custom data twice
		}
	
		switch($post->post_type) { // Do different things based on the post type
			case "gp_budget":
				if ( ( isset( $_POST['gp-budget-print'] ) ) && ( isset( $_POST['gp-budget-id'] ) ) ) {
				
					include_once GESTIONPYMES_CORE_DIR . '/mpdf/mpdf.php';
				
					$budget_number = get_post_meta( $post->ID, '_gp_budget_number', TRUE );
				
					$tableVar = GP_PDF_Template::getBudgetContent( $_POST['gp-budget-id'] );
					$stylesheet = GP_PDF_Template::getBudgetCSS( $_POST['gp-budget-id'] );
				
					$mpdf=new mPDF();
				
					$mpdf->SetHTMLFooter( GP_PDF_Template::getBudgetFooterContent( $_POST['gp-budget-id'] ) );
				
					$mpdf->WriteHTML($stylesheet,1);
					$mpdf->WriteHTML($tableVar,2);
					$mpdf->Output( __( 'budget-', 'gestion-pymes' ) . $budget_number . '.pdf','D');
					exit;
				}
				// to Invoice
				if ( ( isset( $_POST['gp-budget-to-invoice'] ) ) && ( isset( $_POST['gp-budget-id'] ) ) ) {
					$invoice_id = GestionPymes::budgetToInvoice( $_POST['gp-budget-id'] );
					wp_redirect( admin_url( 'post.php?post=' . $invoice_id .'&action=edit' ) );
					exit;
				}
				
				if ( (!isset( $_POST['gp_budget_information'] ) ) || ( !wp_verify_nonce( $_POST['gp_budget_information'], plugin_basename(__FILE__) ) ) ) {
					return $post->ID;
				}
				// Number
				if ( isset( $_POST['_gp_budget_number'] ) ) {
					$value = sanitize_text_field( $_POST['_gp_budget_number'] );
					if ( get_post_meta( $post->ID, '_gp_budget_number', FALSE ) ) { // If the custom field already has a value
						update_post_meta( $post->ID, '_gp_budget_number', $value );
					} else { // If the custom field doesn't have a value
						add_post_meta( $post->ID, '_gp_budget_number', $value );
					}
				}
				// Date
				if ( isset( $_POST['_gp_budget_date'] ) ) {
					$value = sanitize_text_field( $_POST['_gp_budget_date'] );
					$value = sanitize_text_field( apply_filters('gestion_pymes_budget_date', $value) );
					if ( get_post_meta( $post->ID, '_gp_budget_date', FALSE ) ) { // If the custom field already has a value
						update_post_meta( $post->ID, '_gp_budget_date', $value );
					} else { // If the custom field doesn't have a value
						add_post_meta( $post->ID, '_gp_budget_date', $value );
					}
				}
				// TAX
				if ( isset( $_POST['_gp_budget_tax'] ) ) {
					$value = sanitize_text_field( $_POST['_gp_budget_tax'] );
					if ( get_post_meta( $post->ID, '_gp_budget_tax', FALSE ) ) { // If the custom field already has a value
						update_post_meta( $post->ID, '_gp_budget_tax', $value );
					} else { // If the custom field doesn't have a value
						add_post_meta( $post->ID, '_gp_budget_tax', $value );
					}
				}
				// IRPF
				if ( isset( $_POST['_gp_budget_irpf'] ) ) {
					$value = sanitize_text_field( $_POST['_gp_budget_irpf'] );
					if ( !$value || ( strlen($value) <= 0 ) ) {
					    $value = 0;
					}
					if ( get_post_meta( $post->ID, '_gp_budget_irpf', FALSE ) ) { // If the custom field already has a value
						update_post_meta( $post->ID, '_gp_budget_irpf', $value );
					} else { // If the custom field doesn't have a value
						add_post_meta( $post->ID, '_gp_budget_irpf', $value );
					}
				}
				// Customer
				if ( isset( $_POST['_gp_budget_customer'] ) ) {
					$value = sanitize_text_field( $_POST['_gp_budget_customer'] );
					if ( get_post_meta( $post->ID, '_gp_budget_customer', FALSE ) ) { // If the custom field already has a value
						update_post_meta( $post->ID, '_gp_budget_customer', $value );
					} else { // If the custom field doesn't have a value
						add_post_meta( $post->ID, '_gp_budget_customer', $value );
					}
				}
				// items
				if ( isset( $_POST['gp-budget-desc'] ) ) {
					$descriptions = array();
					foreach ( $_POST['gp-budget-desc'] as $description ) {
					    $descriptions[] = sanitize_text_field( ($description) );
					}
					$values = maybe_serialize( $descriptions );
					update_post_meta( $post->ID, 'gp-budget-desc', addslashes($values) );
				}
				if ( isset( $_POST['gp-budget-cant'] ) ) {
					$cants = array();
					foreach ( $_POST['gp-budget-cant'] as $cant ) {
					    // We use . as decimal separator
					    $cants[] = sanitize_text_field( str_replace(',', '.', $cant) );
					}
					$values = maybe_serialize( $cants );
					update_post_meta( $post->ID, 'gp-budget-cant', $values );
				}
				if ( isset( $_POST['gp-budget-price'] ) ) {
					$prices = array();
					foreach ( $_POST['gp-budget-price'] as $price ) {
					    // We use . as decimal separator
						$prices[] = sanitize_text_field( str_replace(',', '.', $price) );
					}
					$values = maybe_serialize( $prices );
					update_post_meta( $post->ID, 'gp-budget-price', $values );
				}
				break;
		}
	}

}
GP_Budgets::init();