<?php
// Enqueue jQuery and custom script, localize AJAX vars
function enqueue_rating_script() {
    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');

// 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_votes = get_post_meta($post_id, 'rating_total_votes', true) ?: 0;
    $total_rating = get_post_meta($post_id, 'rating_total_value', true) ?: 0;
    $average = $total_votes > 0 ? round($total_rating / $total_votes, 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-1="<?php _e($opt_themes['rating_title'], TEXT_DOMAIN); ?>">
	<?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 $total_votes; ?> <span id="hilang"><?php _e($opt_themes['rating_title'], TEXT_DOMAIN); ?></span>)</span>
	</div>
	
	</div>

	<?php
    //echo '<div class="rating-stars" data-post-id="' . $post_id . '" data-average="' . $average . '">';
    //for ($i = 1; $i <= 5; $i++) {
    //    $class = $i <= $average ? 'filled' : '';
    //    echo '<span class="star ' . $class . '" data-rating="' . $i . '">&#9733;</span>'; // Unicode star
    //}
    //echo '<span class="rating-text">(' . $total_votes . ' votes, avg: ' . $average . ')</span>';
    //echo '</div>';
}


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

.rating-stars {
	font-size: 1.4rem;
	cursor: pointer;
	display: inline-block;
	margin-left: -3px;
}

.star {
	color: #ddd;
	transition: color 0.3s;
}

.star.filled {
	color: var(--color_svg);
}

.rating-text {
	font-size: 15px; 
	color: #666;
}

#rating-alert {
	position: fixed;
	bottom: 20px;
	left: 50%;
	transform: translateX(-50%);
	background: #333;
	color: white;
	padding: 12px 24px;
	border-radius: 6px;
	font-size: 15px;
	font-weight: 500;
	z-index: 99999;
	box-shadow: 0 4px 12px rgba(0,0,0,0.3);
	display: none;
	min-width: 200px;
	text-align: center;
}

#rating-alert.success {
	background: #28a745;
}

#rating-alert.error {
	background: #dc3545;
}

#rating-alert.show {
	animation: fadeInDown 0.4s;
}

@keyframes fadeInDown {
	from {
		opacity: 0;
		transform: translateX(-50%) translateY(-20px);
	}

	to {
		opacity: 1;
		transform: translateX(-50%) translateY(0);
	}
}
</style>


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


// AJAX handler for rating submission (logged-in users)
function handle_post_rating() {
    check_ajax_referer('rating_nonce', 'nonce');
    $post_id = intval($_POST['post_id']);
    $rating = intval($_POST['rating']);
    $ip = $_SERVER['REMOTE_ADDR'];
    
    // 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_votes = get_post_meta($post_id, 'rating_total_votes', true) ?: 0;
    $total_rating = get_post_meta($post_id, 'rating_total_value', true) ?: 0;
    $total_votes++;
    $total_rating += $rating;
    update_post_meta($post_id, 'rating_total_votes', $total_votes);
    update_post_meta($post_id, 'rating_total_value', $total_rating);
    //$voted_ips[] = $ip;
    //update_post_meta($post_id, 'rating_voted_ips', $voted_ips);
    
    $average = round($total_rating / $total_votes, 1);
    wp_send_json_success(array('average' => $average, 'votes' => $total_votes));
}

// 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',
        'low'
    );
}
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_rating = floatval(get_post_meta($post_id, 'rating_total_value', true));
    $vote_count   = intval(get_post_meta($post_id, 'rating_total_votes', true));
    $average      = $vote_count > 0 ? round($total_rating / $vote_count, 2) : 0;

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

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

    <div class="rating-manual-inputs">
        <label>Average Rating (1–5)</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 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_rating); ?>" style="display:none">


        <label>Number of Votes</label>
        <input type="number" min="0" 
               name="manual_count" value="<?php echo esc_attr($vote_count); ?>">

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

        <div class="rating-current">
            <strong>Current displayed rating:</strong><br>
            <?php echo $average; ?>/5 from <?php echo $vote_count; ?> vote(s)
            <div style="margin-top:8px;">
                <?php for($i=1;$i<=5;$i++): ?>
                    <span style="font-size:2.2em;color:<?php echo $i<=$average?'#f5c242':'#ddd'; ?>">★</span>
                <?php endfor; ?>
            </div>
        </div>
    </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_total_value', $total);
    } else {
        delete_post_meta($post_id, 'rating_total_value');
    }

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

