<?php

//define('RATING_TOTALS', 'rating_total_value' );
//define('RATING_COUNTS', 'rating_total_votes' ); 

define('RATING_TOTALS2', '_post_rating_total' );
define('RATING_COUNTS2', '_post_rating_count' ); 
  
// Enqueue jQuery and custom script, localize AJAX vars
function enqueue_rating_script() {
	if (is_single()) {
    wp_enqueue_script('jquery'); // Already included in WP
    wp_register_script('rating-script', get_template_directory_uri() . '/libs/rating/rating2.js', array('jquery'), '1.0', true);
    wp_enqueue_script('rating-script');
    wp_localize_script('rating-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('rating_nonce')
    ));
	}
}
add_action('wp_enqueue_scripts', 'enqueue_rating_script');


// AJAX handler for rating submission (logged-in users)
function handle_post_rating() {
	global $opt_themes;
    check_ajax_referer('rating_nonce', 'nonce');
    $post_id 	= intval($_POST['post_id']);
    $rating 	= intval($_POST['rating']);
    $ip 		= $_SERVER['REMOTE_ADDR'];
    
	// Prevent ALL caching
    if (!defined('DONOTCACHEPAGE')){ 
		define('DONOTCACHEPAGE', true);
	}
    if (function_exists('nocache_headers')){ 
		nocache_headers();
	} 
	
	if($opt_themes['restriction']){
    // Check if user already voted (store IPs in post meta array)
		$voted_ips = get_post_meta($post_id, 'rating_voted_ips', true) ?: array();
		if (in_array($ip, $voted_ips)) {
			wp_send_json_error('You have already rated this post.');
		}
    }
    // Update ratings
    $total = (int) get_post_meta($post_id, RATING_TOTALS2, true) ?: 0;
    $count = (int) get_post_meta($post_id, RATING_COUNTS2, true) ?: 0;
    $count++;
    $total += $rating;
    update_post_meta($post_id, RATING_COUNTS2, $count);
    update_post_meta($post_id, RATING_TOTALS2, $total);
	
	if($opt_themes['restriction']){
		$voted_ips[] = $ip;
		update_post_meta($post_id, 'rating_voted_ips', $voted_ips);
	}
    
    $average = round($total / $count, 1);
    wp_send_json_success(array(
		'average' => $average, 
		'votes' => number_format_i18n($count), 
        'message' => $opt_themes['rating_error2']
	));
}

// AJAX handler for non-logged-in users
function handle_post_rating_nopriv() {
    handle_post_rating(); // Reuse the same logic
}

// Hook the AJAX actions
add_action('wp_ajax_submit_rating', 'handle_post_rating');
add_action('wp_ajax_nopriv_submit_rating', 'handle_post_rating_nopriv');


// 1. Add Enhanced Meta Box with Input Fields
function my_rating_manual_meta_box() {
    add_meta_box(
        'my_rating_manual_box',
        'Rating Post',
        'my_rating_manual_callback',
        ['post'], // add more post types if needed
        'side',
        'high'
    );
}
add_action('add_meta_boxes', 'my_rating_manual_meta_box');

// 2. Meta Box HTML + Inputs
function my_rating_manual_callback($post) {
    $post_id 	= $post->ID;

    // Get current values
    $total 		= floatval(get_post_meta($post_id, RATING_TOTALS2, true));
    $count   	= intval(get_post_meta($post_id, RATING_COUNTS2, true));
    $average	= $count > 0 ? round($total / $count, 1) : 0;

    // Nonce for security
    wp_nonce_field('my_rating_manual_save', 'my_rating_manual_nonce');
    ?>

    <style>
	:root {
	  --c_modal_bg: hsl(var(--modal-bg)); 
	  --c_text: hsl(var(--c-text)); 
	  --c_star: silver; 
	  --c_star_fill: orangered; 
	}

        .rating-manual-inputs label { display:block; margin:8px 0 4px; font-weight:600; }
        .rating-manual-inputs input { width:auto; padding:6px; }
        .rating-current { padding:10px; border:1px solid #ddd; font-size:15px; }
    </style>

	<div class="rating-current" style="text-align: center;">
	<strong>Current Displayed Rating:</strong><br>
	<strong style="font-weight: bold;"><?php echo $average; ?></strong> / 5 from <strong style="font-weight: bold;"><?php echo number_format_i18n($count); ?> </strong>vote(s)
		<div style="margin-top:8px;">
		<?php for($i=1;$i<=5;$i++): ?>
		<span style="font-size:2.4em;color:<?php echo $i<=$average ? ' orangered ' : ' silver '; ?>">★</span>
		<?php endfor; ?>
		</div>
	</div>
	
    <div class="rating-manual-inputs">
        <label>Average Rating (1–5) (<?php echo floatval(get_post_meta( $post->ID, 'wp_rated_GP', true )); ?>)</label>
        <input type="number" step="0.01" min="0" max="5" name="manual_average" value="<?php echo esc_attr($average); ?>" placeholder="e.g. 4.32" />

        <label>Number of Votes (<?php echo floatval(get_post_meta( $post->ID, 'wp_ratings_GP', true )); ?>)</label>
        <input type="number" min="0" name="manual_count" value="<?php echo esc_attr($count); ?>" />

        <label style="display:none">Total Score (Sum of all votes)</label>
        <input type="number" step="0.01" min="0" name="manual_total" value="<?php echo esc_attr($total); ?>" style="display:none" />

        <p style="margin:15px 0 8px;">
		<input type="submit" class="button button-primary" value="Save Manual Rating" />
        </p>

    </div>

    <?php
}

// 3. Save the Manual Values
function my_rating_manual_save($post_id) {
    // Verify nonce + permissions
    if (!isset($_POST['my_rating_manual_nonce']) || 
        !wp_verify_nonce($_POST['my_rating_manual_nonce'], 'my_rating_manual_save')) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    // Prevent auto-save interference
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    // Get and sanitize inputs
    $average = isset($_POST['manual_average']) ? floatval($_POST['manual_average']) : 0;
    $total   = isset($_POST['manual_total']) ? floatval($_POST['manual_total']) : 0;
    $count   = isset($_POST['manual_count']) ? intval($_POST['manual_count']) : 0;

    // Optional: keep consistency (recalculate total from average × count if average is filled)
    if ($average > 0 && $count > 0) {
        $total = round($average * $count, 2);
    } elseif ($average > 0 && $count == 0) {
        // If count is 0 but average given → set count to 1
        $count = 1;
        $total = $average;
    }

    // Save (or delete if zero)
    if ($total > 0) {
        update_post_meta($post_id, RATING_TOTALS2, $total);
    } else {
        delete_post_meta($post_id, RATING_TOTALS2 );
    }

    if ($count > 0) {
        update_post_meta($post_id, RATING_COUNTS2, $count);
    } else {
        delete_post_meta($post_id, RATING_COUNTS2 );
    }
}
add_action('save_post', 'my_rating_manual_save');


/* Columns */
function rating_add_column($columns) {
    $columns['rating'] = __('Rating', 'textdomain');
    return $columns;
}
//add_filter('manage_post_posts_columns', 'rating_add_column');

/* Column content */
function rating_column_content($column, $post_id) {
    if ($column !== 'rating') return;

    $total = (float) get_post_meta($post_id, RATING_TOTALS2, true);
    $count = (int)   get_post_meta($post_id, RATING_COUNTS2, true);
    $average = $count ? round($total / $count, 1) : 0;

    echo $average ? $average . ' (' . $count . ')' : '—';
}
//add_action('manage_post_posts_custom_column', 'rating_column_content', 10, 2);


// Display rating stars in the post content (add this where you want ratings, e.g., single.php)
function display_post_rating($post_id) {
	global $opt_themes;
    $total 		= (int) get_post_meta($post_id, RATING_TOTALS2, true) ?: 0;
    $count 		= (int) get_post_meta($post_id, RATING_COUNTS2, true) ?: 0;	
    $average 	= $count > 0 ? round($total / $count, 1) : 0;
    ?>
	
	<div class="rate">	 
	
	<div class="rating-stars " data-post-id="<?php echo $post_id; ?>" data-average="<?php echo $average; ?>" data-text-succes="<?php _e($opt_themes['rating_sukses'], TEXT_DOMAIN); ?>" data-text-error="<?php _e($opt_themes['rating_error'], TEXT_DOMAIN); ?>" data-text-1="<?php _e($opt_themes['rating_title'], TEXT_DOMAIN); ?>" data-text-2="<?php _e($opt_themes['rating_sukses2'], TEXT_DOMAIN); ?>" data-text-3="<?php _e($opt_themes['rating_error2'], TEXT_DOMAIN); ?>" data-timer="2000">
	<?php 
	for ($i = 1; $i <= 5; $i++): 
	$class = $i <= $average ? 'filled' : '';
	?><span class="star <?php echo $class; ?>" data-rating="<?php echo $i; ?>">&#9733;</span><?php endfor; ?>  
	 
	<span class="rating-text"><span class="fbold"><?php echo $average; ?> / 5</span> (<?php echo number_format_i18n( $count ); ?><span id="hilang"> <?php _e($opt_themes['rating_title'], TEXT_DOMAIN); ?></span>)</span> 
	</div>
	
	</div>
 
	 

	<?php 
}


function rating_css() {
if (is_single()) {
?>   

<!-- Center Popup Alert -->
<div id="rating-popup-overlay" class="rating-popup-overlay"></div>
<div id="rating-popup" class="rating-popup">
    <div class="rating-popup-content">
        <span class="rating-popup-close">×</span>
        <h3 class="rating-popup-title"></h3>
        <p class="rating-popup-message"></p>
        <p class="rating-popup-stats"></p> 
    </div>
</div>

<style>
:root {
  --c_modal_bg: hsl(var(--modal-bg)); 
  --c_text: hsl(var(--c-text)); 
  --c_star: silver; 
  --c_star_fill: orangered; 
}

@media (max-width: 499px) {
	#hilang {display:none}
	.rating-text {
	  font-size: 12px;
	  color: #666;
	}
}
 
html.darkmod .rating-text {
	color: var(--putih);
}


@media (max-width: 499px) {.rating-popup {top: 20%!important;}}.rating-stars {font-size: 20px;cursor: pointer;display: inline-block;}.star {color: var(--c_star);transition: color 0.3s;}.star.filled {color: var(--c_star_fill);}.rating-text {font-size: 14px;color: var(--c_text);//#666 }.rating-popup-overlay {display: none;position: fixed;top: 0;left: 0;right: 0;bottom: 0;background: rgba(0,0,0,0.6);z-index: 99998;backdrop-filter: blur(20px);}.rating-popup-overlay.show {display: block;}.rating-popup {position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%) scale(0.7);width: 320px;max-width: 90%;background: var(--c_modal_bg);border-radius: 8px;box-shadow: 0 10px 30px rgba(0,0,0,.3);opacity: 0;visibility: hidden;transition: all .3s ease;z-index: 99999;}.rating-popup.show {transform: translate(-50%, - 50%) scale(1);opacity: 1;visibility: visible;}.rating-popup-content {position: relative;padding: 24px;text-align: center;}.rating-popup-close {position: absolute;top: 8px;right: 12px;font-size: 26px;cursor: pointer;color: var(--c_text);}.rating-popup-close:hover {color: #000;}.rating-popup-title {margin: 0 0 12px;font-size: 20px;}.rating-popup-message {margin: 0 0 12px;font-size: 16px;}.rating-popup-stats {margin: 0 0 18px;font-weight: bold;color: var(--c_text);}.rating-popup-ok {min-width: 80px;}.rating-popup.error .rating-popup-title {color: #d9534f;}.rating-popup.error .rating-popup-stats {display: none;}
</style>


<?php }
}
add_action( 'wp_footer', 'rating_css', 100 );

