<?php

add_action( 'wp_enqueue_scripts', 'basel_child_enqueue_styles', 1000 );

function basel_child_enqueue_styles() {
	$version = basel_get_theme_info( 'Version' );

	if( basel_get_opt( 'minified_css' ) ) {
		wp_enqueue_style( 'basel-style', get_template_directory_uri() . '/style.min.css', array('bootstrap'), $version );
	} else {
		wp_enqueue_style( 'basel-style', get_template_directory_uri() . '/style.css', array('bootstrap'), $version );
	}

    wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array('bootstrap'), $version );
}
//add_action( 'wp_enqueue_scripts', 'basel_child_script' );
function basel_child_script() {

wp_enqueue_script( 'slick.js', get_stylesheet_directory_uri() . 'inc/assets/js/slick.min.js');
}
add_action( 'woocommerce_review_order_after_order_total', 'woocommerce_checkout_coupon_form_custom' );

    function woocommerce_checkout_coupon_form_custom() {
        echo '<tr class="coupon-form"><td colspan="2">';?>
		<div class="coupon-field tt">
			<?php  if ( isset( $_POST['apply_coupon'] ) && empty( $_POST['coupon_code'] ) ) {
					echo "<p class='error_coupon'>Please enter a coupon code.</p>";}?>
					<p class="hide-cont">If you have a coupon code, please apply it below.</p>
					<form class="form-coupons" method="post">
						<input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Enter Coupon code', 'woocommerce' ); ?>" id="coupon_code" value="" />
						<button type="submit" class="btn-red greenBtn" name="apply_coupon" value="<?php esc_attr_e( 'Apply ', 'woocommerce' ); ?>">
							<span><?php esc_html_e( 'Apply Coupon', 'woocommerce' ); ?></span>
						</button>
					</form>
			</div>
			<?php
		 echo '</td></tr> ';
    }

add_action( 'woocommerce_review_order_before_payment', 'estimate_text' );
function estimate_text(){?>
    <p class="estimate-text">
	<?php if( basel_get_opt( 'checkout-bar' ) != '' ): ?>
	<?php echo do_shortcode( basel_get_opt( 'checkout-bar' ) ); ?>
	<?php endif; ?>
	</p>
   	<?php  }
/**woocommerce_proceed_to_checkout **/
add_action( 'woocommerce_proceed_to_checkout', 'woocommerce_cart_totals_after_shippingss' );
function woocommerce_cart_totals_after_shippingss(){ ?>
<div class="coupon-field gg">
<?php echo '<tr class="coupon-form"><td colspan="2">';?>
		<div class="coupon-field">
			<?php  if ( isset( $_POST['apply_coupon'] ) && empty( $_POST['coupon_code'] ) ) {
					echo "<p class='error_coupon'>Please enter a coupon code.</p>";}?>
					<form class="form-coupons" method="post">
						<input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Enter Coupon code', 'woocommerce' ); ?>" id="coupon_code" value="" />
						<button type="submit" class="btn-red greenBtn" name="apply_coupon" value="<?php esc_attr_e( 'Apply ', 'woocommerce' ); ?>">
							<span><?php esc_html_e( 'Apply Coupon', 'woocommerce' ); ?></span>
						</button>
					</form>
			</div>
			<?php
		 echo '</td></tr>';

}
add_action( 'woocommerce_before_cart', 'woocommerce_output_all_notices', 10 );

add_action( 'woocommerce_cart_collaterals', 'woocommerce_cross_sell_display' );
add_action( 'woocommerce_cart_collaterals', 'woocommerce_cart_totals', 10 );

add_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
add_filter('woocommerce_dropdown_variation_attribute_options_args','fun_select_default_option',10,1);
function fun_select_default_option( $args)
{

    if(count($args['options']) > 0) //Check the count of available options in dropdown
        $args['selected'] = $args['options'][0];
    return $args;
}
/**
 * Disable messages about the mobile apps in WooCommerce emails.
 * https://wordpress.org/support/topic/remove-process-your-orders-on-the-go-get-the-app/
 */
function mtp_disable_mobile_messaging( $mailer ) {
    remove_action( 'woocommerce_email_footer', array( $mailer->emails['WC_Email_New_Order'], 'mobile_messaging' ), 9 );
}
add_action( 'woocommerce_email', 'mtp_disable_mobile_messaging' );
/**
* Apply Coupon automatically to the cart
*/
add_action('woocommerce_before_cart', 'auto_apply_discount_coupon');
function auto_apply_discount_coupon() {
    $wc_coupon = new WC_Coupon('A Founder\'s  Circle Gift Thank You'); // get intance of wc_coupon which code is "DEMO-90JOURS"
    if (!$wc_coupon || !$wc_coupon->is_valid()) {
        return;
    }

    $coupon_code = $wc_coupon->get_code();
    if (!$coupon_code) {
        return;
    }

    global $woocommerce;
    if (!$woocommerce->cart->has_discount($coupon_code)) {
        if (!$woocommerce->cart->apply_coupon($coupon_code)) {
            $woocommerce->wc_print_notices();
            return;
        }

        //wc_print_notice('' . $coupon_code . '', 'notice');
    }
}

//add_action('woocommerce_after_shop_loop_item','replace_add_to_cart');
function replace_add_to_cart() {
    global $product;
    $link = $product->get_permalink();
    if ( !$product->is_in_stock() ) {
		echo do_shortcode('<a href="'.$link.'" class="button addtocartbutton">Out of Stock</a>');
	}else{
		echo '<a href="'. $product->add_to_cart_url().'" value="'. esc_attr( $product->get_id() ).'" class="ajax_add_to_cart add_to_cart_button" data-product_id="'.$product->get_id() .'" aria-label="Add “<?php //the_title_attribute() ?>” to your cart">Add to Cart</a>';
	}
}


add_filter('woocommerce_get_availability_text', 'themeprefix_change_soldout', 10, 2 );

/**
* Change Sold Out Text to Something Else
*/
function themeprefix_change_soldout ( $text, $product) {
if ( !$product->is_in_stock() ) {
	 $shop_page_url = get_permalink( wc_get_page_id( 'shop' ) );
$text = 'Currently Fully Reserved. We invite you to explore <a href="'.$shop_page_url.'">our other exquisite styles.</a>';
}
return $text;
}


add_filter('posts_clauses', 'order_by_stock_status');
function order_by_stock_status($posts_clauses) {
    global $wpdb;
    // only change query on WooCommerce loops
    if (is_woocommerce() && (is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy())) {
        $posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) ";
        $posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
        $posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
    }
    return $posts_clauses;
}
add_filter( 'woocommerce_email_order_items_args', 'bbloomer_order_with_product_images', 9999 );

function bbloomer_order_with_product_images( $args ) {
   $args['show_image'] = true;
   return $args;
}
function reordered_tabs($tabs) {
    $tabs['reviews']['priority'] = 9999;
    return $tabs;
}
add_filter('woocommerce_product_tabs', 'reordered_tabs');

function display_reviews($rating = 'all', $page = 1) {
    global $wpdb;

    $per_page = 10;
    $offset = ($page - 1) * $per_page;

    $query = "
        SELECT {$wpdb->comments}.comment_ID, comment_post_ID, comment_author, comment_content, comment_approved,
              meta_value AS rating
        FROM {$wpdb->comments}
        LEFT JOIN {$wpdb->commentmeta} ON {$wpdb->comments}.comment_ID = {$wpdb->commentmeta}.comment_id
        WHERE meta_key = 'rating' AND comment_approved = 1
    ";

    if ($rating !== 'all') {
        $query .= $wpdb->prepare(" AND meta_value = %d", $rating);
    }

    $query .= " ORDER BY comment_date DESC LIMIT %d OFFSET %d";

    $query = $wpdb->prepare($query, $per_page, $offset);
    $reviews = $wpdb->get_results($query);

// Display the comments
if (!empty($reviews)) {
    foreach ($reviews as $review) {
        setup_postdata($review);
        $product_id = $review->comment_post_ID;
        $product = wc_get_product($review->comment_post_ID);
        $dateString = $review->comment_date;
        $timestamp = strtotime($dateString);
        $usDateFormat = date('m/d/Y', $timestamp);

        echo '<div class="review">';
        echo '<span class="reviewer-first-letter">' . strtoupper(substr($review->comment_author, 0, 1)) . '<span class="vc_icon_element-icon fas fa-check"></span> </span>';
        echo wc_get_rating_html($review->rating);
        echo '<span class="combination"><span class="date">' . $usDateFormat . ' about </span> <span class="product__name"><a href="' . get_permalink($product_id) . '">' . esc_html($product->get_name()) . '</a></span></span>';
        echo '<div class="author"> ' . esc_html($review->comment_author) . '</div> ';
        echo '<p class="content">' . esc_html($review->comment_content) . '</p>';
        echo '</div>';
    }
    wp_reset_postdata();
} else {
    echo '<h3>No reviews found.</h3>';
}



//echo '</div>';


}

function display_pagination($rating = 'all', $page = 1) {
    global $wpdb;

    $per_page = 10;

    $query = "
        SELECT COUNT(*) AS total
        FROM {$wpdb->comments}
        LEFT JOIN {$wpdb->commentmeta} ON {$wpdb->comments}.comment_ID = {$wpdb->commentmeta}.comment_id
        WHERE meta_key = 'rating' AND comment_approved = 1
    ";

    if ($rating !== 'all') {
        $query .= $wpdb->prepare(" AND meta_value = %d", $rating);
    }

    $total_reviews = $wpdb->get_var($query);
    $total_pages = ceil($total_reviews / $per_page);

    echo '<div class="pagination">';
        if ($page > 1) {
            $prev_page = $page - 1;
            echo '<a href="#" class="' . $active . '" data-page="' . $prev_page . '">  Previous</a> ';
        }

    if ($total_pages > 1) {

        for ($i = 1; $i <= $total_pages; $i++) {
            $active = ($i == $page) ? 'active' : '';
            echo '<a href="#" class="' . $active . '" data-page="' . $i . '">' . $i . '</a> ';
        }

    }


if ($page < $total_pages) {
    $next_page = $page + 1;
    echo '<a href="#" class="' . $active . '" data-page="' . $next_page . '">  Next</a> ';
}
echo '</div>';


}


function filter_reviews() {
    check_ajax_referer('filter_reviews_nonce', 'nonce');

    $rating = isset($_POST['rating']) ? sanitize_text_field($_POST['rating']) : 'all';
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;

    ob_start();
    display_reviews($rating, $page);
    $reviews_html = ob_get_clean();

    ob_start();
    display_pagination($rating, $page);
    $pagination_html = ob_get_clean();

    wp_send_json_success([
        'reviews' => $reviews_html,
        'pagination' => $pagination_html
    ]);
}

add_action('wp_ajax_filter_reviews', 'filter_reviews');
add_action('wp_ajax_nopriv_filter_reviews', 'filter_reviews');

function display_product_ratings_overview() {
    global $wpdb;

    // Query to get the count of each rating
    $query = "
        SELECT meta_value AS rating, COUNT(meta_value) AS count
        FROM {$wpdb->commentmeta}
        LEFT JOIN {$wpdb->comments} ON {$wpdb->comments}.comment_ID = {$wpdb->commentmeta}.comment_id
        WHERE meta_key = 'rating' AND comment_approved = 1
        GROUP BY meta_value
    ";

    $ratings = $wpdb->get_results($query, ARRAY_A);

    $total_reviews = 0;
    $ratings_count = [
        '5' => 0,
        '4' => 0,
        '3' => 0,
        '2' => 0,
        '1' => 0,
    ];

    // Calculate total reviews and individual rating counts
    foreach ($ratings as $rating) {
        $total_reviews += $rating['count'];
        $ratings_count[$rating['rating']] = $rating['count'];
        $ratings_sum += $rating['rating'] * $rating['count'];
    }

    // Calculate percentages
    $ratings_percentage = array_map(function($count) use ($total_reviews) {
        return $total_reviews ? round(($count / $total_reviews) * 100, 2) : 0;
    }, $ratings_count);


// Calculate the overall average rating
    $overall_average_rating = $total_reviews ? round($ratings_sum / $total_reviews, 2) : 0;

	echo '<div class="basedreview">
    <p><span class="star-rating"><span style="width:'.($overall_average_rating*10*2).'%"></span></span><br>'.$overall_average_rating ;


	echo ' Based on '.$total_reviews.' reviews </p>';


    // Display the results
    echo '<div class="divder"></div><div class="ratings-summary">';
    $width= 100;$countdata =5;
    foreach ($ratings_count as $rating => $count) {
        echo '<div class="rating" data-value="'.$countdata.'">';
        echo '<span class="star-rating"><span style="width:'.$width.'%"></span></span>';
        echo $ratings_percentage[$rating] . '% (' . $count . ' Reviews)';
        echo '</div>';

        $width = $width-20;
        $countdata--;
    }
    echo '</div></div>';
}
