<?php

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

if (isset($_POST['bdpcp_booking_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['bdpcp_booking_nonce'])), 'bdpcp_booking_nonce')) {

    $product_id = isset($_POST['bdpcp_product_id']) ? intval($_POST['bdpcp_product_id']) : 0;
    $booking_date = isset($_POST['bdpcp_booking_date']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_booking_date'])) : '';
    $booking_time = isset($_POST['bdpcp_booking_time']) ? sanitize_text_field(wp_unslash($_POST['bdpcp_booking_time'])) : '';
    $time_slots = isset($_POST['bdpcp_time_slots']) ? (is_array($_POST['bdpcp_time_slots']) ? array_map('sanitize_text_field', wp_unslash($_POST['bdpcp_time_slots'])) : sanitize_text_field(wp_unslash($_POST['bdpcp_time_slots']))) : [];
    $time_slots = (array)json_decode($time_slots, true);
    $type_count = isset($_POST['bdpcp_type_count']) ? array_map('intval', $_POST['bdpcp_type_count']) : [];

    $bdpcp_product = wc_get_product($product_id);
    $price_details = !empty($bdpcp_product->get_meta('_bdcp_price_details')) ? $bdpcp_product->get_meta('_bdcp_price_details') : [];
    $unit_type = !empty($bdpcp_product->get_meta('_bdcp_unit_type')) ? $bdpcp_product->get_meta('_bdcp_unit_type') : '';
    $base_price = !empty($bdpcp_product->get_meta('_bdcp_base_price')) ? $bdpcp_product->get_meta('_bdcp_base_price') : 0;
    $fixed_base_fee = !empty($bdpcp_product->get_meta('_bdcp_fixed_base_fee')) ? $bdpcp_product->get_meta('_bdcp_fixed_base_fee') : 0;

    $current_user_id = get_current_user_id();
    $order = wc_create_order();
    $order->set_customer_id($current_user_id);

    $total_amount = 0;
    $total_slots = 0;
    if (!empty($unit_type)) {
        foreach ($type_count as $key => $value) {
            $typePrice = $price_details[$key]['price'];
            $total_slots += $value;
            $total_amount += ($typePrice * $value * count($time_slots));
        }
    } else {
        $total_amount = $base_price * count($time_slots);
        $total_slots += 1;
    }

    $order->add_product($bdpcp_product, 1, [
        'subtotal' => $total_amount,
        'total' => $total_amount
    ]);

    if (!empty($fixed_base_fee)) {
        $item_fee = new WC_Order_Item_Fee();
        $item_fee->set_name('Addition fee');
        $item_fee->set_amount($fixed_base_fee);
        $item_fee->set_total($fixed_base_fee);
        $order->add_item($item_fee);
    }

    $order->update_meta_data('_bdcp_booking_date', gmdate('Y-m-d', strtotime($booking_date)));
    foreach ($time_slots as $time) {
        $order->add_meta_data('_bdcp_booking_time', gmdate('H:i', strtotime($time)));
    }
    $order->update_meta_data('_bdcp_unit_type_count', $type_count);
    $order->update_meta_data('_bdcp_order', 1);
    $order->update_meta_data('_bdcp_product_id', $product_id);
    $order->update_meta_data('_bdcp_total_slots', $total_slots);
    $order->update_meta_data('_bdcp_price_details', $price_details);

    $order->calculate_totals();
    $order->save();

    $order_id = $order->get_id();
    $payment_url = $order->get_checkout_payment_url();
    echo ("<script>location.href = '" . $payment_url . "'</script>");
    // wp_redirect($payment_url);
    exit;
}

$bdpcp_product = null;

if (isset($atts['product_id']) && !empty($atts['product_id'])) {
    $bdpcp_product = wc_get_product($atts['product_id']);
} elseif (!empty($bdpcp_elementor_settings['bdpcp_product_id'] ?? '')) {
    $bdpcp_product = wc_get_product($bdpcp_elementor_settings['bdpcp_product_id']);
} else {
    global $product;
    $bdpcp_product = $product;
}

if (!$bdpcp_product) {
    return "Please select a product.";
}

$bdpcp_product = $bdpcp_product;
$product_name = $bdpcp_product->get_name();
$product_price = wc_price($bdpcp_product->get_price());

$bdpcp_booking_everyday = !empty($bdpcp_product->get_meta('_bdcp_booking_everyday')) ? $bdpcp_product->get_meta('_bdcp_booking_everyday') : 0;
$bdpcp_start_date = !empty($bdpcp_product->get_meta('_bdcp_start_date')) ? $bdpcp_product->get_meta('_bdcp_start_date') : '';
$bdpcp_end_date = !empty($bdpcp_product->get_meta('_bdcp_end_date')) ? $bdpcp_product->get_meta('_bdcp_end_date') : '';
$bdpcp_booking_week_off = !empty($bdpcp_product->get_meta('_bdcp_booking_week_off')) ? $bdpcp_product->get_meta('_bdcp_booking_week_off') : [];
$bdpcp_price_details = !empty($bdpcp_product->get_meta('_bdcp_price_details')) ? $bdpcp_product->get_meta('_bdcp_price_details') : [];
$bdpcp_time_slots = !empty($bdpcp_product->get_meta('_bdcp_time_slots')) ? $bdpcp_product->get_meta('_bdcp_time_slots') : [];
$bdpcp_unit_type = !empty($bdpcp_product->get_meta('_bdcp_unit_type')) ? $bdpcp_product->get_meta('_bdcp_unit_type') : '';
$bdpcp_is_multiple_time_select = !empty($bdpcp_product->get_meta('_bdcp_is_multiple_time_select')) ? $bdpcp_product->get_meta('_bdcp_is_multiple_time_select') : '';
$product_id = $bdpcp_product->get_id();

$bdpcp_time_duration = !empty($bdpcp_product->get_meta('_bdcp_time_duration')) ? $bdpcp_product->get_meta('_bdcp_time_duration') : '';
$bdpcp_time_duration_type = !empty($bdpcp_product->get_meta('_bdcp_time_duration_type')) ? $bdpcp_product->get_meta('_bdcp_time_duration_type') : '';
$bdpcp_max_slot_per_time = !empty($bdpcp_product->get_meta('_bdcp_max_slot_per_time')) ? $bdpcp_product->get_meta('_bdcp_max_slot_per_time') : 0;
$bdpcp_booking_day_off = !empty($bdpcp_product->get_meta('_bdcp_booking_day_off')) ? $bdpcp_product->get_meta('_bdcp_booking_day_off') : [];

wp_enqueue_style($this->plugin_name . '-flatpickr', BDPCP_ROOT_URL . 'public/css/flatpickr.min.css', array(), $this->version, 'all');
wp_enqueue_script($this->plugin_name . '-flatpickr', BDPCP_ROOT_URL . 'public/js/flatpickr.js', array('jquery'), $this->version, false);

wp_enqueue_style($this->plugin_name, BDPCP_ROOT_URL . 'public/css/bdpcp-public.css', array(), $this->version, 'all');
wp_enqueue_script($this->plugin_name, BDPCP_ROOT_URL . 'public/js/bdpcp-public.js', array('jquery'), $this->version, false);
wp_localize_script($this->plugin_name, 'bdpcp_object', array(
    'ajaxurl' => admin_url('admin-ajax.php'),
    'is_multiple_time_select' => $bdpcp_is_multiple_time_select,
    'booking_week_off' => $bdpcp_booking_week_off,
    'start_date' => gmdate('d-m-Y', strtotime($bdpcp_start_date)),
    'end_date' => gmdate('d-m-Y', strtotime($bdpcp_end_date)),
    'booking_everyday' => $bdpcp_booking_everyday,
    'right_arrow' => BDPCP_ROOT_URL . 'public/images/right-arrow.svg',
    'max_slot_per_time' => $bdpcp_max_slot_per_time,
    'nonce' => wp_create_nonce('bdpcp_nonce_action'),
    'booking_day_off' => $bdpcp_booking_day_off,
));

$bdpcp_settings = get_option('_bdcp_settings', []);

if (!isset($bdpcp_elementor_settings)) {
    $bdpcp_elementor_settings = [];
}

$bdpcp_setting_default = function ($key) use ($bdpcp_settings, $bdpcp_elementor_settings) {
    $default = [
        'form_background_color' => '#ffffff',
        'form_border_radius' => 8,
        'form_border_color' => '#808080',
        'form_label_size' => 14,
        'form_label_color' => '#212529',
        'form_control_background_color' => '#ffffff',
        'form_control_border_radius' => 8,
        'form_control_text_color' => '#000000',

        'book_button_text' => 'Book Now',
        'book_button_background_color' => '#212529',
        'book_button_text_color' => '#F8F9FA',

        'unit_type_background_color' => '#212529',
        'unit_type_text_color' => '#F8F9FA',

        'date_selection_label' => 'Select Date',
        'time_selection_label' => 'Select Time',
        'duration_label' => 'Duration',
        'sub_total_label' => 'Sub Total',
        'additional_fee_label' => 'Additional Fee',
        'total_amount_label' => 'Total Amount',

        'date_selection_error' => 'Please select date.',
        'time_selection_error' => 'Please select time.',
        'unit_selection_error' => 'Please select slot.',
    ];

    if (isset($bdpcp_elementor_settings['bdpcp_' . $key]) && !empty($bdpcp_elementor_settings['bdpcp_' . $key])) {
        return esc_html($bdpcp_elementor_settings['bdpcp_' . $key]);
    }
    if (isset($bdpcp_settings[$key])) {
        return esc_html($bdpcp_settings[$key]);
    }
    return esc_html($default[$key]);
};

// Inline css
$inline_css = "
    .bdpcp-main-container {
        background-color: " . esc_html($bdpcp_setting_default('form_background_color')) . " !important;
        border-radius: " . esc_html($bdpcp_setting_default('form_border_radius')) . "px !important;
        border-color: " . esc_html($bdpcp_setting_default('form_border_color')) . " !important;
    }

    .bdpcp-form-label,
    .bdpcp-price-item {
        font-size: " . esc_html($bdpcp_setting_default('form_label_size')) . "px !important;
        color: " . esc_html($bdpcp_setting_default('form_label_color')) . " !important;
    }

    .bdpcp-form-control,
    .bdpcp-time-select {
        background-color: " . esc_html($bdpcp_setting_default('form_control_background_color')) . " !important;
        border-radius: " . esc_html($bdpcp_setting_default('form_control_border_radius')) . "px !important;
        color: " . esc_html($bdpcp_setting_default('form_control_text_color')) . " !important;
    }

    .bdpcp-btn-book-now {
        background-color: " . esc_html($bdpcp_setting_default('book_button_background_color')) . " !important;
        color: " . esc_html($bdpcp_setting_default('book_button_text_color')) . " !important;
        border-radius: " . esc_html($bdpcp_setting_default('form_control_border_radius')) . "px !important;
    }

    .bdpcp-people-type-count-display {
        background-color: " . esc_html($bdpcp_setting_default('unit_type_background_color')) . " !important;
        color: " . esc_html($bdpcp_setting_default('unit_type_text_color')) . " !important;
    }
";

// Add inline css
wp_add_inline_style($this->plugin_name, $inline_css);
?>

<div class="bdpcp-main-container">
    <form action="" method="post" id="bdpcp_booking_form">
        <input type="hidden" name="action" value="bdpcp_booking">
        <input type="hidden" name="bdpcp_product_id" id="bdpcp_product_id" value="<?php echo esc_html($product_id) ?>">
        <textarea name="bdpcp_time_slots" id="bdpcp_time_slots" style="display: none;"></textarea>

        <?php wp_nonce_field('bdpcp_booking_nonce', 'bdpcp_booking_nonce'); ?>

        <?php
        global $product;
        $check_blobal_product = $product;
        if (!$check_blobal_product): ?>
            <h1 class="bookingdaddy-pro-product-name"><?php echo esc_html($product_name) ?></h1>
        <?php endif; ?>

        <div class="bdpcp-price-details">

            <div class="bdpcp-price-loading" id="bdpcp_price_loading" style="display: none;">
                <span class="bdpcp-price-loading-dots"></span>
                <span class="bdpcp-price-loading-dots"></span>
                <span class="bdpcp-price-loading-dots"></span>
            </div>

            <span id="bdpcp_price_details">
                <?php echo wp_kses_post($product_price) ?>
                <?php if (!empty($bdpcp_hour_price)) { ?>
                    / <?php echo esc_html(($bdpcp_hour_price['hours'] > 1 ? $bdpcp_hour_price['hours'] : '') . _n('Hour', ' Hours', $bdpcp_hour_price['hours'], 'bookingdaddy-pro')); ?>
                <?php } ?>
            </span>

        </div>

        <div class="bdpcp-form-group">
            <label for="bdpcp_booking_date" class="bdpcp-form-label"><?php echo esc_html($bdpcp_setting_default('date_selection_label')); ?></label>
            <input type="text" id="bdpcp_booking_date" name="bdpcp_booking_date" class="bdpcp-form-control" value="" required>
            <div class="bdpcp-error" style="display: none;"><?php echo esc_html($bdpcp_setting_default('date_selection_error')); ?></div>
        </div>

        <div class="bdpcp-form-group" id="bdpcp_time_slot_div" style="display: none;">
            <label for="bdpcp_booking_time" class="bdpcp-form-label"><?php echo esc_html($bdpcp_setting_default('time_selection_label')); ?></label>
            <div style="position: relative;">
                <div class="bdpcp-time-select" id="bdpcp_booking_time">
                </div>
                <div class="bdpcp-error" style="display: none;"><?php echo esc_html($bdpcp_setting_default('time_selection_error')) ?></div>
                <div class="bdpcp-price-loading" id="bdpcp_time_loading" style="display: none;">
                    <span class="bdpcp-price-loading-dots"></span>
                    <span class="bdpcp-price-loading-dots"></span>
                    <span class="bdpcp-price-loading-dots"></span>
                </div>
            </div>
            <div id="bdpcp_time_select_error" class="bdpcp-time-select-error"></div>
        </div>

        <?php if (!empty($bdpcp_price_details)) { ?>

            <div class="bdpcp-form-group">
                <?php if (empty($bdpcp_hour_price)): ?>
                    <label for="bdpcp_people" class="bdpcp-form-label">
                        <?php
                        /* translators: %s is replaced with the unit type */
                        echo sprintf(esc_html__('No. of %s', 'bookingdaddy-pro'), esc_attr($bdpcp_unit_type)); ?>
                    </label>
                <?php else: ?>
                    <label for="bdpcp_people" class="bdpcp-form-label"><?php esc_html_e('Hours', 'bookingdaddy-pro') ?></label>
                <?php endif; ?>

                <?php foreach ($bdpcp_price_details as $key => $value) { ?>
                    <input type="hidden" id="bdpcp_count_<?php echo esc_html($key) ?>" class="bdpcp-type-count" data-people-type="<?php echo esc_html($key) ?>" name="bdpcp_type_count[<?php echo esc_html($key) ?>]" value="<?php echo esc_html($value['min_slot']) ?>">
                <?php } ?>

                <div class="bdpcp-form-control bdpcp-people-select-control" style="display: flex; gap: 2px;padding: 7px;" tabindex="0">
                    <?php foreach ($bdpcp_price_details as $key => $value) { ?>
                        <div class="bdpcp-people-type-count-display" id="bdpcp_count_display_<?php echo esc_html($key) ?>">
                            <?php echo esc_html($value['min_slot']) ?> <?php echo esc_html(ucfirst($key)) ?>
                        </div>
                    <?php } ?>
                </div>
                <div class="bdpcp-error" style="display: none;"><?php echo esc_html($bdpcp_setting_default('unit_selection_error')) ?></div>
            </div>
        <?php } else if (!empty($bdpcp_time_duration)) { ?>
            <div class="bdpcp-form-group">
                <label for="bdpcp_display_hour" class="bdpcp-form-label"><?php echo esc_html($bdpcp_setting_default('duration_label')); ?></label>
                <input type="text" id="bdpcp_display_hour" name="bdpcp_display_hour" class="bdpcp-form-control" value="<?php echo esc_html($bdpcp_time_duration . ' ' . ucfirst($bdpcp_time_duration_type)) ?>" readonly>
            </div>
        <?php } ?>

        <div id="bdpcp_total_price_details">

        </div>

        <div>
            <button class="bdpcp-btn-book-now" id="bdpcp_btn_book_now" type="buttom">
                <?php echo esc_html($bdpcp_setting_default('book_button_text')); ?>
            </button>
        </div>
    </form>

    <div class="bdpcp-people-container" style="display: none;">
        <div class="bdpcp-people-container-arrow"></div>
        <?php foreach ($bdpcp_price_details as $key => $value) { ?>
            <div class="bdpcp-people-type">
                <div><?php echo esc_html(ucfirst($key)) ?></div>
                <?php if (!isset($value['editable']) || (isset($value['editable']) && !empty($value['editable']))): ?>
                    <div class="bdpcp-people-actions">
                        <button type="button" data-min="<?php echo esc_html($value['min_slot']) ?>" class="bdpcp-people-button bdpcp-btn-minus" data-people-type="<?php echo esc_html($key) ?>">-</button>
                        <div id="bdpcp_count_control_<?php echo esc_html($key) ?>" style="width: 25px; text-align: center;"><?php echo esc_html($value['min_slot']) ?></div>
                        <button type="button" data-max="<?php echo esc_html($value['max_slot']) ?>" class="bdpcp-people-button bdpcp-btn-plus" data-people-type="<?php echo esc_html($key) ?>">+</button>
                    </div>
                <?php endif; ?>
            </div>
        <?php } ?>
    </div>
</div>