<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       http://example.com
 * @since      1.0.0
 *
 * @package    Plugin_Name
 * @subpackage Plugin_Name/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Plugin_Name
 * @subpackage Plugin_Name/admin
 * @author     Your Name <email@example.com>
 */
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/metaboxes.php';
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/options.php';
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/settings.php';
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/ajax.php';
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/image.php';

class WosmPL_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;

	}


	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles($hook) {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Plugin_Name_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Plugin_Name_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/wosmpl-admin.css', array(), $this->version.'.1', 'all' );
		
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts($hook) {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Plugin_Name_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Plugin_Name_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		// var_dump($hook);
		// echo "hook";
		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/wosmpl-admin.js', array( 'jquery' ), $this->version.'.1', false );
			if ($hook == 'post.php' || $hook == 'post-new.php') {
				wosmpl_leaflet_activate();
				$wosmpl_nonce = wp_create_nonce( 'wosmpl_ajax' );
				wp_enqueue_script( 'ajax-script',
				    plugins_url( '/js/wosmpl-ajax.js', __FILE__ ),
				    array('jquery')
				);
				wp_localize_script( 'ajax-script', 'wosmpl_ajax_obj', array(
				    'ajax_url' => admin_url( 'admin-ajax.php' ),
				    'nonce'    => $wosmpl_nonce, 
					) 
			 	);   
				        
			}
		
	}

	/**
	 * LatLong page box
	 *
	 * @since    1.0.0
	 */
	public function wosmpl_geodata_box(){
		//TODO ask allowed type in settings area
		//$screens = ['post', 'page','wosmpl_partners'];
		$screens = ['wosmpl_partners'];
	    foreach ($screens as $screen) {
	        add_meta_box(
	            'wosmpl_geodata_box',           // Unique ID
	            'Geolocalisation',  // Box title
	            'wosmpl_geodata_box_html',  // Content callback, must be of type callable
	            $screen                   // Post type
	        );
	        add_meta_box(
	            'wosmpl_additionnal_marker_data_box',       // Unique ID
	            'Informations supplémentaires (marqueur)',  // Box title
	            'wosmpl_additionnal_marker_data_box_html',  // Content callback, must be of type callable
	            $screen                   // Post type
	        );
	        add_meta_box(
	            'wosmpl_additionnal_data_box',       // Unique ID
	            'Informations supplémentaires (page)',  // Box title
	            'wosmpl_additionnal_page_data_box_html',  // Content callback, must be of type callable
	            $screen                   // Post type
	        );
	    }
	}

	/**
	 * Save or update metadata
	 *
	 * @since    1.0.0
	 */
	public function wosmpl_save_post($post_id){
		if (empty($_POST)) {
		    return;
		}

		$errors = [];
		//TODO use of wp_verify_nonce
		$wosmpl_latlon = $_POST['wosmpl_latlon'];
		$wosmpl_geo_cat = $_POST['wosmpl_geo_cat'];
		$wosmpl_presta_type = $_POST['wosmpl_presta_type'];
		$wosmpl_post_addr = $_POST['wosmpl_post_addr'];
		$wosmpl_partner_pict = $_POST['wosmpl_partner_pict'];
		$wosmpl_partner_open_hours = $_POST['wosmpl_partner_open_hours'];
		$wosmpl_partner_specialty = $_POST['wosmpl_partner_specialty'];
		$wosmpl_partner_challenge = $_POST['wosmpl_partner_challenge'];
		$wosmpl_partner_phone =  $_POST['wosmpl_partner_phone'];
		$wosmpl_partner_phone_visible =  $_POST['wosmpl_partner_phone_visible'] ?? '';
		$wosmpl_partner_email =  $_POST['wosmpl_partner_email'];
		$wosmpl_partner_email_visible =  $_POST['wosmpl_partner_email_visible'] ?? '';
		$wosmpl_partner_website =  $_POST['wosmpl_partner_website'];
		$wosmpl_partner_website_visible =  $_POST['wosmpl_partner_website_visible'] ?? '';
		//Data verif
		if ($wosmpl_geo_cat && !is_numeric($wosmpl_geo_cat)) {
			$errors[] = 'Invalid category type';
		}

		if (preg_match('/[^0-9 \, \.]+/', $wosmpl_latlon)) {
			$errors[] = 'Invalid caracter in latlon string';
		}
		$wosmpl_presta_type = sanitize_text_field($wosmpl_presta_type);
		if (strlen($wosmpl_partner_email) > 5 && !is_email($wosmpl_partner_email)) {
			$errors[] = $wosmpl_partner_email . 'is invalid.';
			$wosmpl_partner_email = '';
		}
		$wosmpl_partner_open_hours = implode( "\n", array_map( 'sanitize_text_field', explode( "\n", $wosmpl_partner_open_hours ) ) );
		$wosmpl_partner_specialty =  implode( "\n", array_map( 'sanitize_text_field', explode( "\n", $wosmpl_partner_specialty ) ) );
		
		$wosmpl_partner_challenge  =  implode( "\n", array_map( 'sanitize_text_field', explode( "\n", $wosmpl_partner_challenge ) ) );
		
		$wosmpl_partner_phone = sanitize_text_field($wosmpl_partner_phone);
		$wosmpl_partner_phone_visible = sanitize_text_field($wosmpl_partner_phone_visible);
		$wosmpl_partner_email = sanitize_text_field($wosmpl_partner_email);
		$wosmpl_partner_email_visible = sanitize_text_field($wosmpl_partner_email_visible);

		$wosmpl_partner_website = esc_url_raw($wosmpl_partner_website);
		$wosmpl_partner_website_visible = sanitize_text_field($wosmpl_partner_website_visible);
		$received_options = [
								'wosmpl_latlon' => $wosmpl_latlon,
								'wosmpl_geo_cat' => $wosmpl_geo_cat,
								'wosmpl_presta_type' => $wosmpl_presta_type,
								'wosmpl_post_addr' => $wosmpl_post_addr,
								'wosmpl_partner_pict' => $wosmpl_partner_pict,
								'wosmpl_partner_open_hours' => $wosmpl_partner_open_hours,
								'wosmpl_partner_specialty' => $wosmpl_partner_specialty,
								'wosmpl_partner_challenge' => $wosmpl_partner_challenge,
								'wosmpl_partner_phone' => $wosmpl_partner_phone,
								'wosmpl_partner_phone_visible' => $wosmpl_partner_phone_visible,
								'wosmpl_partner_email' => $wosmpl_partner_email,
								'wosmpl_partner_email_visible' => $wosmpl_partner_email_visible,
								'wosmpl_partner_website' => $wosmpl_partner_website,
								'wosmpl_partner_website_visible' => $wosmpl_partner_website_visible
							];

		if (count($errors) == 0) {
			$metadata = get_post_meta( $post_id);
		
			if (isset($metadata['wosmpl_latlon'])) {
				foreach ($received_options as $key => $val){
					update_post_meta( $post_id, $key, $val);
				}
				
			} else {
				foreach ($received_options as $key => $val){
					add_post_meta( $post_id, $key, $val);
				}
			}
		} else {
			$msg = implode("<br />",$errors);

			new WosmPL_Admin_Error_Message($msg);
			
		}
		// ob_start();
		// var_dump($metadata);
		// file_put_contents('/tmp/wosmpl.log',ob_get_clean()."\n",FILE_APPEND);
	}

	public function wosmpl_widgets(){
		register_widget('WosmPL_GeoCat_Widget');
	}

	public function wosmpl_options_page()
	{
	    add_submenu_page(
	    	'options-general.php',
	        'WosmPL - Settings', //page title
	        'WosmPL Settings', // menu title
	        'manage_options', //user capability
	        'wosmpl', // menu_slug
	        'wosmpl_options_page_html', //settings.php
	        //plugin_dir_url(__FILE__) . 'images/wosmpl.png',
	        2000 // menu place
	    );

	}

	public function wosmpl_register_type(){
		$args = array(
	        'label' => 'Partenaires',
	        'public' => true,
	        'show_ui' => true,
	        'capability_type' => 'post',
	        'hierarchical' => false,
	        'rewrite' => array('slug' => 'partenaires'),
	        'query_var' => true,
	        'menu_position'=> 5,
		'has_archive' => TRUE,
	        //'menu_icon' => 'dashicons-video-alt',
	        'supports' => array(
	            'title',
	            'editor',
	            //'excerpt',
	            //'trackbacks',
	            //'custom-fields',
	            //'comments',
	            'revisions',
	            'thumbnail',
	            'author',
	            'page-attributes',)
	        );
	    register_post_type( 'wosmpl_partners', $args );
	}

	public function wosmpl_partner_template($single_template) {
     global $post;

     if ($post->post_type == 'wosmpl_partners') {
          $single_template = plugin_dir_path( dirname( __FILE__ ) ) . 'includes/templates/wosmpl-partner-template.php';
     }
     return $single_template;
}

}


class WosmPL_Admin_Error_Message {
	private $_message;

    function __construct( $message ) {
        $this->_message = $message;
        
        add_action( 'admin_notices', array( $this, 'render' ) );
        die($message); //Because render doesnt work
    }

    function render() {
    	// TODO : doesnt work !
        printf( '<script type="text/javascript">alert("%s")</script>', $this->_message );
    }

}
