<?php
function enqueue_rating_scripts() {
    if (is_single()) { 
        wp_enqueue_script('jquery');
        wp_localize_script('jquery', 'ajax_object', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('rating_nonce')
        ));
		//wp_enqueue_script( THEMES_NAMES_ALT.'-jquery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js', array('jquery'), null, false);
		wp_enqueue_script('rating-js', get_template_directory_uri() . '/libs/rating/rating.js', array('jquery'), '1.0', true);
    }
}
add_action('wp_enqueue_scripts', 'enqueue_rating_scripts');
 
function display_post_rating($post_id) {
	global $opt_themes;
    $total 		= get_post_meta( $post_id, '_post_rating_total', true); 
    $count 		= get_post_meta( $post_id, '_post_rating_count', true) > 0 ? get_post_meta( $post_id, '_post_rating_count', true) : 0;
    $average 	= $count > 0 ? round($total / $count, 1) : 0;
	if($opt_themes['rating_on']){
    ?>
	  
	
	<div class="post-rating" data-post-id="<?php echo $post_id; ?>" 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); ?>">
	<div class="rating-stars" data-average="<?php echo $average; ?>">
	<?php for ($i = 1; $i <= 5; $i++): ?>
		<span class="star" data-rating="<?php echo $i; ?>">★</span>
	<?php endfor; ?> 
	</div>
	<span class="rating-average "><?php echo $average; ?>/5 ( <?php echo $count; ?> <?php _e($opt_themes['rating_title'], TEXT_DOMAIN); ?> )</span>	 
	</div>
	 
	
	<style>
		.rating-stars { cursor: pointer; font-size: 20px; color: #ddd; }
		.rating-stars .star:hover, .rating-stars .star.active { color: #ffd700; }
		.rating-message { margin-top: 10px; font-weight: bold; }
	</style>	
    <?php
	}
}


function rating_slide_alert_footer_code() {
?>  
<!-- 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>

/* ---- Center Popup Alert ---- */
.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;
}
.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: hsl(var(--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;
}

/* Content */
.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: #aaa;
}
.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: #28a745; 
}
.rating-popup-ok {
    min-width: 80px;
}

/* Error style */
.rating-popup.error .rating-popup-title { color: #d9534f; }
.rating-popup.error .rating-popup-stats { display: none; }
</style>


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

function handle_post_rating() {
	global $opt_themes;
    // Verify nonce
    //if (!wp_verify_nonce($_POST['nonce'], 'rating_nonce')) {
    //    wp_die('Security check failed');
    //}

    $post_id = intval($_POST['post_id']);
    $rating = intval($_POST['rating']);
    $ip = $_SERVER['REMOTE_ADDR'];
    $transient_key = 'voted_' . md5($ip . $post_id);

    // Check if user already voted (simple IP-based, expires in 24 hours)
    //if (get_transient($transient_key)) {
    //   wp_send_json_error($opt_themes['rating_error_1']);
    //}

    // Get current meta
    $total = (float) get_post_meta($post_id, '_post_rating_total', true) ?: 0;
    $count = (int) get_post_meta($post_id, '_post_rating_count', true) ?: 0;

    // Update meta
    $total += $rating;
    $count++;
    update_post_meta($post_id, '_post_rating_total', $total);
    update_post_meta($post_id, '_post_rating_count', $count);

    // Mark as voted
    //set_transient($transient_key, true, 24 * HOUR_IN_SECONDS);

    // Calculate new average
    $average = round($total / $count, 1);

    wp_send_json_success(array(
        'average' => $average,
        'count' => $count,
        'message' => $opt_themes['rating_error_2']
    ));
}

// For logged-in users
add_action('wp_ajax_submit_rating', 'handle_post_rating');
// For logged-out users
add_action('wp_ajax_nopriv_submit_rating', 'handle_post_rating');


// 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, '_post_rating_total', true));
    $vote_count   = intval(get_post_meta($post_id, '_post_rating_count', 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, '_post_rating_total', $total);
    } else {
        delete_post_meta($post_id, '_post_rating_total');
    }

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




/* ------------------------------------------------------------------
   1. REGISTER META-BOX
------------------------------------------------------------------ */
function rating_add_meta_box() {
    add_meta_box(
        'post_rating_meta',          // id
        __('Post Rating', 'textdomain'), // title
        'rating_meta_box_callback',  // callback
        'post',                      // screen (post type)
        'side',                      // context
        'low'                       // priority
    );
}
//add_action('add_meta_boxes', 'rating_add_meta_box');

/* ------------------------------------------------------------------
   2. META-BOX CONTENT
------------------------------------------------------------------ */
function rating_meta_box_callback($post) {
	global $opt_themes;
    $total = (float) get_post_meta($post->ID, '_post_rating_total', true);
    $count = (int)   get_post_meta($post->ID, '_post_rating_count', true);
    $average = $count ? round($total / $count, 1) : 0;

    // Nonce for reset action
    wp_nonce_field('rating_reset_nonce', 'rating_reset_nonce');
	
    ?>
    <div class="rating-meta-box"> 
	<?php if(!$opt_themes['rating_on']){ ?>
	<p>Please Enable <b>Rating by User<b> on Panel Thems to show the result </p>
	<?php } ?>
        <p>
            <strong><?php _e('Average rating:', 'textdomain'); ?></strong>
            <span class="rating-average"><?php echo $average; ?>/5</span>
        </p>
        <p>
            <strong><?php _e('Total votes:', 'textdomain'); ?></strong>
            <span class="rating-count"><?php echo $count; ?></span>
        </p>

        <!-- Star display (same as front-end) -->
        <div class="rating-stars-display" data-average="<?php echo $average; ?>">
            <?php for ($i = 1; $i <= 5; $i++): ?>
                <span class="star <?php echo $i <= $average ? 'active' : ''; ?>">★</span>
            <?php endfor; ?>
        </div>

        <?php if ($count > 0): ?>
            <p style="margin-top:12px;">
                <input type="submit"
                       name="reset_post_rating"
                       class="button button-secondary"
                       value="<?php _e('Reset rating', 'textdomain'); ?>"
                       onclick="return confirm('<?php _e('Are you sure you want to delete all ratings for this post?', 'textdomain'); ?>');">
            </p>
        <?php endif; ?>
    </div>
	<style>
	.rating-meta-box .rating-stars-display { font-size: 20px; }
	.rating-meta-box .rating-stars-display .star { color: #ddd; }
	.rating-meta-box .rating-stars-display .star.active { color: #ffd700; }
	</style>
    <?php
}

/* ------------------------------------------------------------------
   3. HANDLE RESET BUTTON (save_post)
------------------------------------------------------------------ */
function rating_handle_reset($post_id, $post) {
    // Bail if autosave, no permission, or nonce missing
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;
    if (!isset($_POST['rating_reset_nonce']) ||
        !wp_verify_nonce($_POST['rating_reset_nonce'], 'rating_reset_nonce')) {
        return;
    }

    if (isset($_POST['reset_post_rating'])) {
        delete_post_meta($post_id, '_post_rating_total');
        delete_post_meta($post_id, '_post_rating_count');

        // Optional: clear all vote transients for this post
        global $wpdb;
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM $wpdb->options WHERE option_name LIKE %s",
                '_transient_voted_%' . md5('%' . $post_id)
            )
        );
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM $wpdb->options WHERE option_name LIKE %s",
                '_transient_timeout_voted_%' . md5('%' . $post_id)
            )
        );
    }
}
add_action('save_post', 'rating_handle_reset', 10, 2);

function rating_admin_styles() {
    wp_enqueue_style(
        'rating-admin',
        get_stylesheet_directory_uri() . '/assets/css/admin-rating.css',
        array(),
        '1.0'
    );
}
//add_action('admin_enqueue_scripts', 'rating_admin_styles');

/* 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, '_post_rating_total', true);
    $count = (int)   get_post_meta($post_id, '_post_rating_count', true);
    $average = $count ? round($total / $count, 1) : 0;

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