<?php

/*
Theme Designed By: Meysam Hosseinkhani
Email: Meysam98@Gmail.com
Demo Website: dinakala.i-design.ir
Author Website: i-design.ir
*/

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) )
    exit;

// Add dina order time delivery CSS & JS
add_action( 'wp_enqueue_scripts', 'dina_order_delivery_time_enqueue' );
function dina_order_delivery_time_enqueue() {
    if ( is_checkout() ) {
        wp_enqueue_style( 'dina-order-delivery-time-css', DI_URI . '/includes/woo/assets/dina-order-delivery-time.css', array(), DI_VER );
        wp_enqueue_script( 'dina-order-delivery-time-js', DI_URI . '/includes/woo/assets/dina-order-delivery-time.js', ['jquery'], DI_VER, true );
        wp_localize_script( 'dina-order-delivery-time-js', 'dinaDeliveryAjax', [
            'ajax_url' => admin_url( 'admin-ajax.php' )
        ] );
    }
}

// Add dina order time delivery wrapper
add_action( dina_opt( 'order_delivery_time_location' ), function () {
    if ( dina_should_show_delivery_table_on_load() ) {
        echo '<div id="dina-delivery-table-wrap">';
        echo dina_delivery_table_html();
        echo '</div>';
    } else {
        echo '<div id="dina-delivery-table-wrap" style="display:none;"></div>';
    }
});

// dina_should_show_delivery_table_on_load
function dina_should_show_delivery_table_on_load() {
    $raw_allowed = dina_opt( 'order_delivery_time_cities' ) ?? '[]';
    $allowed = is_string( $raw_allowed ) ? json_decode( $raw_allowed, true ) : $raw_allowed;

    if ( empty( $allowed ) ) {
        return true;
    }

    $state = WC()->customer->get_billing_state();
    $city  = WC()->customer->get_billing_city();

    if ( ! $state || ! $city ) {
        return false;
    }

    foreach ( $allowed as $item ) {
        if (
            isset( $item['state_code'], $item['city_label'] ) &&
            $item['state_code'] === $state &&
            $item['city_label'] === $city
        ) {
            return true;
        }
    }

    return false;
}



// Add dina order time delivery AJAX response
add_action( 'wp_ajax_check_delivery_table_visibility', 'dina_check_delivery_table_visibility' );
add_action( 'wp_ajax_nopriv_check_delivery_table_visibility', 'dina_check_delivery_table_visibility' );
function dina_check_delivery_table_visibility() {
    $city  = sanitize_text_field($_POST['city'] ?? '');
    $state = sanitize_text_field($_POST['state'] ?? '');

    $raw = dina_opt('order_delivery_time_cities') ?? '[]';
    $allowed = is_string($raw) ? json_decode($raw, true) : $raw;

    if ( empty( $allowed ) ) {
        wp_send_json_success( dina_delivery_table_html() );
    }

    foreach ( $allowed as $item ) {
        if ( $item['state_code'] === $state && ( $item['city_label'] === $city || $item['city_code'] == '01' ) ) {
            wp_send_json_success( dina_delivery_table_html() );
        }
    }

    wp_send_json_error();
}

// dina_delivery_table_html
function dina_delivery_table_html() {

    $digital = false;
    foreach (WC()->cart->get_cart() as $cart_item) {
        if ($cart_item['data']->is_virtual()) {
            $digital = true;
            break;
        }
    }
    if (dina_opt('order_delivery_time_disable_digital') && $digital) {
        return;
    }

    dina_set_wp_timezone();

    ob_start();

    $delivery_day_number    = (int)(dina_opt('order_delivery_time_days') ?: 7);
    $delivery_day_start     = (int) dina_opt('order_delivery_time_start') ?: 0;
    $delivery_time_options  = dina_opt('order_delivery_time_day_ranges') ?? '[]';
    $delivery_time_ranges   = is_string($delivery_time_options) ? json_decode($delivery_time_options, true) : $delivery_time_options;
    $delivery_disable_days  = dina_opt( 'order_delivery_time_disable_days' ) ?? '[]';
    $delivery_disable_dates = dina_opt( 'order_delivery_time_disable_dates' ) ?? '[]';
    $delivery_disable_days  = is_array($delivery_disable_days) ? $delivery_disable_days : (is_string($delivery_disable_days) && !empty($delivery_disable_days) ? explode(',', $delivery_disable_days) : []);
    $delivery_disable_dates = is_array($delivery_disable_dates) ? $delivery_disable_dates : (is_string($delivery_disable_dates) && !empty($delivery_disable_dates) ? explode(',', $delivery_disable_dates) : []);
    $delivery_time_default  = dina_opt( 'order_delivery_time_default' );
    $default_selected       = ! $delivery_time_default ? true : false;
    
    $future_days = [];
    for ($i = 0; $i < $delivery_day_number; $i++) {
        $timestamp     = time() + (($delivery_day_start + $i) * 86400);
        $day_key       = strtolower(date('l', $timestamp));
        $day_label     = dina_date('l', $timestamp);
        $date_label    = dina_date('j F', $timestamp);
        $data_date     = dina_date('Y/m/d', $timestamp);
        

        $date_inactive = in_array( $day_key, $delivery_disable_days ) || in_array( $data_date, $delivery_disable_dates );

        $future_days[] = [
            'key'      => 'day-' . $i,
            'label'    => $day_label,
            'date'     => $date_label,
            'inactive' => $date_inactive,
            'slot_key' => $day_key,
            'date_raw' => dina_date('Y-m-d', $timestamp),
        ];

    }
    ?>
    <div class="dina-delivery-tabs">

        <?php if (!empty(dina_opt('order_delivery_time_title'))) : ?>
            <div class="dina-delivery-title">
                <?= esc_html(dina_opt('order_delivery_time_title')) ?>
            </div>
        <?php endif; ?>

        <?php
        $first_active_index = 0;
        foreach ($future_days as $i => $day) {
            if (! $day['inactive']) {
                $first_active_index = $i;
                break;
            }
        }
        ?>

        <ul class="dina-delivery-tab-nav owl-carousel" data-dir="<?= dina_rtl() ?>" data-itemnavs="true">
            <?php foreach ($future_days as $i => $day) : ?>
                <li class="<?= $day['inactive'] ? 'dina-inactive-delivery-day ' : '' ?><?= $i === $first_active_index ? 'active' : '' ?>" data-day="<?= esc_attr($day['key']) ?>">
                    <?= esc_html($day['label']) ?><br>
                    <span class="dina-tab-date"><?= esc_html($day['date']) ?></span>
                    <?php if ($day['inactive']) : ?>
                        <span class="dina-tab-inactive"><?= dina_opt( 'order_delivery_time_inactive' ) ?></span>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>

        <?php foreach ($future_days as $i => $day) : ?>
            <div class="dina-delivery-tab-content<?= $day['inactive'] ? ' dina-inactive-delivery-tab-content' : '' ?>" data-day="<?= esc_attr($day['key']) ?>" style="<?= $i === $first_active_index ? '' : 'display:none;' ?>">

                <?php if (!empty($delivery_time_ranges[$day['slot_key']])) : ?>
                    <?php foreach ($delivery_time_ranges[$day['slot_key']] as $slot): ?>
                        <?php
                        $value = "{$day['date_raw']}_{$day['slot_key']}_{$slot['from']}-{$slot['to']}";
                        $checked = '';
                        $disabled = false;

                        // مقدار ساعت مانده از تنظیمات
                        $min_hours_left = (int) dina_opt( 'order_delivery_time_min_hours_left' );
                        if ( $delivery_day_start == 0 && !$day['inactive'] && $i === 0 ) {
                            $now = date('H:i');
                            // اگر زمان فعلی بزرگتر یا مساوی انتهای بازه باشد غیرفعال شود
                            if ($slot['to'] <= $now) {
                                $disabled = true;
                            } else if ($min_hours_left > 0) {
                                // محاسبه اختلاف ساعت فعلی تا انتهای بازه
                                $slot_to_time = strtotime(date('Y-m-d') . ' ' . $slot['to']);
                                $now_time = strtotime(date('Y-m-d') . ' ' . $now);
                                $hours_left = ($slot_to_time - $now_time) / 3600;
                                if ($hours_left < $min_hours_left) {
                                    $disabled = true;
                                }
                            }
                        }

                        if ( ! $default_selected && ! $day['inactive'] && ! $disabled ) {
                            $checked = ' checked';
                            $default_selected = true;
                        }
                        ?>
                        <label<?= $day['inactive'] || $disabled ? ' class="dina-disabled-time-range"' : '' ?>>
                            <input type="radio" name="delivery_slot" value="<?= esc_attr($value) ?>" <?= $checked ?> <?php disabled( $day['inactive'] || $disabled, true ); ?>>
                            <?= sprintf(
                                esc_html__('From %1$s To %2$s', 'dina-kala'),
                                esc_html($slot['from']),
                                esc_html($slot['to'])
                            ) ?>
                            <?php if ($disabled): ?>
                                <span class="dina-time-range-inactive"><?= '('. dina_opt( 'order_delivery_hours_inactive' ) .')' ?></span>
                            <?php endif; ?>
                        </label>
                    <?php endforeach; ?>
                <?php else : ?>
                    <p><?= dina_opt( 'order_delivery_time_no_range' ) ?></p>
                <?php endif; ?>

            </div>
        <?php endforeach; ?>

    </div>

    <?php
    return ob_get_clean();
}

// dina_order_delivery_time_checkout_process
add_action( 'woocommerce_checkout_process', 'dina_order_delivery_time_checkout_process' );
function dina_order_delivery_time_checkout_process() {
    // Check if option to require delivery time is enabled
    if ( ! dina_opt( 'req_order_delivery_time' ) ) {
        return;
    }

    // Check if the delivery_slot field exists in the form
    if ( isset( $_POST['delivery_slot'] ) && empty( $_POST['delivery_slot'] ) ) {
        wc_add_notice( dina_opt( 'order_delivery_time_req_error' ), 'error' );
    }
}

// dina_add_order_delivery_time_order_meta
add_action('woocommerce_checkout_create_order', 'dina_add_order_delivery_time_order_meta', 10, 2);
function dina_add_order_delivery_time_order_meta( $order, $data ) {
    if ( !empty( $_POST['delivery_slot'] ) ) {
        $slot_value = sanitize_text_field( $_POST['delivery_slot'] );
        $order->update_meta_data( '_dina_delivery_slot', $slot_value );
    }
}

// dina_display_delivery_slot_thankyou
add_action( 'woocommerce_order_details_before_order_table', 'dina_display_delivery_slot_thankyou', 20 );
function dina_display_delivery_slot_thankyou( $order_id ) {
    $order = wc_get_order( apply_filters( 'dina_shortcode_delivery_time_order_id', $order_id ) );
    $slot  = $order->get_meta( '_dina_delivery_slot' );
    if ( $slot ) {
        echo '<p class="dina-order-view-delivery-time"><strong><i class="fal fa-clock" aria-hidden="true"></i> ' . dina_opt( 'order_delivery_time_thankyou' ) . '</strong> ' . esc_html( dina_format_slot( $slot ) ) . '</p>';
    }
}

// dina_admin_order_data_after_shipping_address
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'dina_admin_order_data_after_shipping_address' );
function dina_admin_order_data_after_shipping_address( $order ) {
    $slot = $order->get_meta( '_dina_delivery_slot' );
    if ( $slot ) {
        echo '<p><strong>' . dina_opt( 'order_delivery_time_admin' ) . '</strong> ' . esc_html( dina_format_slot($slot) ) . '</p>';
    }
}

// dina_format_slot
function dina_format_slot($value) {
    $parts = explode('_', $value);
    if (count($parts) === 3) {
        $date  = $parts[0];
        $day   = $parts[1];
        $range = str_replace('-', esc_html__(' To ', 'dina-kala'), $parts[2]);

       $days = [
            'saturday'  => esc_html__( 'Saturday', 'dina-kala' ),
            'sunday'    => esc_html__( 'Sunday', 'dina-kala' ),
            'monday'    => esc_html__( 'Monday', 'dina-kala' ),
            'tuesday'   => esc_html__( 'Tuesday', 'dina-kala' ),
            'wednesday' => esc_html__( 'Wednesday', 'dina-kala' ),
            'thursday'  => esc_html__( 'Thursday', 'dina-kala' ),
            'friday'    => esc_html__( 'Friday', 'dina-kala' ),
        ];

        if ( dina_is_jalali_date( $date ) ) {
            $date = dina_jalali_date_to_gregorian_string( $date );
        }

        $day_label = isset($days[$day]) ? $days[$day] : $day;
        
        return dina_date( 'j F Y', strtotime( $date ) ) . ' - ' . $day_label . ' - ' . $range;
    }

    return esc_html($value);
}

//Dina order delivery time Shortcode
function dina_order_delivery_time( $atts ) {
    $order_id = $atts['order_id'];

    if ( empty ( $order_id ) )
        return;

    $order = wc_get_order( apply_filters( 'dina_shortcode_delivery_time_order_id', $order_id ) );

    if ( ! $order ) 
        return;

    $delivery_time = $order->get_meta( '_dina_delivery_slot' );
    $dina_delivery_time = esc_html( dina_format_slot( $delivery_time ) );
    
    return $dina_delivery_time;
}
add_shortcode( 'dina_order_delivery_time', 'dina_order_delivery_time' );

// Add Persian Woocommerce shortcode for delivery time
add_filter( 'pwoosms_order_sms_body_before_replace', function ( $content, $shortcodes, $replacements, $order_id, $order ) {
    $slot               = $order->get_meta( '_dina_delivery_slot' );
    $dina_delivery_time = esc_html( dina_format_slot( $slot ) );

    $shortcodes[] = '{dina_delivery_time}';

    $replacements[] = $dina_delivery_time;

    return str_ireplace( $shortcodes, $replacements, $content );
}, 10, 5 );