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

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

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

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

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