<?php
/**
 * Controller to handling updating bar process
 *
 * @package wp-viral-click
 * @author InstaProduct
 * @link http://insta-product.com/
 */

if ( ! class_exists( 'IPJck_Ajax_Update_bar' ))
{
	class IPJck_Ajax_Update_bar
	{
		/**
		 * Execution save options process
		 *
		 * @return void
		 */
		public function exec()
		{
			$redirect = false;
			$is_add   = false;
			$error    = true;
			if ( ! empty( $_POST['isadd'] )) {
					$is_add = true;
			}
			if ( ! empty( $_POST['bar_id'] )) {
					$barId = absint( $_POST['bar_id'] );
					if ( $bar = get_post( $barId ) ) {
							$this->_updateBar( $bar );
					} else {
							$barId = 0;
					}
			} else {
					$barId = $this->_addBar();
			}
			if ( $barId )
			{
					$error = false;
					$model = new IPJck_Model_Widget_Bar();
					$model->saveSetting( $barId );
			}
			if ( $error ) {
					$status   = 0;
					$barId  = 0;
					if ( $is_add ) {
							$message = __( 'Failed create bar.', IPJCK_SLUG );
					} else {
							$message = __( 'Failed save bar.', IPJCK_SLUG );
					}
			} else {
					$status = 1;
					if ( $is_add ) {
							$message  = __( 'Successfully created bar.', IPJCK_SLUG );
							$redirect = admin_url() . 'admin.php?page=' . IPJCK_PAGENAME . '-bar&action=edit&id=' . $barId . '&create=1';
					} else {
							$message = __( 'Successfully saved bar.', IPJCK_SLUG );
							$redirect = admin_url() . 'admin.php?page=' . IPJCK_PAGENAME . '-bar&action=edit&id=' . $barId . '&edited=1';
					}
			}

			$result = array(
					'status'    	=> $status,
					'message'   	=> $message,
					'barid'  			=> $barId
			);
			if ( $redirect ) {
					$result['redirect'] = $redirect;
			}
			echo json_encode( $result );
			die();
		}

		/**
		 * Add new bar
		 *
		 * @return int
		 */
		protected function _addBar()
		{
			global $user_ID;

			if ( empty( $_POST['widget_name'] )) {
					$title = 'Unknown';
			} else {
					$title = apply_filters( 'single_post_title', $_POST['widget_name'] );
			}

			$dataPost = array(
				'post_status'  => 'publish',
				'post_type'    => 'ipjck_bar',
				'post_author'  => $user_ID,
				'post_title'   => $title,
				'post_content' => ''
			);
			$result = wp_insert_post( $dataPost );
			return $result;
		}

		/**
		 * Update bar
		 *
		 * @param  object $bar
		 * @return boolean
		 */
		protected function _updateBar( $bar )
		{
			$result   = 0;
			$dataPost = array();
			if ( ! empty( $_POST['widget_name'] ) && $_POST['widget_name'] != $bar->post_title ) {
					$dataPost['post_title'] = apply_filters( 'single_post_title', $_POST['widget_name'] );
			}
			if ( ! empty( $dataPost )) {
					$dataPost['ID'] = $bar->ID;
					$result = wp_update_post( $dataPost );
			}
			return $result;
		}
	}
}
