/*
	Theme Name: Hello Elementor
	Theme URI: https://elementor.com/hello-theme/?utm_source=wp-themes&utm_campaign=theme-uri&utm_medium=wp-dash
	Description: Hello Elementor is a lightweight and minimalist WordPress theme that was built specifically to work seamlessly with the Elementor site builder plugin. The theme is free, open-source, and designed for users who want a flexible, easy-to-use, and customizable website. The theme, which is optimized for performance, provides a solid foundation for users to build their own unique designs using the Elementor drag-and-drop site builder. Its simplicity and flexibility make it a great choice for both beginners and experienced Web Creators.
	Author: Elementor Team
	Author URI: https://elementor.com/?utm_source=wp-themes&utm_campaign=author-uri&utm_medium=wp-dash
	Version: 3.4.4
	Stable tag: 3.4.4
	Requires at least: 6.0
	Tested up to: 6.8
	Requires PHP: 7.4
	License: GNU General Public License v3 or later.
	License URI: https://www.gnu.org/licenses/gpl-3.0.html
	Text Domain: hello-elementor
	Tags: accessibility-ready, flexible-header, custom-colors, custom-menu, custom-logo, featured-images, rtl-language-support, threaded-comments, translation-ready,
*/
add_action('wp_ajax_atlantessa_process_calculation', 'atlantessa_process_calculation_handler');
add_action('wp_ajax_nopriv_atlantessa_process_calculation', 'atlantessa_process_calculation_handler');

function atlantessa_process_calculation_handler() {
    // 1. Перевірка nonce для безпеки
    check_ajax_referer('atlantessa_nonce_action', 'nonce'); // Переконайтеся, що назва екшену збігається

    $status = sanitize_text_field($_POST['status']);
    $client_data = $_POST['client_data'];
    $email = sanitize_email($client_data['email']);
    $phone = sanitize_text_field($client_data['phone']);

    // 2. Логіка Upsert (Пошук існуючого запису)
    global $wpdb;
    $table_name = $wpdb->prefix . 'atlantessa_calculations'; // Назва вашої таблиці

    $existing_id = $wpdb->get_var($wpdb->prepare(
        "SELECT id FROM $table_name 
         WHERE (email = %s OR phone = %s) 
         AND status = 'abandoned' 
         AND created_at > NOW() - INTERVAL 10 MINUTE 
         ORDER BY created_at DESC LIMIT 1",
        $email, $phone
    ));

    $data_to_save = [
        'first_name' => sanitize_text_field($client_data['first_name']),
        'email'      => $email,
        'phone'      => $phone,
        'status'     => $status,
        'payload'    => json_encode($_POST), // Зберігаємо все як JSON
        'updated_at' => current_time('mysql')
    ];

    if ($existing_id) {
        // ОНОВЛЕННЯ існуючого запису
        $wpdb->update($table_name, $data_to_save, ['id' => $existing_id]);
        $response_id = $existing_id;
    } else {
        // СТВОРЕННЯ нового запису
        $data_to_save['created_at'] = current_time('mysql');
        $wpdb->insert($table_name, $data_to_save);
        $response_id = $wpdb->insert_id;
    }

    // 3. Якщо статус 'completed' — виконуємо розрахунок
    if ($status === 'completed') {
        // Тут ваша логіка математичного розрахунку...
        $result = [
            'range' => '$1000 - $2000',
            'price_24h' => '$1500',
            'price_72h' => '$1200',
            'share_url' => home_url('/budget/' . $response_id)
        ];

        wp_send_json_success($result);
    }

    wp_send_json_success(['message' => 'Draft saved']);
}