<?php
add_action('woocommerce_checkout_order_processed', 'add_reserved_time_to_blocked_dates_on_checkout', 10, 3);

function add_reserved_time_to_blocked_dates_on_checkout($order_id, $posted_data, $order) {
    $reserved_time = WC()->session->get('reserved_time');
    if ($reserved_time) {
        $reserved_time_formatted = date('Y-m-d,H:i', strtotime($reserved_time));
        $blocked_dates = get_option('blocked_dates', '');
        $blocked_dates .= "\n" . $reserved_time_formatted;
        update_option('blocked_dates', $blocked_dates);
        WC()->session->set('reserved_time', null);
    }
}

add_action('template_redirect', 'redirect_from_order_received');
function redirect_from_order_received() {
    if (is_order_received_page()) {
        $thank_you_url = home_url('/dziekuje');
        wp_redirect($thank_you_url);
        exit;
    }
}

add_action('woocommerce_after_order_notes', 'add_reserved_time_checkout_field');

function add_reserved_time_checkout_field($checkout) {
    echo '<div id="reserved_time_field"><h2>' . __('Зарезервированное время') . '</h2>';
    woocommerce_form_field('reserved_time', array(
        'type'        => 'text',
        'class'       => array('reserved_time form-row-wide'),
        'label'       => __('Зарезервированное время'),
        'placeholder' => __('Введите зарезервированное время'),
        'required'    => false,
    ), $checkout->get_value('reserved_time'));
    echo '</div>';
}

add_action('woocommerce_checkout_update_order_meta', 'save_reserved_time_checkout_field');

function save_reserved_time_checkout_field($order_id) {
    if (!empty($_POST['reserved_time'])) {
        $reserved_time = sanitize_text_field($_POST['reserved_time']);
        update_post_meta($order_id, 'reserved_time', $reserved_time);
        WC()->session->set('reserved_time', $reserved_time);
    }
}

add_action('woocommerce_email_order_meta', 'display_reserved_time_in_email', 10, 3);

function display_reserved_time_in_email($order, $sent_to_admin, $plain_text) {
    $reserved_time = get_post_meta($order->get_id(), 'reserved_time', true);
    if ($reserved_time) {
        echo '<p><strong>' . __('Reserved time') . ':</strong> ' . esc_html($reserved_time) . '</p>';
    }
}


add_action('woocommerce_admin_order_data_after_billing_address', 'display_reserved_time_admin_order_meta', 10, 1);

function display_reserved_time_admin_order_meta($order) {
    $reserved_time = get_post_meta($order->get_id(), 'reserved_time', true);
    if ($reserved_time) {
        echo '<p><strong>' . __('Зарезервированное время') . ':</strong> ' . esc_html($reserved_time) . '</p>';
    }
}

add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');
function custom_override_checkout_fields($fields) {
    foreach ($fields as $category => $category_fields) {
        foreach ($category_fields as $key => $field) {
            if ($key !== 'billing_first_name' && $key !== 'billing_last_name' && 
                $key !== 'billing_email' && $key !== 'billing_phone') {
                 $fields[$category][$key]['required'] = false;
            }
        }
    }
    foreach ($fields as $category => $category_fields) {
        foreach ($category_fields as $key => $field) {
            $fields[$category][$key]['required'] = false;
        }
    }
    return $fields;
}

add_action('woocommerce_checkout_create_order', 'add_custom_order_meta', 20, 2);

function add_custom_order_meta($order, $data) {
    if (isset($_POST['reserved_time'])) {
        $order->update_meta_data('reserved_time', sanitize_text_field($_POST['reserved_time']));
    }
}

add_action('wp_ajax_add_to_cart', 'handle_add_to_cart');
add_action('wp_ajax_nopriv_add_to_cart', 'handle_add_to_cart');

function handle_add_to_cart() {
    check_ajax_referer('create_order_nonce', 'nonce');

    $product_id = intval($_POST['product_id']);
    $date = sanitize_text_field($_POST['date']);
    $name = sanitize_text_field($_POST['name']);
    $phone = sanitize_text_field($_POST['phone']);
    $email = sanitize_email($_POST['email']);

    if (!wc_get_product($product_id)) {
        wp_send_json_error('Неверный идентификатор продукта.');
    }
    WC()->cart->empty_cart();

    WC()->cart->add_to_cart($product_id);

    WC()->session->set('billing_first_name', $name);
    WC()->session->set('billing_last_name', $name);
    WC()->session->set('billing_phone', $phone);
    WC()->session->set('billing_email', $email);
    WC()->session->set('reserved_time', $date);

    wp_send_json_success(array(
        'redirect_url' => home_url('/zamowienie')
    ));
}

