<?php
/**
 * Class: WPGMP_Model_Group_Map
 *
 * @author Flipper Code <hello@flippercode.com>
 * @version 3.0.0
 * @package Maps
 */

if ( ! class_exists( 'WPGMP_Model_Group_Map' ) ) {

	/**
	 * Category model for CRUD operation.
	 *
	 * @package Maps
	 * @author Flipper Code <hello@flippercode.com>
	 */
	class WPGMP_Model_Group_Map extends FlipperCode_Model_Base {
		/**
		 * Validations on category properies.
		 *
		 * @var array
		 */
		protected $validations;
		/**
		 * Intialize location object.
		 */
		function __construct() {

			$this->validations = array(
				'group_map_title' => array( 
											'req' => esc_html__( 'Please enter title for marker category.', 'wpgmp-google-map' ),
											'max=255' => esc_html__( 'Marker category title cannot contain more than 255 characters. Please enter a shorter marker category title.', 'wpgmp-google-map' )
									 ),
				'group_marker'      => array( 'req' => esc_html__( 'Please upload marker image.', 'wpgmp-google-map' ) ),
			);

			$this->table  = TBL_GROUPMAP;
			$this->unique = 'group_map_id';
		}

		/**
		 * Admin menu for CRUD Operation
		 *
		 * @return array Admin menu navigation(s).
		 */
		function navigation() {
			return array(
				'wpgmp_form_group_map'   => esc_html__( 'Add Marker Category', 'wpgmp-google-map' ),
				'wpgmp_manage_group_map' => esc_html__( 'Marker Categories', 'wpgmp-google-map' ),
			);

		}
		/**
		 * Install table associated with Location entity.
		 *
		 * @return string SQL query to install map_locations table.
		 */
		function install() {
			global $wpdb;
			$charset_collate = $wpdb->get_charset_collate();

			$group_map = 'CREATE TABLE ' . $wpdb->prefix . 'group_map (
			group_map_id int(11) NOT NULL AUTO_INCREMENT,
			group_map_title varchar(255) DEFAULT NULL,
			group_marker text DEFAULT NULL,
			extensions_fields text DEFAULT NULL,
			group_parent int(11) DEFAULT 0,
			group_added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY  (group_map_id)
			) '.$charset_collate.';';
			return $group_map;
		}
		/**
		 * Get Categories
		 *
		 * @param  array $where  Conditional statement.
		 * @return array         Array of Category object(s).
		 */
		public function fetch( $where = array() ) {

			$objects = $this->get( $this->table, $where );
			foreach ( $objects as $object ) {
				if ( isset($object->group_marker) && strstr( $object->group_marker, 'wp-google-map-pro/icons/' ) !== false ) {
					$object->group_marker = str_replace( 'icons', 'assets/images/icons', $object->group_marker ); }
					$object->extensions_fields = maybe_unserialize( $object->extensions_fields );

			}
			if ( isset( $objects ) ) {
				return $objects;
			}
		}

		function write_to_db(){

			$entityID = '';
			if ( isset( $_POST['entityID'] ) )
			$entityID = intval( wp_unslash( $_POST['entityID'] ) );

			$data['group_map_title']   = sanitize_text_field( wp_unslash( $_POST['group_map_title'] ) );
			$data['group_parent']      = (isset($_POST['group_parent']) && !empty($_POST['group_parent'])) ? intval( wp_unslash( $_POST['group_parent'] ) ) : '';
			$data['extensions_fields'] = (isset($_POST['extensions_fields']) && !empty($_POST['extensions_fields'])) ? serialize( wp_unslash( $_POST['extensions_fields'] ) ) : 'a:1:{s:9:"cat_order";s:0:"";}';
			if(!isset($_POST['group_marker']) || empty($_POST['group_marker'])){
				$data['group_marker'] = WPGMP_IMAGES.'default_marker.png';
			}else{
				$data['group_marker'] = wp_unslash( $_POST['group_marker'] );	
			}
			if ( $entityID > 0 ) {
				$where[ $this->unique ] = $entityID;
			} else {
				$where = '';
			}

			$data = apply_filters('fc_save_categories_data',$data,$where);

			$result = FlipperCode_Database::insert_or_update( $this->table, $data, $where );
			
			return $result;

		}

		public function save_via_rest() {  
			
			//Rest Validations
            $rest_errors = [];
            if(!isset($_POST['group_map_title']) || empty($_POST['group_map_title']))
                $rest_errors[] = esc_html__( 'Please enter marker category title.', 'wpgmp-google-map' );      
           if(isset($_POST['extensions_fields']['cat_order']) && !empty($_POST['extensions_fields']['cat_order']) && !is_numeric($_POST['extensions_fields']['cat_order']) ){   
                $rest_errors[] = esc_html__( 'Please enter only a numeric value for marker category order number.', 'wpgmp-google-map' );
            }
        
            $rest_errors = apply_filters('wpgmp_marker_category_rest_validation',$rest_errors,$_POST);
            if ( is_array( $rest_errors ) && ! empty( $rest_errors ) ){
                return new WP_Error( 'wpgmp_rest_validation_failed', esc_html__( 'Please checkout the errors and fix those to proceed with this request.', 'rest-api-for-google-maps' ), array( 'status' => 422, 'errors' => $rest_errors ) );
            }

			//Write to DB
			$result = $this->write_to_db();

			$action  = (isset( $_POST['entityID'] ) && !empty($_POST['entityID']) ) ? 'update' : 'create';

            // Handle the result
            if ( false !== $result ) {
                return new WP_REST_Response( array( 'success' => true , 'wpgmp_module' => 'marker_category' , 'action' => $action ), 200 );
            } else {
                return new WP_REST_Response( array( 'success' => false ), 400 );
            }
	

		}
		/**
		 * Add or Edit Operation.
		 */
		function save() {
						
			$data     = array();

			$entityID = '';
			if ( isset( $_POST['entityID'] ) ) {
				$entityID = intval( wp_unslash( $_POST['entityID'] ) );
			}
			
			//Nonce Verification
			if( !isset( $_REQUEST['_wpnonce'] ) || ( isset( $_REQUEST['_wpnonce'] ) && empty($_REQUEST['_wpnonce']) ) )
			die( 'You are not allowed to save changes!' );
			if ( isset( $_REQUEST['_wpnonce'] ) && ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'wpgmp-nonce' ) )
			die( 'You are not allowed to save changes!' );

			//Form Validations
			$this->verify( $_POST );
			if(isset($_POST['extensions_fields']['cat_order']) && !empty($_POST['extensions_fields']['cat_order']) && !is_numeric($_POST['extensions_fields']['cat_order']) ){	
				$this->errors[] = esc_html__( 'Please enter only a numeric value for marker category order number.', 'wpgmp-google-map' );
			}
			$this->errors = apply_filters('wpgmp_category_validation',$this->errors,$_POST);
			if ( is_array( $this->errors ) and ! empty( $this->errors ) ) {
				$this->throw_errors();
			}

			//Write to DB
			$result = $this->write_to_db();
			
			if ( false === $result ) {
				$response['error'] = esc_html__( 'Something went wrong. Please try again.', 'wpgmp-google-map' );
			} elseif ( $entityID > 0 ) {
				$response['success'] = esc_html__( 'Marker category was updated successfully.', 'wpgmp-google-map' );
			} else {
				$response['success'] = esc_html__( 'Marker category was added successfully.', 'wpgmp-google-map' );
			}
			$response['last_db_id'] = $result;
			
			return $response;
		}

		/**
		 * Delete location object by id.
		 */
		function delete() {
			if ( isset( $_GET['group_map_id'] ) ) {
				$id          = intval( wp_unslash( $_GET['group_map_id'] ) );
				$connection  = FlipperCode_Database::connect();
				$this->query = $connection->prepare( "DELETE FROM $this->table WHERE $this->unique='%d'", $id );
				return FlipperCode_Database::non_query( $this->query, $connection );
			}
		}

	}
}
