<?php

class GestionPymes_wp_init {
	
	public static function init () {
	    add_action('wp_insert_post', array(__CLASS__, 'wp_insert_post'));
	}
	
	
	public static function wp_insert_post ( $post_id ) {
	    if ( get_post_type($post_id) == 'gp_invoice' ) {
	        $cnt          = get_option('gp_settings_invoice_cnt');
	        $cnt_formated = apply_filters( 'gp_invoice_cnt_format', sprintf('%03d', $cnt) );
	        $num_format   = get_option('gp_settings_invoice_number_format');
	        
	        if ( isset($num_format) && (strlen($num_format) > 0) ) {
	            $num_invoice = str_replace( '{{cnt}}', $cnt_formated, $num_format );
	            $old_value = get_post_meta($post_id, '_gp_invoice_number', true);
	            if ( !$old_value || (strlen($old_value) <= 0) ) {
	               update_post_meta($post_id, '_gp_invoice_number', $num_invoice);
	               $cnt++;
	               update_option('gp_settings_invoice_cnt', $cnt, false);
	            }
	        }
	    }
	    return true;
	}
	
}
GestionPymes_wp_init::init();