<?php

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

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

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

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

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

        // some basic validation
        if ( ! $name ) {
            $errors[] = __( 'Error: name 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,
            'esi_industry_table' => $_POST['esi_industry_table'],
            'esi_function_table' => $_POST['esi_function_table'],
        );

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

            $insert_id = esi_insert_radar( $fields );

        } else {

            $fields['id'] = $field_id;
            $insert_id = esi_insert_radar( $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_Radar_Form();
