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

if ( ! class_exists( 'IPJck_Ajax_Update_slide' ))
{
	class IPJck_Ajax_Update_slide
	{
		/**
		 * 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['slide_id'] )) {
					$slideId = absint( $_POST['slide_id'] );
					if ( $slide = get_post( $slideId ) ) {
							$this->_updateSlide( $slide );
					} else {
							$slideId = 0;
					}
			} else {
					$slideId = $this->_addSlide();
			}
			if ( $slideId )
			{
					$error = false;
					$model = new IPJck_Model_Widget_Slide();
					$model->saveSetting( $slideId );
			}
			if ( $error ) {
					$status   = 0;
					$slideId  = 0;
					if ( $is_add ) {
							$message = __( 'Failed create slide.', IPJCK_SLUG );
					} else {
							$message = __( 'Failed save slide.', IPJCK_SLUG );
					}
			} else {
					$status = 1;
					if ( $is_add ) {
							$message  = __( 'Successfully created slide.', IPJCK_SLUG );
							$redirect = admin_url() . 'admin.php?page=' . IPJCK_PAGENAME . '-slide&action=edit&id=' . $slideId . '&create=1';
					} else {
							$message = __( 'Successfully saved slide.', IPJCK_SLUG );
							$redirect = admin_url() . 'admin.php?page=' . IPJCK_PAGENAME . '-slide&action=edit&id=' . $slideId . '&edited=1';
					}
			}

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

		/**
		 * Add new slide
		 *
		 * @return int
		 */
		protected function _addSlide()
		{
			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_slide',
				'post_author'  => $user_ID,
				'post_title'   => $title,
				'post_content' => ''
			);
			$result = wp_insert_post( $dataPost );
			return $result;
		}

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