<?php

if (!defined('ABSPATH')) exit;

require_once plugin_dir_path(__FILE__) . './minicomerce_record_on_database.php';

function minicomerce_save_customers_data()
{ 
    echo wp_json_encode(minicomerce_process_user_data());
    wp_die();
}

function minicomerce_process_user_data()
{

    try {

        if (
            !isset($_POST['product']) ||
            !isset($_POST['name']) ||
            !isset($_POST['surname']) ||
            !isset($_POST['tel']) ||
            !isset($_POST['city']) || 
            !isset($_POST['email']) || 
            !isset($_POST['address']) ||
            !isset($_POST['postalCode']) ||
            empty($_POST['product']) ||
            empty($_POST['name']) ||
            empty($_POST['surname']) ||
            empty($_POST['tel']) ||
            empty($_POST['city']) ||
            empty($_POST['email']) || 
            empty($_POST['address']) ||
            empty($_POST['postalCode'])
        ) { 
            return array(  'status' => 400, 'message' => 'Some files or securyty fields are missing' );
        }

        if(!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])) , 'customers_nonce')){
            throw new Exception(esc_html__('Nonce is not valid', 'minicomerce'));
        }
 
        $product = sanitize_text_field(wp_unslash($_POST['product']));
        $name = sanitize_text_field(wp_unslash($_POST['name']));
        $surname = sanitize_text_field(wp_unslash($_POST['surname']));
        $tel = sanitize_text_field(wp_unslash($_POST['tel']));
        $city = sanitize_text_field(wp_unslash($_POST['city']));
        $email = sanitize_email(wp_unslash($_POST['email'])); 
        $address = sanitize_text_field(wp_unslash($_POST['address']));
        $postalCode = sanitize_text_field(wp_unslash($_POST['postalCode']));
        $note = (isset($_POST['note'])) ? sanitize_text_field(wp_unslash($_POST['note'])) : 'not added note';
        $user_data = [minicomerce_getActualPrice(), $product, $name, $surname, $tel, $city, $email, $address, $postalCode, $note  ];

        return minicomerce_record_data_on_database($user_data);
 
    } catch (Exception $e) {
        return array(  'status' => 400, 'message' => 'Error procesing customers data', $e->getMessage() ); 
    }
}


function minicomerce_getActualPrice()
{
    $essential_data = (null !==  get_option(MINICOMERCE_ESSENTIAL)) ? unserialize(get_option(MINICOMERCE_ESSENTIAL)) : null;
    $price =  $essential_data[7];
    return $price;
}

