<?php
if (!defined('ABSPATH')) exit();
if (class_exists('OrderUlp')) return;
class OrderUlp extends CustomPostTypeUlp{
	/**
	 * @var string
	 */
	protected $post_type_slug = 'ulp_order';
	/**
	 * @var int
	 */
	protected $menu_position = 6;
	/**
	 * @var array
	 */
	protected $supports = ['title', 'author'];
	public function __construct(){
		$this->labels = array(
								    'name'               => __('Orders', 'ulp'),
								    'singular_name'      => __('Order', 'ulp'),
								    'add_new'            => __('Add new Order', 'ulp'),
								    'add_new_item'       => __('Add new Order', 'ulp'),
								    'edit_item'          => __('Edit Order', 'ulp'),
								    'new_item'           => __('New Order', 'ulp'),
								    'all_items'          => __('All Orders', 'ulp'),
								    'view_item'          => __('View Order', 'ulp'),
								    'search_items'       => __('Search Order', 'ulp'),
								    'not_found'          => '',
								    'not_found_in_trash' => '',
								    'parent_item_colon'  => '',
								    'menu_name'          => __('Orders', 'ulp'),
		);
		$this->taxonomy_labels = array(
									'name'              => __('Categories Orders', 'ulp'),
									'singular_name'     => '',
									'search_items'      => '',
									'all_items'         => __('Categories Orders', 'ulp'),
									'parent_item'       => '',
									'parent_item_colon' => '',
									'edit_item'         => '',
									'update_item'       => '',
									'add_new_item'      => '',
									'new_item_name'     => '',
									'menu_name'         => __('Categories Orders', 'ulp'),
		);
		$this->taxonomy_slug = 'ulp_order_categories';
		$this->metaBoxes[] = array(
												'slug' => 'ulp_metas',
												'title' => __('Order Details', 'ulp'),
												'callback' => array($this, 'ulp_metas_box'),
												'context' => 'normal', // normal || side || advanced
												'priority' => 'high', /// high || low
		);
		add_action( 'add_meta_boxes', array($this, 'remove_meta_boxes' ), 10 );
		$this->run();
		add_filter('wp_insert_post_data', array($this, 'custom_save_order'));
		///
		add_action('init', array($this, 'register_order_status'));
	}
	public function custom_save_order($data=array()){
			if (isset($data ['post_type']) && $data ['post_type']==$this->post_type_slug && is_admin()){
					if (isset($_POST['ulp_status'])){
							$_POST['ulp_status'] = sanitize_text_field( $_POST['ulp_status'] );
							$data ['post_status'] = $_POST['ulp_status'];
					}
			}
			return $data;
	}
	public function register_order_status(){
		register_post_status('ulp_pending', [
			 'label' => __('Pending', 'ulp'),
			 'public'                    => false,
			 'exclude_from_search'       => false,
			 'show_in_admin_all_list'    => true,
			 'show_in_admin_status_list' => true,
		]);
		register_post_status('ulp_complete', [
			 'label' => __('Completed', 'ulp'),
			 'public'                    => false,
			 'exclude_from_search'       => false,
			 'show_in_admin_all_list'    => true,
			 'show_in_admin_status_list' => true,
		]);
		register_post_status('ulp_fail', [
			 'label' => __('Fail', 'ulp'),
			 'public'                    => false,
			 'exclude_from_search'       => false,
			 'show_in_admin_all_list'    => true,
			 'show_in_admin_status_list' => true,
		]);
	}
	/*
	 * @param none
	 * @return array
	 */
	protected function allMetaNames(){
		return array();
	}
	public function remove_meta_boxes(){
		remove_meta_box( 'submitdiv', $this->post_type_slug, 'side' );
		remove_meta_box( 'titlediv', $this->post_type_slug, 'normal' );
		remove_meta_box( 'slugdiv', $this->post_type_slug, 'normal' );
		remove_meta_box( 'authordiv', $this->post_type_slug, 'normal' );
		remove_meta_box( 'ulp_order_categoriesdiv', $this->post_type_slug, 'normal' );
	}
	/**
	 * @param int
	 * @return none
	 */
	public function afterSavePost($post_id=0){
		if ($post_id){
			require_once ULP_PATH . 'classes/Db/DbUlpOrdersMeta.class.php';
			$DbUlpOrdersMeta = new DbUlpOrdersMeta();
			$metas = [
					'user_id',
					'course_id',
					'unique_identificator',
					'amount',
			];
			foreach ($metas as $meta_key){
					if (isset($_POST[$meta_key]))
							$DbUlpOrdersMeta->save($post_id, $meta_key, $_POST[$meta_key]);
			}
			if (isset($_POST['original_post_status']) && isset($_POST['ulp_status']) && $_POST['original_post_status']!=$_POST['ulp_status']){
					$order = new UlpOrder();
					$order->modify_status($_POST['unique_identificator'], $_POST['ulp_status'], TRUE);
			}
		}
	}
	public function ulp_metas_box(){
		global $post;
		require_once ULP_PATH . 'classes/Db/DbUlpOrdersMeta.class.php';
		$DbUlpOrdersMeta = new DbUlpOrdersMeta();
		$metas = [
				'user_id',
				'course_id',
				'unique_identificator',
				'amount',
		];
		$post_id = isset($post->ID) ? $post->ID : 0;
		foreach ($metas as $meta_key){
				$meta_data ['metas'][$meta_key] = $DbUlpOrdersMeta->get($post_id, $meta_key);
		}

		if (isset($meta_data ['metas']['user_id'])){
			$meta_data ['metas']['avatar'] = DbUlp::getAuthorImage($meta_data ['metas']['user_id']);
			$meta_data ['metas']['username'] = DbUlp::getUsernameByUID($meta_data ['metas']['user_id']);
		}
		$source = $DbUlpOrdersMeta->getSource($post_id);
		if ($source){
              $meta_data ['metas']['source'] = ucfirst($source);
          }
		$meta_data ['courses'] = DbUlp::getAllCourses();
		$meta_data ['post_status'] = isset($post->post_status) ? $post->post_status : 'ulp_pending';

		$payment_settings = DbUlp::getOptionMetaGroup('payment_settings');
		$meta_data ['currency'] = $payment_settings['ulp_currency'];



		/// output
		$view = new ViewUlp();
		$view->setTemplate(ULP_PATH . 'views/admin/meta_boxes/order_metas.php');
		$view->setContentData($meta_data);
		echo $view->getOutput();
	}
}
