<?php

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

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

    /**
    * Handle the new type and edit form
    *
    * @return void
    */
    public function handle_form() {

        if ( ! isset( $_POST['submit_investment_type'] ) ) {
            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-investment-type' );
        $field_id = isset( $_POST['field_id'] ) ? intval( $_POST['field_id'] ) : 0;

        $name = isset( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : '';
        $description = isset( $_POST['description'] ) ? sanitize_text_field( $_POST['description'] ) : '';

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

        if ( ! $description ) {
            $errors[] = __( 'Error: Description 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(
            'name' => $name,
            'description' => $description,
        );

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

            $insert_id = esi_insert_investment_type( $fields );

        } else {

            $fields['id'] = $field_id;

            $insert_id = esi_insert_investment_type( $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_Investment_Type_Form();
