<?php
/*
Plugin Name: GS CRM Company
Description: GS CRM Company 
Plugin URI: https://gsoulinc.com/
Author URI: https://gsoulinc.com/
Author: Sungyong Kim
License: Public Domain
Version: 2.8
*/


global $gsb_db_version;
$gsb_db_version = '1.0';

// Register Custom Post Type Company
function create_crm_company() {
    $labels = array(
    'name'               => _x( 'Companies', 'post type general name', 'sw-clients' ),
    'singular_name'      => _x( 'Company', 'post type singular name', 'sw-clients' ),
    'menu_name'          => __( 'Companies', 'admin menu', 'sw-clients' ),
    'name_admin_bar'     => __( 'Company', 'add new on admin bar', 'sw-clients' ),
    'add_new'            => _x( 'Add New', 'company', 'sw-clients' ),
    'add_new_item'       => __( 'Add New Company', 'sw-clients' ),
    'new_item'           => __( 'New Company', 'sw-clients' ),
    'edit_item'          => __( 'Edit Company', 'sw-clients' ),
    'view_item'          => __( 'View Company', 'sw-clients' ),
    'all_items'          => __( 'All Companies', 'sw-clients' ),
    'search_items'       => __( 'Search Companies', 'sw-clients' ),
    'parent_item_colon'  => __( 'Parent Companies:', 'sw-clients' ),
    'not_found'          => __( 'No Companies found.', 'sw-clients' ),
    'not_found_in_trash' => __( 'No Companies found in Trash.', 'sw-clients' )
    );

    /*
     * The $supports parameter describes what the post type supports
     */
    $supports = array(
        'title',        // Post title
        'editor',       // Post content
        'excerpt',      // Allows short description
        'author',       // Allows showing and choosing author
        'thumbnail',    // Allows feature images
//        'comments',     // Enables comments
//        'trackbacks',   // Supports trackbacks
        'revisions',    // Shows autosaved version of the posts
//        'custom-fields' // Supports by custom fields
    );

    $args = array(
        'labels'              => $labels,
        'description'         => __( 'Description.', 'sw-clients' ), // Description
        'public'              => true,  // Makes the post type public
        'publicly_queryable'  => true,  // Allows queries to be performed on the front-end part if set to true
        'show_ui'             => true,  // Displays an interface for this post type
        'show_in_menu'        => true,  // Displays in the Admin Menu (the left panel)
        'show_in_nav_menus'   => true,  // Displays in Appearance -> Menus
        'show_in_admin_bar'   => true,  // Displays in the black admin bar
		'show_in_rest'        => true,
		'query_var'           => true,
    	'rewrite'             => array( 'slug' => 'company' ),
        'capability_type'     => 'post', // Allows read, edit, delete like “Post”
        'has_archive'         => true,  // Enables post type archive (by month, date, or year)
        'hierarchical'        => false, // Allows hierarchical categorization, if set to false, the Custom Post Type will behave like Post, else it will behave like Page
        'menu_position'       => 2,     // The position number in the left menu
		'show_in_rest'        => true,
    	'rest_base'           => 'company',
    	'rest_controller_class' => 'WP_REST_Posts_Controller',
		'menu_icon'   			=> 'dashicons-building',
        'supports'            => $supports,
        'taxonomies'          => array( 'category', 'post_tag' ), // Allowed taxonomies
        'can_export'          => true,  // Allows content export using Tools -> Export
        'exclude_from_search' => false // Excludes posts of this type in the front-end search result page if set to true, include them if set to false
    );
	register_post_type( 'company', $args );
	
	
	global $wpdb;
	global $gsb_db_version;

	$table_name = $wpdb->prefix . 'gs_billing';
	
	$charset_collate = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE $table_name (
		id mediumint(9) NOT NULL AUTO_INCREMENT,
		post_id tinytext,
		billing_id tinytext,
		billing_created datetime DEFAULT '0000-00-00 00:00:00',
		billing_status tinytext,
		billing_completed datetime DEFAULT '0000-00-00 00:00:00',
		billing_account tinytext,
		billing_method tinytext,
		billing_term tinytext,
		billing_amount tinytext,
		billing_tax tinytext,
		billing_date datetime DEFAULT '0000-00-00 00:00:00',
		billing_period tinytext,
		billing_total tinytext,
		billing_paid_method tinytext,
		billing_paid_amount tinytext,
		billing_bank_name tinytext,
		billing_check_num tinytext,
		billing_note text,
		billing_updated datetime DEFAULT '0000-00-00 00:00:00',
		PRIMARY KEY  (id)
	) $charset_collate;";

	require_once ABSPATH . 'wp-admin/includes/upgrade.php';
	dbDelta( $sql );

	add_option( 'gsb_db_version', $gsb_db_version );

}
add_action( 'init', 'create_crm_company', 0 );
add_theme_support( 'post-thumbnails', array( 'post', 'company' ) );

function gs_add_metabox_settings(){
	add_meta_box("gs_company_meta", "Company Information", "company_display_options", "company", "normal", "high");
}
add_action("admin_init", "gs_add_metabox_settings");

function gs_company_table_content( $column_name, $post_id ) {
	if ($column_name == 'signal_number') {
		$status = get_post_meta( $post_id, 'signal_number', true );
		echo $status;
	}
	if ($column_name == 'signal_sub') {
		$status = get_post_meta( $post_id, 'signal_sub', true );
		echo $status;
	}
    if ($column_name == 'address') {
    $status = get_post_meta( $post_id, 'com_address', true )." ";
    $status .= get_post_meta( $post_id, 'com_address2', true )." ";
    $status .= get_post_meta( $post_id, 'com_city', true ).", ";
    $status .= get_post_meta( $post_id, 'com_state', true )." ";
    $status .= get_post_meta( $post_id, 'com_zip', true )." ";
    echo $status;
    }
    if ($column_name == 'billing_date') {
    $status = get_post_meta( $post_id, 'billing_date', true )." ";
    echo $status;
    }
    if ($column_name == 'phone') {
		$data = get_post_meta( $post_id, 'phone', true );

		$number = preg_replace("/[^\d]/", "", $data);
 
		// get number length.
		$length = strlen($number);
 
 		// if number = 10
 		if($length == 10) {
			$number = preg_replace("/^1?(\d{3})(\d{3})(\d{4})$/", "($1) $2-$3", $number);
		}
		echo $number;
    }

}
add_action( 'manage_company_posts_custom_column', 'gs_company_table_content', 10, 2 );

function add_company_columns ( $columns ) {
	unset($columns['author']);
	unset($columns['categories']);
	unset($columns['tags']);
	unset($columns['date']);
	return array_merge ( $columns, array ( 
		'signal_number' => __ ( 'Account Number' ),
		'signal_sub' 	=> __ ( 'Radio Number' ),
		'billing_date'	=> __ ( 'Billing Date' ),
		'address'		=> __ ( 'Address' ),
		'phone'			=> __ ( 'Phone' ),
		'author'		=> __ ( 'Author' ),
		'categories'	=> __ ( 'Categories' ),
		'tags'			=> __ ( 'tags' ),
		'date'			=> __ ( 'Date' )
	) );
}
add_filter ( 'manage_company_posts_columns', 'add_company_columns' );

function gs_company_table_sorting( $columns ) {
  $columns['signal_number'] = 'signal_number';
  return $columns;
}
add_filter( 'manage_edit-event_sortable_columns', 'gs_company_table_sorting' );


function gs_company_date_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'signal_number' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'signal_number',
            'orderby' => 'meta_value'
        ) );
    }

    return $vars;
}
add_filter( 'request', 'gs_company_date_column_orderby' );


function gs_billing_date_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'signal_number' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'billing_date',
            'orderby' => 'meta_value'
        ) );
    }

    return $vars;
}
add_filter( 'request', 'gs_billing_date_column_orderby' );



function company_display_options($callback_args) {
	global $post;
	global $wpdb;
	
	$thumbs = array();
	$custom = get_post_custom($post->ID);
	
	$master_code 		= isset($custom["master_code"][0]) ? $custom["master_code"][0] : '';
	$signal_number 		= isset($custom["signal_number"][0]) ? $custom["signal_number"][0] : '';
	$signal_sub			= isset($custom["signal_sub"][0]) ? $custom["signal_sub"][0] : '';
	$installer 			= isset($custom["installer"][0]) ? $custom["installer"][0] : '';
	$install_date 		= isset($custom["install_date"][0]) ? $custom["install_date"][0] : '';
	$dealer_number 		= isset($custom["dealer_number"][0]) ? $custom["dealer_number"][0] : '';
	$time_zone	 		= isset($custom["time_zone"][0]) ? $custom["time_zone"][0] : '';
	$location_type		= isset($custom["location_type"][0]) ? $custom["location_type"][0] : '';
	$passcode			= isset($custom["passcode"][0]) ? $custom["passcode"][0] : '';
	$phone				= isset($custom["phone"][0]) ? $custom["phone"][0] : '';
	$phone2				= isset($custom["phone2"][0]) ? $custom["phone2"][0] : '';
	$com_email			= isset($custom["com_email"][0]) ? $custom["com_email"][0] : '';
	$com_address		= isset($custom["com_address"][0]) ? $custom["com_address"][0] : '';
	$com_address2		= isset($custom["com_address2"][0]) ? $custom["com_address2"][0] : '';
	$com_city			= isset($custom["com_city"][0]) ? $custom["com_city"][0] : '';
	$com_state			= isset($custom["com_state"][0]) ? $custom["com_state"][0] : '';
	$com_zip			= isset($custom["com_zip"][0]) ? $custom["com_zip"][0] : '';
	$com_street			= isset($custom["com_street"][0]) ? $custom["com_street"][0] : '';
	$com_county			= isset($custom["com_county"][0]) ? $custom["com_county"][0] : '';
	
	$open_set			= isset($custom["open_set"][0]) ? $custom["open_set"][0] : '';
	$open_note			= isset($custom["open_note"][0]) ? $custom["open_note"][0] : '';
	$open_mon			= isset($custom["open_mon"][0]) ? $custom["open_mon"][0] : '';
	$open_tue			= isset($custom["open_tue"][0]) ? $custom["open_tue"][0] : '';
	$open_wed			= isset($custom["open_wed"][0]) ? $custom["open_wed"][0] : '';
	$open_thu			= isset($custom["open_thu"][0]) ? $custom["open_thu"][0] : '';
	$open_fri			= isset($custom["open_fri"][0]) ? $custom["open_fri"][0] : '';
	$open_sat			= isset($custom["open_sat"][0]) ? $custom["open_sat"][0] : '';
	$open_sun			= isset($custom["open_sun"][0]) ? $custom["open_sun"][0] : '';
	$close_mon			= isset($custom["close_mon"][0]) ? $custom["close_mon"][0] : '';
	$close_tue			= isset($custom["close_tue"][0]) ? $custom["close_tue"][0] : '';
	$close_wed			= isset($custom["close_wed"][0]) ? $custom["close_wed"][0] : '';
	$close_thu			= isset($custom["close_thu"][0]) ? $custom["close_thu"][0] : '';
	$close_fri			= isset($custom["close_fri"][0]) ? $custom["close_fri"][0] : '';
	$close_sat			= isset($custom["close_sat"][0]) ? $custom["close_sat"][0] : '';
	$close_sun			= isset($custom["close_sun"][0]) ? $custom["close_sun"][0] : '';
	
	$contact			= isset($custom["contact"][0]) ? $custom["contact"][0] : '';
	$contact_code		= isset($custom["contact_code"][0]) ? $custom["contact_code"][0] : '';
	$contact_email		= isset($custom["contact_email"][0]) ? $custom["contact_email"][0] : '';
	$contact_phone		= isset($custom["contact_phone"][0]) ? $custom["contact_phone"][0] : '';
	$contact_phone2		= isset($custom["contact_phone2"][0]) ? $custom["contact_phone2"][0] : '';
	$contact2			= isset($custom["contact2"][0]) ? $custom["contact2"][0] : '';
	$contact2_code		= isset($custom["contact2_code"][0]) ? $custom["contact2_code"][0] : '';
	$contact2_email		= isset($custom["contact2_email"][0]) ? $custom["contact2_email"][0] : '';
	$contact2_phone		= isset($custom["contact2_phone"][0]) ? $custom["contact2_phone"][0] : '';
	$contact2_phone2	= isset($custom["contact2_phone2"][0]) ? $custom["contact2_phone2"][0] : '';
	$contact3			= isset($custom["contact3"][0]) ? $custom["contact3"][0] : '';
	$contact3_code		= isset($custom["contact3_code"][0]) ? $custom["contact3_code"][0] : '';
	$contact3_email		= isset($custom["contact3_email"][0]) ? $custom["contact3_email"][0] : '';
	$contact3_phone		= isset($custom["contact3_phone"][0]) ? $custom["contact3_phone"][0] : '';
	$contact3_phone2	= isset($custom["contact3_phone2"][0]) ? $custom["contact3_phone2"][0] : '';
	$contact4			= isset($custom["contact4"][0]) ? $custom["contact4"][0] : '';
	$contact4_code		= isset($custom["contact4_code"][0]) ? $custom["contact4_code"][0] : '';
	$contact4_email		= isset($custom["contact4_email"][0]) ? $custom["contact4_email"][0] : '';
	$contact4_phone		= isset($custom["contact4_phone"][0]) ? $custom["contact4_phone"][0] : '';
	$contact4_phone2	= isset($custom["contact4_phone2"][0]) ? $custom["contact4_phone2"][0] : '';
	$billing_method		= isset($custom["billing_method"][0]) ? $custom["billing_method"][0] : '';
	$billing_term		= isset($custom["billing_term"][0]) ? $custom["billing_term"][0] : '';
	$billing_amount		= isset($custom["billing_amount"][0]) ? $custom["billing_amount"][0] : '';
	$billing_tax		= isset($custom["billing_tax"][0]) ? $custom["billing_tax"][0] : '';
	$billing_date		= isset($custom["billing_date"][0]) ? $custom["billing_date"][0] : '';
	$billing_up			= isset($custom["billing_up"][0]) ? $custom["billing_up"][0] : '';
	$billing_diff		= isset($custom["billing_diff"][0]) ? $custom["billing_diff"][0] : '';
	$billing_address	= isset($custom["billing_address"][0]) ? $custom["billing_address"][0] : '';
	$billing_address2	= isset($custom["billing_address2"][0]) ? $custom["billing_address2"][0] : '';
	$billing_city		= isset($custom["billing_city"][0]) ? $custom["billing_city"][0] : '';
	$billing_state		= isset($custom["billing_state"][0]) ? $custom["billing_state"][0] : '';
	$billing_zip		= isset($custom["billing_zip"][0]) ? $custom["billing_zip"][0] : '';
	$billing_note		= isset($custom["billing_note"][0]) ? $custom["billing_note"][0] : '';

	$test_timer			= isset($custom["test_timer"][0]) ? $custom["test_timer"][0] : '';
	$timer_event		= isset($custom["timer_event"][0]) ? $custom["timer_event"][0] : '';
	$timer_not1			= isset($custom["timer_not1"][0]) ? $custom["timer_not1"][0] : '';
	$timer_not2			= isset($custom["timer_not2"][0]) ? $custom["timer_not2"][0] : '';
	$timer_not3			= isset($custom["timer_not3"][0]) ? $custom["timer_not3"][0] : '';
	$timer_not4			= isset($custom["timer_not4"][0]) ? $custom["timer_not4"][0] : '';
	$comm_maker			= isset($custom["comm_maker"][0]) ? $custom["comm_maker"][0] : '';
	$comm_phone			= isset($custom["comm_phone"][0]) ? $custom["comm_phone"][0] : '';
	$comm_phone2		= isset($custom["comm_phone2"][0]) ? $custom["comm_phone2"][0] : '';
	$comm_type1			= isset($custom["comm_type1"][0]) ? $custom["comm_type1"][0] : '';
	$comm_type2			= isset($custom["comm_type2"][0]) ? $custom["comm_type2"][0] : '';
	$comm_type3			= isset($custom["comm_type3"][0]) ? $custom["comm_type3"][0] : '';
	$comm_type4			= isset($custom["comm_type4"][0]) ? $custom["comm_type4"][0] : '';
	$comm_type5			= isset($custom["comm_type5"][0]) ? $custom["comm_type5"][0] : '';
	$comm_type6			= isset($custom["comm_type6"][0]) ? $custom["comm_type6"][0] : '';
	$comm_type7			= isset($custom["comm_type7"][0]) ? $custom["comm_type7"][0] : '';
	$comm_type8			= isset($custom["comm_type8"][0]) ? $custom["comm_type8"][0] : '';
	$comm_trans1		= isset($custom["comm_trans1"][0]) ? $custom["comm_trans1"][0] : '';
	$comm_trans2		= isset($custom["comm_trans2"][0]) ? $custom["comm_trans2"][0] : '';
	$comm_trans3		= isset($custom["comm_trans3"][0]) ? $custom["comm_trans3"][0] : '';
	$comm_trans4		= isset($custom["comm_trans4"][0]) ? $custom["comm_trans4"][0] : '';
	$comm_provider		= isset($custom["comm_provider"][0]) ? $custom["comm_provider"][0] : '';
	$comm_service		= isset($custom["comm_service"][0]) ? $custom["comm_service"][0] : '';

	
	//if(function_exists('pf_show_link')){
	//echo pf_show_link();} 
 	if(isset($signal_number)){ 
					$postid = $post->ID;
					$invoice_info 	= check_last_invoice($post->ID);
					$invoiceid		= $invoice_info[0]->billing_id;
					if($invoiceid==""){
?>

	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold;">Create Billing Information </h2>
	</p>
	<table style="width: 100%">
		<tr>
			<td>
			<label for="billing_term">Payment Method:</label>
				<?php $b_method = get_post_meta( $post->ID, 'billing_method', true );
				//print_r($b_method);?>
            <select name="billing_method" id="billing_method" style="width:100%;">
				<option value="" <?php selected( $b_method, '' ); ?>>Select Billing Method</option>
				<option value="Mail" <?php selected( $b_method, 'Mail' )?" selected ":""; ?>>Mail</option>
				<option value="Pickup" <?php selected( $b_method, 'Pickup' )?" selected ":""; ?>>Pickup</option>
				<option value="Autopay" <?php selected( $b_method, 'Autopay' )?" selected ":""; ?>>Autopay</option>
				<option value="Card" <?php selected( $b_method, 'Card' )?" selected ":""; ?>>Card</option>
				<option value="Email" <?php selected( $b_method, 'Email' )?" selected ":""; ?>>Email</option>
				<option value="Other" <?php selected( $b_method, 'Other' )?" selected ":""; ?>>Other</option>
				<option value="Canceled" <?php selected( $b_method, 'Canceled' )?" selected ":""; ?>>Canceled</option>
			</select>
			</td>
			<td>
			<label for="billing_term">Billing Term:</label>
				<?php $b_value = get_post_meta( $post->ID, 'billing_term', true );
				//echo $vab_valuelue." value";?>
            <select name="billing_term" id="billing_term" style="width:100%;" required>
				<option value="" <?php selected( $b_value, '' ); ?>>Select Billing Term</option>
				<option value="0" <?php selected( $b_value, '0' )?" selected ":""; ?>>Menual Billing</option>
				<option value="1" <?php selected( $b_value, '1' )?" selected ":""; ?>>Every Month</option>
				<option value="2" <?php selected( $b_value, '2' )?" selected ":""; ?>>Bi-Monthly</option>
				<option value="3" <?php selected( $b_value, '3' )?" selected ":""; ?>>3 Month</option>
				<option value="6" <?php selected( $b_value, '6' )?" selected ":""; ?>>6 Month</option>
				<option value="12" <?php selected( $b_value, '12' )?" selected ":""; ?>>Yearly</option>
			</select>
			</td>
			<td>
			<label for="billing_amount">Billing Amount:</label>
			<input name="billing_amount" id="billing_amount" type="text" value="<?php echo esc_attr($billing_amount); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="billing_tax">Tax Rate %:</label>
			<input name="billing_tax" id="billing_tax" type="text" value="<?php echo esc_attr($billing_tax); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="billing_date">Next Billing Date:</label>
			<input name="billing_date" id="billing_date" type="date" value="<?php echo esc_attr($billing_date); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td>
			<label for="billing_diff">Billing Address Different? </label>
			<?php $d_value = get_post_meta( $post->ID, 'billing_diff', true );?>
			<input type="checkbox" id="billing_diff" name="billing_diff" value="1" <?php checked($d_value, 1); ?>><label for="billing_diff"> Yes</label>
			</td>
			<td colspan="3">
			<label for="billing_note">Billing Note:</label>
			<input name="billing_note" id="billing_note" type="text" value="<?php echo esc_attr($billing_note); ?>" style="width:100%;" />
			</td>
			<td class="billing_btn">
			<label for="create_invoice">
				<a href="#create_invoice" id="create_invoice" class="create_invoice btn" data-postid="<?php echo $postid; ?>" data-accountid="<?php echo $signal_number; ?>">Create New Invoice</a>
			</label>
			</td>
		</tr>
	</table>	
	<table id="billing_addr" style="width: 100%; <? echo ($d_value)!="1"? " display: none;":" display: block;"; ?>">
		<tr>
			<td colspan="2">
			<label for="billing_address">Address:</label>
			<input name="billing_address" id="billing_address" type="text" value="<?php echo esc_attr($billing_address); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="billing_address2">Address2 (Suite, Unit):</label>
			<input name="billing_address2" id="billing_address2" type="text" value="<?php echo esc_attr($billing_address2); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td>
			<label for="billing_city">City:</label>
			<input name="billing_city" id="billing_city" type="text" value="<?php echo esc_attr($billing_city); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="billing_state">State:</label>
			<input name="billing_state" id="billing_state" type="text" value="<?php echo esc_attr($billing_state); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="billing_zip">Zip:</label>
			<input name="billing_zip" id="billing_zip" type="text" value="<?php echo esc_attr($billing_zip); ?>" style="width:100%;" />
			</td>
		</tr>
	</table>	
	<?php
		}else{
		$invoiceid = $invoice_info[0]->billing_id;
	?>

	<div id="billing_update" style="width: 100%;">
	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold;">Current Invoice #<b><?php echo $invoiceid;?></b></h2>
	</p>
	<table style="width: 100%;">
		<tr>
			<td>Invoice #: <?php echo $invoiceid;?><br>Billing Created: <?php echo date("m/d/Y", strtotime($invoice_info[0]->billing_created));?></td>
			<td>Billing Method:
				<?php 
					$b_method = get_post_meta( $post->ID, 'billing_method', true );
				//print_r($b_method);
				?>
				<select name="billing_update_method" id="billing_update_method" style="width:100%;">
					<option value="" <?php selected( $b_method, '' ); ?>>Select Billing Method</option>
					<option value="Mail" <?php selected( $b_method, 'Mail' )?" selected ":""; ?>>Mail</option>
					<option value="Pickup" <?php selected( $b_method, 'Pickup' )?" selected ":""; ?>>Pickup</option>
					<option value="Autopay" <?php selected( $b_method, 'Autopay' )?" selected ":""; ?>>Autopay</option>
					<option value="Card" <?php selected( $b_method, 'Card' )?" selected ":""; ?>>Card</option>
					<option value="Email" <?php selected( $b_method, 'Email' )?" selected ":""; ?>>Email</option>
					<option value="Other" <?php selected( $b_method, 'Other' )?" selected ":""; ?>>Other</option>
					<option value="Canceled" <?php selected( $b_method, 'Canceled' )?" selected ":""; ?>>Canceled</option>
				</select>
			</td>
			<td>Billing Period: 
				<?php
					$billing_update_period = date("m/d/Y", strtotime(esc_attr(get_post_meta( $post->ID, 'billing_date', true ))))."~".date("m/d/Y", strtotime(get_post_meta( $post->ID, 'billing_date', true ). " + ".get_post_meta( $post->ID, 'billing_term', true )." months"));
				?>
				<input name="billing_update_period" id="billing_update_period" type="text" value="<?php echo $billing_update_period;?>" style="width:100%;" />
			</td>
			<td>Next Billing Date: <input name="billing_update_next" id="billing_update_next" type="date" value="<?php echo esc_attr($billing_date); ?>" style="width:100%;" /></td>
			<td></td>
		</tr>
		<tr>
			<td>
			<label for="billing_term">Billing Term:</label>
				<?php $b_value = get_post_meta( $post->ID, 'billing_term', true );
				//echo $vab_valuelue." value";?>
            <select name="billing_update_term" id="billing_update_term" style="width:100%;" >
				<option value="" <?php selected( $b_value, '' ); ?>>Select Billing Term</option>
				<option value="0" <?php selected( $b_value, '0' )?" selected ":""; ?>>Menual Billing</option>
				<option value="1" <?php selected( $b_value, '1' )?" selected ":""; ?>>Every Month</option>
				<option value="2" <?php selected( $b_value, '2' )?" selected ":""; ?>>Bi-Monthly</option>
				<option value="3" <?php selected( $b_value, '3' )?" selected ":""; ?>>3 Month</option>
				<option value="6" <?php selected( $b_value, '6' )?" selected ":""; ?>>6 Month</option>
				<option value="12" <?php selected( $b_value, '12' )?" selected ":""; ?>>Yearly</option>
			</select>
			</td>
			<td>
			<label for="billing_update_amount">Billing Amount:</label>
			<input name="billing_update_amount" id="billing_update_amount" type="text" value="<?php echo esc_attr($billing_amount); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="billing_update_tax">Tax Rate %:</label>
			<input name="billing_update_tax" id="billing_update_tax" type="text" value="<?php echo esc_attr($billing_tax); ?>" style="width:100%;" />
			</td>
			<?php
			//print_r($invoice_info[0]);
			$invoice_billing_term = $b_value;
			$invoice_billing_date = date("m/d/Y", strtotime(esc_attr($invoice_info[0]->billing_date)));
			//echo $invoice_billing_date;
			$invoice_next_billing = date("m/d/Y", strtotime($invoice_info[0]->billing_date. " + ".$invoice_billing_term." months"));

			$tax_rate		= number_format(($billing_tax/100), 5,'.', ',');
			$total_amount 	= number_format($billing_amount*$b_value+($billing_amount*$b_value*$tax_rate), 2,'.', ',');

			?>
			<td>Billing Total: <input name="billing_update_period" id="billing_update_period" type="text" value="$<?php echo $total_amount;?>" style="width:100%;" /></td>
			<td></td>
		</tr>
		<tr>
			<td>
			<label for="billing_paid_amount">Paid Amount:</label>
			<input name="billing_paid_amount" id="billing_paid_amount" type="text" value="$<?php echo $total_amount; ?>" style="width:100%;" required/>
			</td>
			<td>
			<label for="billing_paid_method">Paid Method</label>
			<select name="billing_paid_method" id="billing_paid_method" style="width:100%;">
				<option value="" <?php selected( $bp_method, '' ); ?>>Select Paid Method</option>
				<option value="Card" <?php selected( $bp_method, 'Card' )?" selected ":""; ?>>Card</option>
				<option value="Cash" <?php selected( $bp_method, 'Cash' )?" selected ":""; ?>>Cash</option>
				<option value="Check" <?php selected( $bp_method, 'Check' )?" selected ":""; ?>>Check</option>
			</select>
			</td>
			<td>
			<label for="billing_bank_name" >The Bank:</label>
			<input name="billing_bank_name" id="billing_bank_name" type="text" value="<?php echo esc_attr($billing_bank_name); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="billing_check_num">The Check Number:</label>
			<input name="billing_check_num" id="billing_check_num" type="text" value="<?php echo esc_attr($billing_check_num); ?>" style="width:100%;" />
			</td>
			<td></td>
			<tr>
			<td class="billing_btn">
			<a class="btn" href="#submit_udpate" id="submit_udpate" class="submit_udpate" data-postid="<?php echo $postid; ?>" data-invoiceid="<?php echo $invoiceid; ?>" data-accountid="<?php echo esc_attr($signal_number); ?>">Update Payment</a>
			</td>
			</tr>
		</tr>
	</table>
	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold;">Billing History </h2>
		<?php
//		$meta = get_post_meta($postid, '', true);
//		print_r($meta); 
		?>
	</p>
	<table id="POITable" style="width: 100%;">
		<thead class="table_head">
			<tr>
			<td>Status</td>
			<td>Invoice #</td>
			<td>Billing Period</td>
			<td>Billing Paid</td>
			<td>Billing Total</td>
			<td>Paid Method</td>
			<td>Bank</td>
			<td>Check #</td>
			<td>Delete</td>
			</tr>
		</thead>
		<tbody>
		<?php
		$tablename			= $wpdb->prefix.'gs_billing';
		$billing_histories	= $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM ' .$tablename. ' WHERE `post_id` = "'.$postid.'" ORDER BY id DESC LIMIT 7'));
		$history_row = 0;
		foreach ( $billing_histories as $history )
		{
			$h_billing_status 		= $history->billing_status;
			$h_billing_id  			= $history->billing_id;
			$h_billing_period 		= $history->billing_period;
			$h_billing_completed 	= $history->billing_completed;
			$h_billing_paid_amount 	= $history->billing_paid_amount;
			$h_billing_paid_method 	= $history->billing_paid_method;
			$h_billing_bank_name 	= $history->billing_bank_name;
			$h_billing_check_num 	= $history->billing_check_num;
		?>
		<tr>
			<td><?php echo $h_billing_status==0?"Unpaid":"Paid";?></td>
			<td><?php echo $h_billing_id;?></td>
			<td><?php echo $h_billing_period;?></td>
			<td><?php echo $h_billing_status==0?"":date("m/d/Y", strtotime($h_billing_completed)); ?></td>
			<td><?php echo $h_billing_status==0?"":$h_billing_paid_amount;?></td>
			<td><?php echo $h_billing_status==0?"":$h_billing_paid_method;?></td>
			<td><?php echo $h_billing_status==0?"":$h_billing_bank_name;?></td>
			<td><?php echo $h_billing_status==0?"":$h_billing_check_num;?></td>
			<td><?php if($history_row != 0){?>
				<a class="btn" href="#submit_delete" id="submit_delete" class="submit_delete" data-postid="<?php echo $postid; ?>" data-invoiceid="<?php echo $h_billing_id; ?>" onclick="deleteRow(this)">X</a>
				<?php }?>
			</td>
		</tr>

		<?php
			$history_row++;
		}

		?>
		</tbody>
	</table>
<?php
		} ?>
<?php }?>

	</div>
	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold;">Company Information </h2>
	</p>
	<table style="width: 100%">
		<tr>
			<td>
			<label for="master_code">Master Code:</label><?php $m_number = str_pad(mt_rand(0,9999),4,'0',STR_PAD_LEFT);?>
			<input name="master_code" id="master_code" type="text" value="<?php echo esc_attr($master_code)==""?$m_number:$master_code; ?>" style="width:100%;" />
			</td>
			<td>
			<label for="signal_number">Account Number:</label>
			<input name="signal_number" id="signal_number" type="text" value="<?php echo esc_attr($signal_number); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="signal_sub">Radio Number:</label>
			<input name="signal_sub" id="signal_sub" type="text" value="<?php echo esc_attr($signal_sub); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="dealer_number">Dealer Number:</label>
			<input name="dealer_number" id="dealer_number" type="text" value="<?php echo esc_attr($dealer_number); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td>
			<label for="installer">Installer:</label>
			<input name="installer" id="installer" type="text" value="<?php echo esc_attr($installer); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="signal_number">Install date:</label>
			<input name="install_date" id="install_date" type="date" value="<?php echo esc_attr($install_date); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="time_zone">Time Zone:</label>
 				<?php $tz_value = get_post_meta( $post->ID, 'time_zone', true );?>
           <select name="time_zone" id="time_zone" style="width:100%;" required>
				<option value="E" <?php selected( $tz_value, 'E' )?" selected ":""; ?>>E- Eastern</option>
				<option value="C" <?php selected( $tz_value, 'C' )?" selected ":""; ?>>C- Central</option>
				<option value="M" <?php selected( $tz_value, 'M' )?" selected ":""; ?>>M- Mountain</option>
				<option value="P" <?php selected( $tz_value, 'P' )?" selected ":""; ?>>P- Pacific</option>
			</select>
			</td>
			<td>
			<label for="location_type">Location Type:</label>
 				<?php $lt_value = get_post_meta( $post->ID, 'location_type', true );?>
           <select name="location_type" id="location_type" style="width:100%;" required>
				<option value="" <?php selected( $lt_value, '' ); ?>>Select Location Type</option>
				<option value="Residential" <?php selected( $lt_value, 'Residential' )?" selected ":""; ?>>Residential</option>
				<option value="Commercial" <?php selected( $lt_value, 'Commercial' )?" selected ":""; ?>>Commercial</option>
				<option value="Other" <?php selected( $lt_value, 'Other' )?" selected ":""; ?>>Other</option>
			</select>
			</td>
		</tr>
		<tr>
			<td>
			<label for="passcode">Passcode:</label>
			<input name="passcode" id="passcode" type="text" value="<?php echo esc_attr($passcode); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="com_email">E-mail:</label>
			<input name="com_email" id="com_email" type="text" value="<?php echo esc_attr($com_email); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="phone">Phone:</label>
			<input name="phone" id="phone" type="text" value="<?php echo esc_attr($phone); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="phone2">Phone2:</label>
			<input name="phone2" id="phone2" type="text" value="<?php echo esc_attr($phone2); ?>" style="width:100%;" />
			</td>
		</tr>
	</table>
	<table style="width: 100%">
		<tr>
			<td colspan="2">
			<label for="com_address">Address:</label>
			<input name="com_address" id="com_address" type="text" value="<?php echo esc_attr($com_address); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="com_address2">Address2 (Suite, Unit):</label>
			<input name="com_address2" id="com_address2" type="text" value="<?php echo esc_attr($com_address2); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td>
			<label for="com_city">City:</label>
			<input name="com_city" id="com_city" type="text" value="<?php echo esc_attr($com_city); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="com_state">State:</label>
			<input name="com_state" id="com_state" type="text" value="<?php echo esc_attr($com_state); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="com_zip">Zip:</label>
			<input name="com_zip" id="com_zip" type="text" value="<?php echo esc_attr($com_zip); ?>" style="width:100%;" />
			</td>
		</tr>
	</table>

	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold;">Conatct Information </h2>
	</p>
	
	<table style="width: 100%">
		<tr>
			<td colspan="2">
			<label for="contact">Primeary Contact Name</label>
			<input name="contact" id="contact" type="text" value="<?php echo esc_attr($contact); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact_code">Passcode</label>
			<input name="contact_code" id="contact_code" type="text" value="<?php echo esc_attr($contact_code); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact_email">E-mail:</label>
			<input name="contact_email" id="contact_email" type="text" value="<?php echo esc_attr($contact_email); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact_phone">Phone:</label>
			<input name="contact_phone" id="contact_phone" type="text" value="<?php echo esc_attr($contact_phone); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact_phone2">Phone2:</label>
			<input name="contact_phone2" id="contact_phone2" type="text" value="<?php echo esc_attr($contact_phone2); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td colspan="2">
			<label for="contact2">2nd Contact Name</label>
			<input name="contact2" id="contact2" type="text" value="<?php echo esc_attr($contact2); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact2_code">Passcode</label>
			<input name="contact2_code" id="contact2_code" type="text" value="<?php echo esc_attr($contact2_code); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact2_email">E-mail:</label>
			<input name="contact2_email" id="contact2_email" type="text" value="<?php echo esc_attr($contact2_email); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact2_phone">Phone:</label>
			<input name="contact2_phone" id="contact2_phone" type="text" value="<?php echo esc_attr($contact2_phone); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact2_phone2">Phone2:</label>
			<input name="contact2_phone2" id="contact2_phone2" type="text" value="<?php echo esc_attr($contact2_phone2); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td colspan="2">
			<label for="contact3">3rd Contact Name</label>
			<input name="contact3" id="contact3" type="text" value="<?php echo esc_attr($contact3); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact3_code">Passcode</label>
			<input name="contact3_code" id="contact3_code" type="text" value="<?php echo esc_attr($contact3_code); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact3_email">E-mail:</label>
			<input name="contact3_email" id="contact3_email" type="text" value="<?php echo esc_attr($contact3_email); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact3_phone">Phone:</label>
			<input name="contact3_phone" id="contact2_phone" type="text" value="<?php echo esc_attr($contact3_phone); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact3_phone2">Phone2:</label>
			<input name="contact3_phone2" id="contact2_phone2" type="text" value="<?php echo esc_attr($contact3_phone2); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td colspan="2">
			<label for="contact4">4th Contact Name</label>
			<input name="contact4" id="contact4" type="text" value="<?php echo esc_attr($contact4); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact4_code">Passcode</label>
			<input name="contact4_code" id="contact4_code" type="text" value="<?php echo esc_attr($contact4_code); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact4_email">E-mail:</label>
			<input name="contact4_email" id="contact4_email" type="text" value="<?php echo esc_attr($contact4_email); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact4_phone">Phone:</label>
			<input name="contact4_phone" id="contact4_phone" type="text" value="<?php echo esc_attr($contact4_phone); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="contact4_phone2">Phone2:</label>
			<input name="contact4_phone2" id="contact4_phone2" type="text" value="<?php echo esc_attr($contact4_phone2); ?>" style="width:100%;" />
			</td>
		</tr>
	</table>
	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold; width: 100%;">Opening Hours </h2>
		<?php $oc_value = get_post_meta( $post->ID, 'open_set', true );?>
		<span style="width: 100%; float: right; font-size: 14px; font-weight: 700; text-align: right;">
		<label for="open_set" style="">Opening / Closing Set: </label><input type="checkbox" id="open_set" name="open_set" value="1" <?php checked($oc_value, 1); ?>> Yes</span>
	</p>
	<table style="width: 100%">
		<tr>
			<td><label for="open_mon">Day</label></td>
			<td><label for="open_mon">Open</label></td>
			<td><label for="open_mon">Close</label></td>
			<td rowspan="8">
				<label for="open_note">Note</label><br><textarea id="open_note" name="open_note" rows="12" style="width:100%;"><?php echo esc_attr($open_note); ?></textarea>
			</td>
		</tr>
		<tr>
			<td><label for="open_mon">Monday</label></td>
			<td><input name="open_mon" id="open_mon" type="text" value="<?php echo esc_attr($open_mon); ?>" style="width:100%;" /></label></td>
			<td><input name="close_mon" id="close_mon" type="text" value="<?php echo esc_attr($close_mon); ?>" style="width:100%;" /></label></td>
		</tr>
		<tr>
			<td><label for="open_tue">Tuesday</label></td>
			<td><input name="open_tue" id="open_tue" type="text" value="<?php echo esc_attr($open_tue); ?>" style="width:100%;" /></td>
			<td><input name="close_tue" id="close_tue" type="text" value="<?php echo esc_attr($close_tue); ?>" style="width:100%;" /></td>
		</tr>
		<tr>
			<td><label for="open_wed">Wednesday</label></td>
			<td><input name="open_wed" id="open_wed" type="text" value="<?php echo esc_attr($open_wed); ?>" style="width:100%;" /></td>
			<td><input name="close_wed" id="close_wed" type="text" value="<?php echo esc_attr($close_wed); ?>" style="width:100%;" /></td>
		</tr>
		<tr>
			<td><label for="open_thu">Thursday</label></td>
			<td><input name="open_thu" id="open_thu" type="text" value="<?php echo esc_attr($open_thu); ?>" style="width:100%;" /></td>
			<td><input name="close_thu" id="close_thu" type="text" value="<?php echo esc_attr($close_thu); ?>" style="width:100%;" /></td>
		</tr>
		<tr>
			<td><label for="open_fri">Friday</label></td>
			<td><input name="open_fri" id="open_mon" type="text" value="<?php echo esc_attr($open_fri); ?>" style="width:100%;" /></td>
			<td><input name="close_fri" id="close_fri" type="text" value="<?php echo esc_attr($close_fri); ?>" style="width:100%;" /></td>
		</tr>
		<tr>
			<td><label for="open_sat">Saturday</label></td>
			<td><input name="open_sat" id="open_open_satmon" type="text" value="<?php echo esc_attr($open_sat); ?>" style="width:100%;" /></td>
			<td><input name="close_sat" id="close_sat" type="text" value="<?php echo esc_attr($close_sat); ?>" style="width:100%;" /></td>
		</tr>
		<tr>
			<td><label for="open_sun">Sunday</label></td>
			<td><input name="open_sun" id="open_sun" type="text" value="<?php echo esc_attr($open_sun); ?>" style="width:100%;" /></td>
			<td><input name="close_sun" id="close_sun" type="text" value="<?php echo esc_attr($close_sun); ?>" style="width:100%;" /></td>
		</tr>
	</table>
	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold;">Service Information </h2>
	</p>
	<table style="width: 100%">
		<tr>
			<td>
			<label for="test_timer">Test Timer:</label>
				<?php $tt_value = get_post_meta( $post->ID, 'test_timer', true );?>
            <select name="test_timer" id="test_timer" style="width:100%;">
				<option value="0" <?php selected( $tt_value, '0' )?" selected ":""; ?>>None</option>
				<option value="1" <?php selected( $tt_value, '1' )?" selected ":""; ?>>Daily</option>
				<option value="2" <?php selected( $tt_value, '2' )?" selected ":""; ?>>Weekly</option>
				<option value="3" <?php selected( $tt_value, '3' )?" selected ":""; ?>>Monthly</option>
			</select>
			</td>
			<td>
			<label for="timer_event">Test Timer Zone/Event:</label>
			<input name="timer_event" id="timer_event" type="text" value="<?php echo esc_attr($timer_event); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="timer_not">Test Timer Not Received Notification (check all that apply):</label></br>
			<input type="checkbox" id="timer_not1" name="timer_not1" value="0" <?php echo ($timer_not1)=="0"? " checked":"";?>><label for="timer_not1">None</label>
			<input type="checkbox" id="timer_not2" name="timer_not2" value="1" <?php echo ($timer_not2)=="1"? " checked":"";?>><label for="timer_not2">Dealer Email</label>
			<input type="checkbox" id="timer_not3" name="timer_not3" value="2" <?php echo ($timer_not3)=="2"? " checked":"";?>><label for="timer_not3">Contact List</label>
			<input type="checkbox" id="timer_not4" name="timer_not4" value="3" <?php echo ($timer_not4)=="3"? " checked":"";?>><label for="timer_not4">Verification Phone Number</label>
			<?php print_r($ttnvalue);?>
			<!--<input name="timer_not" id="timer_not" type="text" value="<?php echo esc_attr($timer_not); ?>" style="width:100%;" />-->
			</td>
		</tr>
	</table>	
	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold;">System Information </h2>
	</p>
	<table style="width: 100%">
		<tr>
			<td>
			<label for="comm_maker">Communicator Maker/Model:</label>
			<input name="comm_maker" id="comm_maker" type="text" value="<?php echo esc_attr($comm_maker); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="comm_phone">Communicator Phone:</label>
			<input name="comm_phone" id="comm_phone" type="text" value="<?php echo esc_attr($comm_phone); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="comm_phone2">Communicator Phone2:</label>
			<input name="comm_phone2" id="comm_phone2" type="text" value="<?php echo esc_attr($comm_phone2); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td colspan="3">
			<label for="comm_type">Installation Type (check all that apply):</label>
			<input type="checkbox" id="comm_type1" name="comm_type1" value="BURGLARY" <?php echo ($comm_type1)=="BURGLARY"? " checked":" checked";?>><label for="comm_type1">BURGLARY</label>
			<input type="checkbox" id="comm_type2" name="comm_type2" value="FIRE" <?php echo ($comm_type2)=="FIRE"? " checked":"";?>><label for="comm_type2">FIRE</label>
			<input type="checkbox" id="comm_type3" name="comm_type3" value="MEDICAL ALERT" <?php echo ($comm_type3)=="MEDICAL ALERT"? " checked":"";?>><label for="comm_type3">MEDICAL ALERT</label>
			<input type="checkbox" id="comm_type4" name="comm_type4" value="HOLD-UP" <?php echo ($comm_type4)=="HOLD-UP"? " checked":"";?>><label for="comm_type4">HOLD-UP</label>
			<input type="checkbox" id="comm_type5" name="comm_type5" value="ENVIRONMENTAL" <?php echo ($comm_type5)=="ENVIRONMENTAL"? " checked":"";?>><label for="comm_type5">ENVIRONMENTAL</label>
			<input type="checkbox" id="comm_type6" name="comm_type6" value="VIDEO" <?php echo ($comm_type6)=="VIDEO"? " checked":"";?>><label for="comm_type6">VIDEO</label>
			<input type="checkbox" id="comm_type7" name="comm_type7" value="ACCESS" <?php echo ($comm_type7)=="ACCESS"? " checked":"";?>><label for="comm_type7">ACCESS</label>
			<input type="checkbox" id="comm_type8" name="comm_type8" value="OTHER" <?php echo ($comm_type8)=="OTHER"? " checked":"";?>><label for="comm_type8">OTHER</label>
			</td>
		</tr>
		<tr>
			<td colspan="3">
			<label for="comm_trans">Transmission Technology (check all that apply):</label>
			<input type="checkbox" id="comm_trans1" name="comm_trans1" value="DIGITAL" <?php echo ($comm_trans1)=="DIGITAL"? " checked":"";?>><label for="comm_trans1">DIGITAL</label>
			<input type="checkbox" id="comm_trans2" name="comm_trans2" value="CELLULAR" <?php echo ($comm_trans2)=="CELLULAR"? " checked":"";?>><label for="comm_trans2">CELLULAR</label>
			<input type="checkbox" id="comm_trans3" name="comm_trans3" value="INTERNET" <?php echo ($comm_trans3)=="INTERNET"? " checked":"";?>><label for="comm_trans3">INTERNET</label>
			<input type="checkbox" id="comm_trans4" name="comm_trans4" value="RADIO NETWORK" <?php echo ($comm_trans4)=="RADIO NETWORK"? " checked":"";?>><label for="comm_trans4">RADIO NETWORK</label>
			</td>
		</tr>
		<tr>
			<td colspan="2">
			<label for="comm_provider">Service Provider:</label>
			<input name="comm_provider" id="comm_provider" type="text" value="<?php echo esc_attr($comm_provider); ?>" style="width:100%;" />
			</td>
			<td>
			<label for="comm_service">Service Plan:</label>
			<input name="comm_service" id="comm_service" type="text" value="<?php echo esc_attr($comm_service); ?>" style="width:100%;" />
			</td>
		</tr>
	</table>	
	<p style="margin-top: 22px;">
		<h2 style="font-weight: bold;">Zone Information </h2>
	</p>
	<table style="width: 100%">
		<tr>
			<td colspan="4">
			<label for="zone_format">Alarm Format</label>
			<input type="checkbox" id="zone_format1" name="zone_format1" value="0" <?php echo ($zone_format1)=="0"? " checked":"";?>><label for="zone_format1">4/2</label>
			<input type="checkbox" id="zone_format2" name="zone_format2" value="1" <?php echo ($zone_format2)=="1"? " checked":"";?>><label for="zone_format2">CID</label>
			<input type="checkbox" id="zone_format3" name="zone_format3" value="2" <?php echo ($zone_format3)=="2"? " checked":"";?>><label for="zone_format3">SIA</label>
			<input type="checkbox" id="zone_format4" name="zone_format4" value="3" <?php echo ($zone_format4)=="3"? " checked":"";?>><label for="zone_format4">Radionics</label>
			<input type="checkbox" id="zone_format5" name="zone_format5" value="4" <?php echo ($zone_format4)=="4"? " checked":"";?>><label for="zone_format5">Other</label>
			</td>
			<td colspan="2">
			<label for="zone_tid">Custom Template ID</label>
			<input name="zone_tid" id="zone_tid" type="text" value="<?php echo esc_attr($zone_tid); ?>" style="width:100%;" />
			</td>
		</tr>
		<tr>
			<td style="width: 10%;">
			<label for="zone_code">Zone/Code:</label>
			</td>
			<td style="width: 50%;">
			<label for="zone_desc">Description:</label>
			</td>
			<td style="width: 10%;">
			<label for="zone_verify">Verify:</label>
			</td>
			<td style="width: 10%;">
			<label for="zone_agency">Agency:</label>
			</td>
			<td style="width: 10%;">
			<label for="zone_notify">Notify List:</label>
			</td>
			<td style="width: 10%;">
			<label for="zone_email">Email Dealer:</label>
			</td>
		</tr>
		<?php 
		$row_count = 0;
		for($i=0; $i<1000; $i++){
			if(isset($custom["zone_code".$i][0])){
				$row_count++;
			}
		}
		$row_count = $row_count==0?1:$row_count;
		//echo $row_count."rows";
		$row_max = ceil($row_count/10)*10;
		$row_max = $row_max==$row_count?$row_max+9:$row_max;
		for ($zone_i = 0; $zone_i < $row_max; $zone_i++) {
		?>
		<tr>
			<td>
			<?php $zc_value = get_post_meta( $post->ID, 'zone_code'.$zone_i, true );?>
			<input name="zone_code<?php echo $zone_i;?>" id="zone_code<?php echo $zone_i;?>" type="text" value="<?php echo esc_attr($zc_value); ?>" style="width:100%;" />
			</td>
			<td>
			<?php $zd_value = get_post_meta( $post->ID, 'zone_desc'.$zone_i, true );?>
			<input name="zone_desc<?php echo $zone_i;?>" id="zone_desc<?php echo $zone_i;?>" type="text" value="<?php echo esc_attr($zd_value); ?>" style="width:100%;" />
			</td>
			<td>
			<?php $zv_value = get_post_meta( $post->ID, 'zone_verify'.$zone_i, true );?>
			<input name="zone_verify<?php echo $zone_i;?>" id="zone_verify<?php echo $zone_i;?>" type="radio" value="Y" <?php echo ( $zv_value == 'Y' )?" checked ":""; ?> />Y
			<input name="zone_verify<?php echo $zone_i;?>" id="zone_verify<?php echo $zone_i;?>" type="radio" value="N" <?php echo ( $zv_value == 'N' )?" checked ":""; ?> />N
			</td>
			<td>
			<?php $za_value = get_post_meta( $post->ID, 'zone_agency'.$zone_i, true );?>
			<select name="zone_agency<?php echo $zone_i?>" id="zone_agency<?php echo $zone_i?>" style="width:100%;" >
				<option value="" <?php selected( $za_value, '' ); ?>>Select Agency</option>
				<option value="P" <?php selected( $za_value, 'P' )?" selected ":""; ?>>P</option>
				<option value="F" <?php selected( $za_value, 'F' )?" selected ":""; ?>>F</option>
				<option value="M" <?php selected( $za_value, 'M' )?" selected ":""; ?>>M</option>
				<option value="O" <?php selected( $za_value, 'O' )?" selected ":""; ?>>O</option>
			</select>
			</td>
			<td>
			<?php $zn_value = get_post_meta( $post->ID, 'zone_notify'.$zone_i, true );?>
			<input name="zone_notify<?php echo $zone_i;?>" id="zone_notify<?php echo $zone_i;?>" type="radio" value="Y" <?php echo ($zn_value == 'Y')?" checked ":""; ?> />Y
			<input name="zone_notif<?php echo $zone_i;?>" id="zone_notify<?php echo $zone_i;?>" type="radio" value="N" <?php echo ($zn_value == 'N')?" checked ":""; ?> />N
			</td>
			<td>
			<?php $ze_value = get_post_meta( $post->ID, 'zone_email'.$zone_i, true );?>
			<input name="zone_email<?php echo $zone_i;?>" id="zone_email<?php echo $zone_i;?>" type="radio" value="Y" <?php echo ($ze_value == 'Y' )?" checked ":""; ?> />Y
			<input name="zone_email<?php echo $zone_i;?>" id="zone_email<?php echo $zone_i;?>" type="radio" value="N" <?php echo ($ze_value == 'N' )?" checked ":""; ?> />N
			</td>
		</tr>

		<?php
		} // End Zone Record
		?>
	</table>	

	<?php
}
function company_save_details($post_id){
	global $pagenow;
	if ( 'post.php' != $pagenow ) return $post_id;
	
	if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
		return $post_id;	
	
	if (isset($_POST["master_code"])) update_post_meta($post_id, "master_code", stripslashes($_POST["master_code"]));
	if (isset($_POST["signal_number"])) update_post_meta($post_id, "signal_number", stripslashes($_POST["signal_number"]));
	if (isset($_POST["signal_sub"])) update_post_meta($post_id, "signal_sub", stripslashes($_POST["signal_sub"]));
	if (isset($_POST["installer"])) update_post_meta($post_id, "installer", stripslashes($_POST["installer"]));
	if (isset($_POST["install_date"])) update_post_meta($post_id, "install_date", stripslashes($_POST["install_date"]));
	if (isset($_POST["dealer_number"])) update_post_meta($post_id, "dealer_number", stripslashes($_POST["dealer_number"]));
	if (isset($_POST["time_zone"])) update_post_meta($post_id, "time_zone", stripslashes($_POST["time_zone"]));
	if (isset($_POST["location_type"])) update_post_meta($post_id, "location_type", esc_attr($_POST["location_type"]));
	if (isset($_POST["passcode"])) update_post_meta($post_id, "passcode", stripslashes($_POST["passcode"]));
	if (isset($_POST["phone"])) update_post_meta($post_id, "phone", stripslashes($_POST["phone"]));
	if (isset($_POST["phone2"])) update_post_meta($post_id, "phone2", stripslashes($_POST["phone2"]));
	if (isset($_POST["com_email"])) update_post_meta($post_id, "com_email", stripslashes($_POST["com_email"]));
	if (isset($_POST["com_address"])) update_post_meta($post_id, "com_address", stripslashes($_POST["com_address"]));
	if (isset($_POST["com_address2"])) update_post_meta($post_id, "com_address2", stripslashes($_POST["com_address2"]));
	if (isset($_POST["com_city"])) update_post_meta($post_id, "com_city", stripslashes($_POST["com_city"]));
	if (isset($_POST["com_state"])) update_post_meta($post_id, "com_state", esc_attr($_POST["com_state"]));
	if (isset($_POST["com_zip"])) update_post_meta($post_id, "com_zip", stripslashes($_POST["com_zip"]));
	if (isset($_POST["com_street"])) update_post_meta($post_id, "com_street", stripslashes($_POST["com_street"]));
	if (isset($_POST["com_county"])) update_post_meta($post_id, "com_county", stripslashes($_POST["com_county"]));

	if ( isset( $_POST['open_set'] ) ) {   
        update_post_meta( $post_id, 'open_set', '1' );
    } else {
        delete_post_meta( $post_id, 'open_set' );
    }
	if (isset($_POST["open_note"])) update_post_meta($post_id, "open_note", stripslashes($_POST["open_note"]));
	if (isset($_POST["open_mon"])) update_post_meta($post_id, "open_mon", stripslashes($_POST["open_mon"]));
	if (isset($_POST["open_tue"])) update_post_meta($post_id, "open_tue", stripslashes($_POST["open_tue"]));
	if (isset($_POST["open_wed"])) update_post_meta($post_id, "open_wed", stripslashes($_POST["open_wed"]));
	if (isset($_POST["open_thu"])) update_post_meta($post_id, "open_thu", stripslashes($_POST["open_thu"]));
	if (isset($_POST["open_fri"])) update_post_meta($post_id, "open_fri", stripslashes($_POST["open_fri"]));
	if (isset($_POST["open_sat"])) update_post_meta($post_id, "open_sat", stripslashes($_POST["open_sat"]));
	if (isset($_POST["open_sun"])) update_post_meta($post_id, "open_sun", stripslashes($_POST["open_sun"]));
	if (isset($_POST["close_mon"])) update_post_meta($post_id, "close_mon", stripslashes($_POST["close_mon"]));
	if (isset($_POST["close_tue"])) update_post_meta($post_id, "close_tue", stripslashes($_POST["close_tue"]));
	if (isset($_POST["close_wed"])) update_post_meta($post_id, "close_wed", stripslashes($_POST["close_wed"]));
	if (isset($_POST["close_thu"])) update_post_meta($post_id, "close_thu", stripslashes($_POST["close_thu"]));
	if (isset($_POST["close_fri"])) update_post_meta($post_id, "close_fri", stripslashes($_POST["close_fri"]));
	if (isset($_POST["close_sat"])) update_post_meta($post_id, "close_sat", stripslashes($_POST["close_sat"]));
	if (isset($_POST["close_sun"])) update_post_meta($post_id, "close_sun", stripslashes($_POST["close_sun"]));
	
	if (isset($_POST["contact"])) update_post_meta($post_id, "contact", stripslashes($_POST["contact"]));
	if (isset($_POST["contact_code"])) update_post_meta($post_id, "contact_code", stripslashes($_POST["contact_code"]));
	if (isset($_POST["contact_email"])) update_post_meta($post_id, "contact_email", stripslashes($_POST["contact_email"]));
	if (isset($_POST["contact_phone"])) update_post_meta($post_id, "contact_phone", stripslashes($_POST["contact_phone"]));
	if (isset($_POST["contact_phone2"])) update_post_meta($post_id, "contact_phone2", esc_attr($_POST["contact_phone2"]));
	if (isset($_POST["contact2"])) update_post_meta($post_id, "contact2", stripslashes($_POST["contact2"]));
	if (isset($_POST["contact2_code"])) update_post_meta($post_id, "contact2_code", stripslashes($_POST["contact2_code"]));
	if (isset($_POST["contact2_email"])) update_post_meta($post_id, "contact2_email", stripslashes($_POST["contact2_email"]));
	if (isset($_POST["contact2_phone"])) update_post_meta($post_id, "contact2_phone", stripslashes($_POST["contact2_phone"]));
	if (isset($_POST["contact2_phone2"])) update_post_meta($post_id, "contact2_phone2", esc_attr($_POST["contact2_phone2"]));
	if (isset($_POST["contact3"])) update_post_meta($post_id, "contact3", stripslashes($_POST["contact3"]));
	if (isset($_POST["contact3_code"])) update_post_meta($post_id, "contact3_code", stripslashes($_POST["contact3_code"]));
	if (isset($_POST["contact3_email"])) update_post_meta($post_id, "contact3_email", stripslashes($_POST["contact3_email"]));
	if (isset($_POST["contact3_phone"])) update_post_meta($post_id, "contact3_phone", stripslashes($_POST["contact3_phone"]));
	if (isset($_POST["contact3_phone2"])) update_post_meta($post_id, "contact3_phone2", esc_attr($_POST["contact3_phone2"]));
	if (isset($_POST["contact4"])) update_post_meta($post_id, "contact4", stripslashes($_POST["contact4"]));
	if (isset($_POST["contact4_code"])) update_post_meta($post_id, "contact4_code", stripslashes($_POST["contact4_code"]));
	if (isset($_POST["contact4_email"])) update_post_meta($post_id, "contact4_email", stripslashes($_POST["contact4_email"]));
	if (isset($_POST["contact4_phone"])) update_post_meta($post_id, "contact4_phone", stripslashes($_POST["contact4_phone"]));
	if (isset($_POST["contact4_phone2"])) update_post_meta($post_id, "contact4_phone2", esc_attr($_POST["contact4_phone2"]));
	if (isset($_POST["billing_method"])) update_post_meta($post_id, "billing_method", stripslashes($_POST["billing_method"]));
	if (isset($_POST["billing_term"])) update_post_meta($post_id, "billing_term", stripslashes($_POST["billing_term"]));
	if (isset($_POST["billing_amount"])) update_post_meta($post_id, "billing_amount", stripslashes($_POST["billing_amount"]));
	if (isset($_POST["billing_tax"])) update_post_meta($post_id, "billing_tax", stripslashes($_POST["billing_tax"]));
	if (isset($_POST["billing_date"])) update_post_meta($post_id, "billing_date", date("Y-m-d", strtotime(stripslashes($_POST["billing_date"]))));
	if (isset($_POST["billing_note"])) update_post_meta($post_id, "billing_note", stripslashes($_POST["billing_note"]));

	if ( isset( $_POST['billing_diff'] ) ) {   
        update_post_meta( $post_id, 'billing_diff', '1' );
    } else {
        delete_post_meta( $post_id, 'billing_diff' );
    }
	if (isset($_POST["billing_address"])) update_post_meta($post_id, "billing_address", stripslashes($_POST["billing_address"]));
	if (isset($_POST["billing_address2"])) update_post_meta($post_id, "billing_address2", stripslashes($_POST["billing_address2"]));
	if (isset($_POST["billing_city"])) update_post_meta($post_id, "billing_city", stripslashes($_POST["billing_city"]));
	if (isset($_POST["billing_state"])) update_post_meta($post_id, "billing_state", stripslashes($_POST["billing_state"]));
	if (isset($_POST["billing_zip"])) update_post_meta($post_id, "billing_zip", stripslashes($_POST["billing_zip"]));

	if (isset($_POST["test_timer"])) update_post_meta($post_id, "test_timer", stripslashes($_POST["test_timer"]));
	if (isset($_POST["timer_event"])) update_post_meta($post_id, "timer_event", esc_attr($_POST["timer_event"]));
	if (isset($_POST["timer_not1"])) update_post_meta($post_id, "timer_not1", stripslashes($_POST["timer_not1"]));
	if (isset($_POST["timer_not2"])) update_post_meta($post_id, "timer_not2", stripslashes($_POST["timer_not2"]));
	if (isset($_POST["timer_not3"])) update_post_meta($post_id, "timer_not3", stripslashes($_POST["timer_not3"]));
	if (isset($_POST["timer_not4"])) update_post_meta($post_id, "timer_not4", stripslashes($_POST["timer_not4"]));
	if (isset($_POST["comm_maker"])) update_post_meta($post_id, "comm_maker", stripslashes($_POST["comm_maker"]));
	if (isset($_POST["comm_phone"])) update_post_meta($post_id, "comm_phone", stripslashes($_POST["comm_phone"]));
	if (isset($_POST["comm_phone2"])) update_post_meta($post_id, "comm_phone2", stripslashes($_POST["comm_phone2"]));
	if (isset($_POST["comm_type1"])) update_post_meta($post_id, "comm_type1", esc_attr($_POST["comm_type1"]));
	if (isset($_POST["comm_type2"])) update_post_meta($post_id, "comm_type2", esc_attr($_POST["comm_type2"]));
	if (isset($_POST["comm_type3"])) update_post_meta($post_id, "comm_type3", esc_attr($_POST["comm_type3"]));
	if (isset($_POST["comm_type4"])) update_post_meta($post_id, "comm_type4", esc_attr($_POST["comm_type4"]));
	if (isset($_POST["comm_type5"])) update_post_meta($post_id, "comm_type5", esc_attr($_POST["comm_type5"]));
	if (isset($_POST["comm_type6"])) update_post_meta($post_id, "comm_type6", esc_attr($_POST["comm_type6"]));
	if (isset($_POST["comm_type7"])) update_post_meta($post_id, "comm_type7", esc_attr($_POST["comm_type7"]));
	if (isset($_POST["comm_type8"])) update_post_meta($post_id, "comm_type8", esc_attr($_POST["comm_type8"]));
	if (isset($_POST["comm_trans1"])) update_post_meta($post_id, "comm_trans1", stripslashes($_POST["comm_trans1"]));
	if (isset($_POST["comm_trans2"])) update_post_meta($post_id, "comm_trans2", stripslashes($_POST["comm_trans2"]));
	if (isset($_POST["comm_trans3"])) update_post_meta($post_id, "comm_trans3", stripslashes($_POST["comm_trans3"]));
	if (isset($_POST["comm_trans4"])) update_post_meta($post_id, "comm_trans4", stripslashes($_POST["comm_trans4"]));
	if (isset($_POST["comm_provider"])) update_post_meta($post_id, "comm_provider", stripslashes($_POST["comm_provider"]));
	if (isset($_POST["comm_service"])) update_post_meta($post_id, "comm_service", stripslashes($_POST["comm_service"]));
	if (isset($_POST["zone_format1"])) update_post_meta($post_id, "zone_format1", stripslashes($_POST["zone_format1"]));
	if (isset($_POST["zone_format2"])) update_post_meta($post_id, "zone_format2", stripslashes($_POST["zone_format2"]));
	if (isset($_POST["zone_format3"])) update_post_meta($post_id, "zone_format3", stripslashes($_POST["zone_format3"]));
	if (isset($_POST["zone_format4"])) update_post_meta($post_id, "zone_format4", stripslashes($_POST["zone_format4"]));
	if (isset($_POST["zone_format5"])) update_post_meta($post_id, "zone_format5", stripslashes($_POST["zone_format5"]));
	if (isset($_POST["zone_tid"])) update_post_meta($post_id, "zone_tid", stripslashes($_POST["zone_tid"]));
	
	$post_count = 0;
	for($i=0; $i<1000; $i++){
		if($_POST["zone_code".$i]!=""){
			$post_count++;
		}
	}
	//echo $post_count."rows";
	for ($post_i = 0; $post_i < $post_count; $post_i++) {
		if (isset($_POST["zone_code".$post_i])) update_post_meta($post_id, "zone_code".$post_i, stripslashes($_POST["zone_code".$post_i]));
		if (isset($_POST["zone_desc".$post_i])) update_post_meta($post_id, "zone_desc".$post_i, stripslashes($_POST["zone_desc".$post_i]));
		if (isset($_POST["zone_verify".$post_i])) update_post_meta($post_id, "zone_verify".$post_i, stripslashes($_POST["zone_verify".$post_i]));
		if (isset($_POST["zone_agency".$post_i])) update_post_meta($post_id, "zone_agency".$post_i, stripslashes($_POST["zone_agency".$post_i]));
		if (isset($_POST["zone_notify".$post_i])) update_post_meta($post_id, "zone_notify".$post_i, stripslashes($_POST["zone_notify".$post_i]));
		if (isset($_POST["zone_email".$post_i])) update_post_meta($post_id, "zone_email".$post_i, stripslashes($_POST["zone_email".$post_i]));
	}
	
}
add_action('save_post', 'company_save_details');


//  Javascript functions to set/update checkbox

add_action( 'admin_footer', 'quick_edit_javascript' );
function quick_edit_javascript() {
	global $current_screen;
?>
	<script type="text/javascript">
		jQuery(document).ready(function() {
			jQuery("#billing_diff").click(function () {
				jQuery( "#billing_addr" ).toggle();
			});  

			jQuery("#update_invoice").click(function () {
				jQuery( "#billing_update" ).toggle();
			});
		});
	</script>
<?php
}

	
function gs_company_style() {
	$plugin_url = plugin_dir_url( __FILE__ );
	wp_enqueue_style( 'style',  $plugin_url . "css/style.css");
	wp_register_style( 'datatable-style', 'https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css' );

}

add_action( 'admin_print_styles', 'gs_company_style' );

function gs_company_script() {   
    wp_enqueue_script( 'gsb_custom_script', plugin_dir_url( __FILE__ ) . 'js/gsc-script.js' );
	wp_register_script( 'jquery', '//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js', null, null, true );
	wp_register_script( 'datatable', '//cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js', null, null, true );

/*
	<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
*/
}
add_action('wp_enqueue_scripts', 'gs_company_script');


function sw_rest_route_company( $route, $post ) {
    if ( $post->post_type === 'company' ) {
        $route = '/wp/v2/company/' . $post->ID;
    }

    return $route;
}
add_filter( 'rest_route_for_company', 'sw_rest_route_company', 10, 2 );



/**
 * Add REST API support to an already registered post type.

 */

add_filter( 'register_post_type_args', 'my_post_type_args', 10, 2 );

function my_post_type_args( $args, $post_type ) {

    if ( 'company' === $post_type ) {
        $args['show_in_rest'] = true;

        // Optionally customize the rest_base or rest_controller_class
        $args['rest_base']             = 'company';
        $args['rest_controller_class'] = 'WP_REST_Posts_Controller';
    }

    return $args;
}

function me_post_pdf(){
    if (isset($_POST['me_post_pdf'])){
        include 'dompdf/autoload.inc.php';
        global $wp;
        $current_url = home_url(add_query_arg(array(),$wp->request));
        
        $html = file_get_contents($current_url);
        
        $options = new Options();
        $options->set('letter','potrait');
        $options->set('enable_css_float',true);
        $options->set('isHtml5ParserEnabled', true);
    
        $dompdf = new DOMPDF($options);
        $dompdf->loadHtml($html);
    
        $dompdf->render();
    
        $dompdf->stream('title.pdf');
    }
}

add_action('init', 'me_post_pdf');


function create_billing_invoice() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    $('.create_invoice').click(function(){
		const company = document.querySelector("#create_invoice");

		company.dataset.postid; // "3"
		company.dataset.accountid; // "12314"

		var data = {
            action: 'create_billing',
            postid: company.dataset.postid,
            accountid: company.dataset.accountid
        };

        $.post(ajaxurl, data, function(response) {
            alert('Message: ' + response);
        });
		location.reload();
    });


});
</script>
<?php
}
add_action('admin_head', 'create_billing_invoice');


function create_billing_callback() {
	global $wpdb; // this is how you get access to the database

	$post_id 		= $_POST['postid'];
	$account_id 	= $_POST['accountid'];
	$meta 			= get_post_meta($post_id, '', true);
	$bp_value 		= date("m/d/Y", strtotime($meta["billing_date"][0]))."~".date("m/d/Y", strtotime($meta["billing_date"][0]. " + ".$meta["billing_term"][0]." months"));
	//echo $bp_value;
	
	$tablename 		= $wpdb->prefix.'gs_billing';
	$query_select 	= 'SELECT id FROM ' .$tablename. ' WHERE billing_account = '.$account_id.' ORDER BY id DESC LIMIT 1';
	$last_id 		= $wpdb->get_var( 'SELECT id FROM ' .$tablename. ' where  id=(select max(id) from '.$tablename.')'); // select * from <table> where  id=(select max(id) from <table>)
//	$last_id 		= $wpdb->get_var( 'SELECT id FROM ' .$tablename. ' ORDER BY id DESC LIMIT 1'); // select * from <table> where  id=(select max(id) from <table>)
	echo "Last ID is ".$last_id;
	$next_id 		= $last_id+1;
	$prefix 		= "";
	$pad_len 		= 7;
	$billing_number = $next_id+1000;
	echo "Next ID is ".$last_id;
	$billing_id 	= sprintf("%s%s", $prefix, str_pad($billing_number, $pad_len, "0", STR_PAD_LEFT));
	
	$check_pre_billing = $wpdb->get_results( $wpdb->prepare( 'SELECT id, billing_id, billing_status FROM ' .$tablename. ' WHERE `post_id` = "'.$post_id.'" AND `billing_status` = 0 ORDER BY id DESC LIMIT 1'));
	//print_r($meta);
	 
	//echo $check_pre_billing->'billing_status';
	$unpaid_invoice  = "";
	$last_billing_id = "";
	foreach ( $check_pre_billing as $pre_billing_result )
	{
		$unpaid_invoice  = $pre_billing_result->billing_status;
		$last_billing_id = $pre_billing_result->id;
	}
	echo "Status :".$unpaid_invoice ."<br>";
	echo "Last ID :".$last_billing_id ."<br>";
	if($unpaid_invoice!=0||$unpaid_invoice==""){
		
		$bt_value 	= get_post_meta( $post_id, 'billing_term', true );
		$ba_value 	= get_post_meta( $post_id, 'billing_amount', true );
		$bx_value 	= get_post_meta( $post_id, 'billing_tax', true );
		$bm_value 	= get_post_meta( $post_id, 'billing_method', true );
		$bd_value 	= get_post_meta( $post_id, 'billing_date', true );
		
		$bt_value 	= get_post_meta( $post_id, 'billing_term', true );
		$bx_rate	= number_format(($bx_value/100), 5,'.', ',');
		$btl_value 	= number_format($ba_value*$bt_value+($ba_value*$bt_value*$bx_rate), 2,'.', ',');
		$bn_value 	= get_post_meta( $post_id, 'billing_note', true );
		$b_time 	= current_datetime()->format('Y-m-d H:i:s');
		$wpdb->insert( $tablename, array(
			'post_id' 			=> $post_id, 
			'billing_id' 		=> $billing_id, 
			'billing_created' 	=> $b_time,
			'billing_status' 	=> '0', 
			'billing_completed' => "",
			'billing_account' 	=> $account_id, 
			'billing_method' 	=> $bm_value, 
			'billing_term' 		=> $bt_value,
			'billing_amount' 	=> $ba_value, 
			'billing_tax' 		=> $bx_value, 
			'billing_date' 		=> $bd_value, 
			'billing_period' 	=> $bp_value, 
			'billing_total' 	=> $btl_value, 
			'billing_note' 		=> $bn_value,
			'billing_updated' 	=> $b_time),
				  array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) 
        );
		echo "Invoice generated successfully!";
	}else{
		$bt_value 	= get_post_meta( $post_id, 'billing_term', true );
		$ba_value 	= get_post_meta( $post_id, 'billing_amount', true );
		$bx_value 	= get_post_meta( $post_id, 'billing_tax', true );
		$bm_value 	= get_post_meta( $post_id, 'billing_method', true );
		$bd_value 	= get_post_meta( $post_id, 'billing_date', true );
		$bt_value 	= get_post_meta( $post_id, 'billing_term', true );
		$bx_rate	= number_format(($bx_value/100), 5,'.', ',');
		$btl_value 	= number_format($ba_value*$bt_value+($ba_value*$bt_value*$bx_rate), 2,'.', ',');
		$bn_value 	= get_post_meta( $post_id, 'billing_note', true );
		$b_time 	= current_datetime()->format('Y-m-d H:i:s');
		

		$wpdb->update( $tablename, array(
			'billing_id' 		=> $billing_id, 
			'billing_created' 	=> $b_time,
			'billing_status' 	=> '0', 
			'billing_completed' => "",
			'billing_account' 	=> $account_id, 
			'billing_method' 	=> $bm_value, 
			'billing_term' 		=> $bt_value,
			'billing_amount' 	=> $ba_value, 
			'billing_tax' 		=> $bx_value, 
			'billing_date' 		=> $bd_value, 
			'billing_period' 	=> $bp_value, 
			'billing_total' 	=> $btl_value,
			'billing_note' 		=> $bn_value,
			'billing_updated' 	=> $b_time),
			array('ID' => $last_billing_id )
			
        );
		echo "Last ID ". $last_billing_id ."updated billing ID ". $last_billing_id ."<br> value of ". $btl_value;
		echo "Unpaid previous invoice already exist. Invoice data has been updated.";		
	}
	
     exit(); // this is required to return a proper result & exit is faster than die();
}
add_action('wp_ajax_create_billing', 'create_billing_callback');


function update_billing_invoice() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    $('#submit_udpate').click(function(){
		//'id':'".$postid."', 'account_id':'".$signal_number."', 'billing_date':'".$billing_date."', 'billing_diff':'".$billing_diff."'
		const billing = document.querySelector("#submit_udpate");
// The following would also work:
// const article = document.getElementById("electric-cars")

		billing.dataset.postid; // "3"
		billing.dataset.accountid; // "12314"
		billing.dataset.invoiceid; // "12314"
		
		var billing_update_method 	= document.getElementById("billing_update_method").value;
		var billing_update_term 	= document.getElementById("billing_update_term").value;
		var billing_update_amount	= document.getElementById("billing_update_amount").value;
		var billing_update_tax 		= document.getElementById("billing_update_tax").value;
		var billing_update_period 	= document.getElementById("billing_update_period").value;
		var billing_update_next 	= document.getElementById("billing_update_next").value;
		var billing_paid_amount 	= document.getElementById("billing_paid_amount").value;
		var billing_paid_method 	= document.getElementById("billing_paid_method").value;
		var billing_bank_name		= document.getElementById("billing_bank_name").value;
		var billing_check_num 		= document.getElementById("billing_check_num").value;

		var data = {
            action: 'update_billing',
            postid: billing.dataset.postid,
            accountid: billing.dataset.accountid,
            invoiceid: billing.dataset.invoiceid,
			billing_update_method: billing_update_method,
			billing_update_term: billing_update_term,
			billing_update_amount: billing_update_amount,
			billing_update_tax: billing_update_tax,
			billing_update_period: billing_update_period,
			billing_update_next: billing_update_next,
            billing_paid_amount: billing_paid_amount,
            billing_paid_method: billing_paid_method,
            billing_bank_name: billing_bank_name,
            billing_check_num: billing_check_num
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        $.post(ajaxurl, data, function(response) {
            alert('Message: ' + response);
			
        });
		location.reload();
//		$("#billing_update").load(window.location.href + " #billing_update" );
//		document.getElementById("billing_update").style.display="block";
    });


});
</script>
<?php
}
add_action('admin_head', 'update_billing_invoice');

function update_billing_callback() {
	global $wpdb; // this is how you get access to the database

	$post_id 			= $_POST['postid'];
	$invoice_id 		= $_POST['invoiceid'];
	$account_id 		= $_POST['accountid'];
	$meta 				= get_post_meta($post_id, '', true);
	$bp_completed 		= current_datetime()->format('Y-m-d H:i:s');
	$bp_update_method 	= $_POST['billing_update_method'];
	$bp_update_term 	= $_POST['billing_update_term'];
	$bp_update_amount 	= $_POST['billing_update_amount'];
	$bp_update_tax 		= $_POST['billing_update_tax'];
	$bx_rate			= number_format(($bp_update_tax/100), 5,'.', ',');
	$bp_update_total 	= number_format($bp_update_amount*$bp_update_term+($bp_update_amount*$bp_update_tax*$bx_rate), 2,'.', ',');
	$bp_update_period 	= $_POST['billing_update_period'];
	$bp_update_next 	= $_POST['billing_update_next'];
	$bp_paid_amount 	= $_POST['billing_paid_amount'];
	$bp_paid_method 	= $_POST['billing_paid_method'];
	$bp_paid_bank		= $_POST['billing_bank_name'];
	$bp_paid_check		= $_POST['billing_check_num'];
	
	switch($bp_paid_method)
    {
        default:
            // The kind wasn't valid, set it to the default
            $bp_status = '0';
    
        case 'Card':
            $bp_status = '1';
            break;
    
        case 'Cash':
            $bp_status = '2';
            break;
    
        case 'Check':
            $bp_status = '3';
            break;
    }

	echo " Invoice ID: ".$invoice_id." ";
/*
	echo " BP Sta: ".$bp_status." ";
	echo " New Term: ".$bp_update_term;
	echo " Billing Account: ".$account_id;
	echo " Paid Amount: ".$bp_paid_amount;
	echo " Paid Method: ".$bp_paid_method;
	echo " Paid Bank: ".$bp_paid_bank;
	echo " Paid Check: ".$bp_paid_check;
	echo " Paid Date: ".$bp_completed;
	echo " Status: ".$billing_status;
	echo "New Billing Period ".$bp_update_period;
	echo "Next Billing: ".$bp_update_next;
*/
	$billing_status = ( $bp_paid_method != '' )?"1":"0";

	//$update_next_billing = date("Y-m-d", strtotime($bp_update_next. " + ".$bp_update_term." months"));
	if($billing_status==0){
		$update_next_billing = date("Y-m-d", strtotime($bp_update_next));
	}else{
		$update_next_billing = date("Y-m-d", strtotime($bp_update_next. " + ".$bp_update_term." months"));
	}
	
	update_post_meta( $post_id, 'billing_method', $bp_update_method );
	update_post_meta( $post_id, 'billing_date', $update_next_billing );
	update_post_meta( $post_id, 'billing_term', $bp_update_term );
	update_post_meta( $post_id, 'billing_tax', $bp_update_tax );
	update_post_meta( $post_id, 'billing_amount', $bp_update_amount );

	
	$tablename = $wpdb->prefix.'gs_billing';
	if ($bp_status =="3"){
		$wpdb->update( $tablename, array(
			'billing_status' 		=> $billing_status, 
			'billing_completed' 	=> $bp_completed,
			'billing_term' 			=> $bp_update_term, 
			'billing_amount' 		=> $bp_update_amount, 
			'billing_tax' 			=> $bp_update_tax, 
			'billing_period' 		=> $bp_update_period, 
			'billing_total' 		=> $bp_update_total, 
			'billing_paid_amount' 	=> $bp_paid_amount, 
			'billing_paid_method' 	=> $bp_paid_method, 
			'billing_bank_name' 	=> $bp_paid_bank, 
			'billing_check_num' 	=> $bp_paid_check), 
			array('billing_id' 		=> $invoice_id )
		);
	}else{
		$wpdb->update( $tablename, array(
			'billing_status' 		=> $billing_status, 
			'billing_completed' 	=> $bp_completed,
			'billing_term' 			=> $bp_update_term, 
			'billing_amount' 		=> $bp_update_amount, 
			'billing_tax' 			=> $bp_update_tax, 
			'billing_period' 		=> $bp_update_period, 
			'billing_total' 		=> $bp_update_total, 
			'billing_paid_amount' 	=> $bp_paid_amount, 
			'billing_paid_method' 	=> $bp_paid_method), 
			array('billing_id' 		=> $invoice_id )
		);
	}
	
	$query_select 	= 'SELECT id FROM ' .$tablename. ' WHERE billing_account = '.$account_id.' ORDER BY id DESC LIMIT 1';
	$last_id 		= $wpdb->get_var( 'SELECT id FROM ' .$tablename. ' where  id=(select max(id) from '.$tablename.')');
//	echo "Last ID is ".$last_id;

	$next_id 		= $last_id+1;
	$prefix 		= "";
	$pad_len 		= 7;
	$billing_number = $next_id+1000;
	$billing_id 	= sprintf("%s%s", $prefix, str_pad($billing_number, $pad_len, "0", STR_PAD_LEFT));
//	echo "Next Billing ID is ".$billing_id;
	
	$check_pre_billing = $wpdb->get_results( $wpdb->prepare( 'SELECT id, billing_id, billing_status FROM ' .$tablename. ' WHERE `post_id` = "'.$post_id.'" AND `billing_status` = 0 ORDER BY id DESC LIMIT 1'));

	$unpaid_invoice  = "";
	$last_billing_id = "";
	foreach ( $check_pre_billing as $pre_billing_result )
	{
		$unpaid_invoice  = $pre_billing_result->billing_status;
		$last_billing_id = $pre_billing_result->id;
	}
	echo " Status : ".$unpaid_invoice. " ";
//	echo "Last ID : ".$last_billing_id;
	if($unpaid_invoice!=0||$unpaid_invoice==""){
		
		$bm_value 	= get_post_meta( $post_id, 'billing_method', true );
		$bt_value 	= $bp_update_term;
		$ba_value 	= $bp_update_amount;
		$bx_value 	= $bp_update_tax;
		$bd_value 	= date("Y-m-d", strtotime($update_next_billing));

		$bp_value	= date("m/d/Y", strtotime($update_next_billing))."~".date("m/d/Y", strtotime($update_next_billing. " + ".$bp_update_term." months"));
		
		$bx_rate	= number_format(($bp_update_tax/100), 5,'.', ',');
		$btl_value 	= number_format($bp_update_amount*$bp_update_term+($bp_update_amount*$bp_update_tax*$bx_rate), 2,'.', ',');
		$bn_value 	= get_post_meta( $post_id, 'billing_note', true );
		$b_time 	= current_datetime()->format('Y-m-d H:i:s');
		$wpdb->insert( $tablename, array(
			'post_id' 			=> $post_id, 
			'billing_id' 		=> $billing_id, 
			'billing_created' 	=> $b_time,
			'billing_status' 	=> '0', 
			'billing_completed' => "",
			'billing_account' 	=> $account_id, 
			'billing_method' 	=> $bm_value, 
			'billing_term' 		=> $bt_value,
			'billing_amount' 	=> $ba_value, 
			'billing_tax' 		=> $bx_value, 
			'billing_date' 		=> $bd_value, 
			'billing_period' 	=> $bp_value, 
			'billing_total' 	=> $btl_value, 
			'billing_note' 		=> $bn_value,
			'billing_updated' 	=> $b_time),
			array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) 
        );
		echo "The Current Invoice Updated as Paid! New Invoice # ".$billing_id." generated successfully!";
	}else{
		echo "The Current Invoice Not Been Paid. The current invoice has been updated!";		
	}
    exit(); // this is required to return a proper result & exit is faster than die();
}
add_action('wp_ajax_update_billing', 'update_billing_callback');


function delete_billing_invoice() {
?>
<script type="text/javascript" >

function deleteRow(row) {

	var invoice_id = jQuery(row).attr("data-invoiceid");
		confirm("Do you want to DELETE invoice number " + invoice_id +"?");

		var data = {
            action: 'delete_billing',
            invoice_id: invoice_id,
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl, data, function(response) {
            alert('Message: ' + response);
			
        });
		location.reload();

}

</script>
<?php
}
add_action('admin_head', 'delete_billing_invoice');

function delete_billing_callback() {
	global $wpdb; // this is how you get access to the database

	$invoice_id 	= $_POST['invoice_id'];

	$billing_status = 1;
	
	$tablename = $wpdb->prefix.'gs_billing';
	
	$wpdb->delete( $tablename, [ 'billing_id'=>$invoice_id ], [ '%d' ] );
		
	echo "Invoice ID: ".$invoice_id. " has been removed successfully";
	
    exit(); // this is required to return a proper result & exit is faster than die();
}
add_action('wp_ajax_delete_billing', 'delete_billing_callback');



function check_last_invoice($postid){
	global $wpdb; // this is how you get access to the database

	$post_id			= $postid;
	$tablename			= $wpdb->prefix.'gs_billing';
	$current_invoice	= $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM ' .$tablename. ' WHERE `post_id` = "'.$post_id.'" AND `billing_status` = 0 ORDER BY id DESC LIMIT 1'));
	//print_r($current_invoice);
	return $current_invoice;
}


function google_cal_menu() {
	//add_menu_page( 'linked_url', 'External link', 'read', 'my_slug', '', 'dashicons-text', 1 );
	add_menu_page( 'SW Schedule', 'SW Schedule', 'administrator', 'https://calendar.google.com/calendar/embed?src=sunworldalarm%40gmail.com&ctz=America%2FNew_York', "", 'dashicons-calendar-alt', 4 );
}
add_action( 'admin_menu', 'google_cal_menu' );

function google_cal_function() {
	global $menu;
	$menu[1][2] = "https://calendar.google.com/calendar/ical/sunworldalarm@gmail.com/public/basic.ics";
}
add_action( 'admin_menu' , 'google_cal_function' );
