<?php

/**
* Handle the form submissions
*
* @package Package
* @subpackage Sub Package
*/
class Esi_Management_Patent_Form {

    /**
    * Hook 'em all
    */
    public function __construct() {
        add_action( 'admin_init', array( $this, 'handle_form' ) );
    }



    /**
    * Handle the new patent and edit form
    *
    * @return void
    */
    public function handle_form($is_ajax = false) {

        if ( !isset( $_POST['submit_patent'] ) && !$is_ajax ) {
            return;
        }

        if ( ! wp_verify_nonce( $_POST['_wpnonce'], '' ) ) {
            die( __( 'Are you cheating?', 'esi' ) );
        }

        if ( ! current_user_can( 'read' ) ) {
            wp_die( __( 'Permission Denied!', 'esi' ) );
        }


        $errors   = array();
        $page_url = admin_url( 'admin.php?page=esi-management-patent' );
        $field_id = isset( $_POST['field_id'] ) ? intval( $_POST['field_id'] ) : 0;

        $code = isset( $_POST['code'] ) ? sanitize_text_field( $_POST['code'] ) : '';
        $description = isset( $_POST['description'] ) ? sanitize_text_field( $_POST['description'] ) : '';
        $entity_id = isset( $_POST['entity_id'] ) ? intval( $_POST['entity_id'] ) : '';

        // some basic validation
        if ( ! $code ) {
            $errors[] = __( 'Error: Code is required', 'esi' );
        }

        if ( ! $entity_id ) {
            $errors[] = __( 'Error: Entity is required', 'esi' );
        }

        // bail out if error found
        if ( $errors ) {
            $first_error = reset( $errors );
            $redirect_to = add_query_arg( array( 'error' => $first_error ), $page_url );
            wp_safe_redirect( $redirect_to );
            exit;
        }

        $fields = array(
            'code' => $code,
            'description' => $description,
            'entity_id' => $entity_id,
        );

        // New or edit?
        if ( ! $field_id ) {

            $insert_id = esi_insert_patent( $fields );

            $fields['id'] = $insert_id;

        } else {

            $fields['id'] = $field_id;

            $insert_id = esi_insert_patent( $fields );
        }

        if($is_ajax){
            return $fields;
        }

        if ( is_wp_error( $insert_id ) ) {
            $redirect_to = add_query_arg( array( 'message' => 'error' ), $page_url );
        } else {
            $redirect_to = add_query_arg( array( 'message' => 'success' ), $page_url );
        }
        
        wp_safe_redirect( $redirect_to );
        exit;
    }
}

new Esi_Management_Patent_Form();
