<?php  
// === Simple Report Post Feature (No Plugin) ===

define('REPORTPOST', '_post_reports' );

// Enqueue scripts and styles
function report_post_enqueue() {
    if (is_singular('post')) {
        wp_enqueue_style('report-post-css', get_stylesheet_directory_uri() . '/libs/report/report-post.css', array(), '1.0');
        wp_enqueue_script('report-post-js', get_stylesheet_directory_uri() . '/libs/report/report-post.js', array('jquery'), '1.0', true);
        wp_localize_script('report-post-js', 'reportPost', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('report_post_nonce')
        ));
    }
}
add_action('wp_enqueue_scripts', 'report_post_enqueue');

// AJAX handler (logged-in + guests)
function handle_report_post() {
	global $opt_themes;
    check_ajax_referer('report_post_nonce', 'nonce');

    // Honeypot check
    if (!empty($_POST['honeypot'])) {
        wp_die('Spam detected');
    }

    $post_id = intval($_POST['post_id']);
    $reason  = sanitize_text_field($_POST['reason']);
    $message = sanitize_textarea_field($_POST['message']);
    $email   = sanitize_email($_POST['reporter_email']);
    $ip      = $_SERVER['REMOTE_ADDR'];

    if (!$post_id || !$reason) {
        wp_send_json_error('Missing data');
    }

    // Store report in post meta (array of reports)
    $reports = get_post_meta($post_id, REPORTPOST, true);
    if (!is_array($reports)) $reports = array();
    
    $reports[] = array(
        'time'    => current_time('mysql'),
        'reason'  => $reason,
        'message' => $message,
        'email'   => $email,
        'ip'      => $ip
    );
    update_post_meta($post_id, REPORTPOST, $reports);

    // Send email to admin
    $post_title = get_the_title($post_id);
    $post_url   = get_permalink($post_id);
    $admin_email = get_option('admin_email');
    
    $subject = "Post Reported: {$post_title}";
    $body    = "A post has been reported:\n\n";
    $body   .= "Post: {$post_title}\nURL: {$post_url}\n\n";
    $body   .= "Reason: {$reason}\nMessage: {$message}\nReporter Email: {$email}\nIP: {$ip}\n\n";
    $body   .= "Total reports for this post: " . count($reports);
    
    wp_mail($admin_email, $subject, $body);

    wp_send_json_success($opt_themes['rep_text_6']);
}
add_action('wp_ajax_nopriv_report_post', 'handle_report_post');
add_action('wp_ajax_report_post', 'handle_report_post');

// Optional: Add admin column to see report count
function report_column_register($columns) {
    $columns['reports'] = 'Reports';
    return $columns;
}
//add_filter('manage_post_posts_columns', 'report_column_register');

function report_column_display($column, $post_id) {
    if ($column === 'reports') {
        $reports = get_post_meta($post_id, REPORTPOST, true);
        $count = is_array($reports) ? count($reports) : 0;
        echo '<a href="' . get_edit_post_link($post_id) . '#post_reports">' . $count . '</a>';
    }
}
//add_action('manage_post_posts_custom_column', 'report_column_display', 10, 2);


function report_post_admin_scripts($hook) {
    // Run only on post edit screens
    if (!in_array($hook, array('post.php', 'post-new.php'))) return;

    wp_enqueue_script(
        'report-post-admin',
        get_stylesheet_directory_uri() . '/libs/report/report-post-admin.js',
        array('jquery'),
        '1.0',
        true
    );

    wp_localize_script('report-post-admin', 'reportPostAdmin', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('clear_post_reports_nonce')
    ));
}
add_action('admin_enqueue_scripts', 'report_post_admin_scripts');

function ajax_clear_post_reports() {
    check_ajax_referer('clear_post_reports_nonce', 'nonce');

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('Permission denied');
    }

    $post_id = intval($_POST['post_id']);
    if (!$post_id) {
        wp_send_json_error('Invalid post ID');
    }

    // Delete the stored meta
    delete_post_meta($post_id, REPORTPOST );

    wp_send_json_success('All reports cleared');
}
add_action('wp_ajax_clear_post_reports', 'ajax_clear_post_reports');


// Optional: Show reports in post meta box
function report_meta_box() {
    add_meta_box('post_reports', 'Reports Post', 'render_report_meta_box', 'post', 'normal');
}
add_action('add_meta_boxes', 'report_meta_box');
 
function render_report_meta_box($post) {
    $reports = get_post_meta($post->ID, REPORTPOST, true);
    ?>
    <div id="report-meta-box-content">
        <?php if (!is_array($reports) || empty($reports)) : ?>
            <p>No reports yet.</p>
        <?php else : ?>
            <table width="100%" class="wp-list-table widefat fixed striped">
                <thead><tr>
                    <th>Time</th>
					<th>Email</th>
					<th>IP</th>
					<th>Reason</th>
					<th>Message</th>
                </tr></thead>
                <tbody>
                <?php foreach ($reports as $r) : ?>
                    <tr>
                        <td><?php echo esc_html($r['time']); ?></td>
                        <td><?php echo esc_html($r['email']); ?></td>
                        <td><?php echo esc_html($r['ip']); ?></td>
                        <td><?php echo esc_html($r['reason']); ?></td>
                        <td><?php echo esc_html($r['message']); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <p style="margin-top:12px;">
            <button type="button" class="button button-secondary" id="clear-post-reports"
                    data-post-id="<?php echo $post->ID; ?>"
                    <?php disabled( empty($reports) ); ?>>
                Clear All Reports
            </button>
            <span id="clear-reports-msg" style="margin-left:8px; font-weight:bold;"></span>
        </p>
    </div>
    <?php
}


// Add report link to post content
function add_report_link($content) {
	global $opt_themes;
	if(!empty($opt_themes['rep_text_1'])){
    if (is_singular('post') && in_the_loop() && is_main_query()) {
        $post_id = get_the_ID();
        $content .= '<div class="report-post-wrapper">';
        $content .= '<a href="#" class="report-post-link" data-post-id="' . $post_id . '">'.$opt_themes['rep_text_1'].'</a>';
        $content .= '</div>';
    }
    }
    return $content;
}
//add_filter('the_content', 'add_report_link');

// Modal HTML (injected in footer)
function report_modal_html() {
	global $opt_themes;
	if(!empty($opt_themes['rep_text_1'])){
    if (is_singular('post')) {
	?>		
        <div id="report-modal" class="report-modal" style="display:none;">
            <div class="report-modal-content">
                <span class="report-close">&times;</span>
				
                <form id="report-form" class="entery rt-scroll">
				
                    <input type="hidden" name="post_id" id="report-post-id">	
                
					<label><?php _e($opt_themes['rep_text_2'], TEXT_DOMAIN); ?></label>
                    <input type="email" name="reporter_email" class="input rt-10px rt-bold rt-14 rt-333">			
					
                    <label><?php _e($opt_themes['rep_text_3'], TEXT_DOMAIN); ?></label>
                    <select name="reason" required class="input rt-10px rt-bold rt-14 rt-333"> 
					<?php
					foreach ( (array) $opt_themes['reasons'] as $key => $val ) { 
					?>
					<option value="<?php echo $val; ?>"><?php echo $val; ?></option>
					<?php } ?>		 
                    </select>	
					
					<?php if(!empty($opt_themes['rep_text_4'])){?>
                    <label><?php _e($opt_themes['rep_text_4'], TEXT_DOMAIN); ?></label>
                    <textarea name="message" rows="4" class="input rt-10px rt-bold rt-14 rt-333"></textarea>   
					<?php } ?>	
					
                    <p id="report-message"></p>
                    <input type="text" name="honeypot" style="display:none;">
                    <button type="submit" style="width: 100%; margin: 1rem 0; padding: 1rem 0; background-color: var(--color_button); color: var(--putih); border: medium; border-radius: 25px; font-size: 16px; display: flex; align-items: center; justify-content: center; "><?php _e($opt_themes['rep_text_5'], TEXT_DOMAIN); ?></button>
                </form>
            </div>
        </div>

        <?php
    }
    }
}
add_action('wp_footer', 'report_modal_html');



function get_total_post_reports( $post_id = 0 ) {
    $post_id = $post_id ?: get_the_ID();
    if ( ! $post_id ) return 0;
    
	$reports = get_post_meta($post_id, REPORTPOST, true);
	$total = is_array($reports) ? count($reports) : 0;
		
    // Ganti salah satu sesuai key yang kamu pakai
    //$total = (int) get_post_meta( $post_id, REPORTPOST, true );   // versi lama
    // $total = (int) get_post_meta( $post_id, REPORTPOST, true ); // jika kamu ganti

    return $total ? : 0;
}
 
function total_all_report() {
     $args = array(
        'post_type' => 'post',
        'meta_query' => array(
            array(
                'key' => REPORTPOST,
                'value' => 0,
                'compare' => '>'
            )
        )
    );

    $query = new WP_Query( $args );
    
    return $query->found_posts;
}

add_action('admin_bar_menu', function($wp_admin_bar) {
    if (!current_user_can('manage_options')) return;
    
    $total = (new WP_Query([
        'post_type'  => 'post',
        'meta_query' => [['key' => REPORTPOST, 'value' => '0', 'compare' => '>']],
        'fields'     => 'ids',
    ]))->found_posts;

    $wp_admin_bar->add_node([
        'id'    => 'total-reported-posts',
        'title' => '<span class="ab-icon dashicons-megaphone"></span> Report : ' . $total,
        'href'  => admin_url('admin.php?page=reports-post'),
    ]);
}, 99999);


// Tambah menu di admin
function menu_laporan_post() {
    global $wpdb; 
    add_menu_page(
        'Post Report',
        'Report <span class="update-plugins count-'.total_all_report().'"><span class="plugin-count">'.total_all_report().'</span></span>',
        'manage_options',
        'reports-post',
        'halaman_laporan_post',
        'dashicons-megaphone',
        999
    );
}
add_action('admin_menu', 'menu_laporan_post');

function halaman_laporan_post() {
	global $post;
    echo '<div class="wrap">
	<h1>Reported Posts ('.total_all_report().') </h1>
	<table class="wp-list-table widefat fixed striped">';
    echo '
	<thead>
	<tr>
	<th>ID</th>
	<th>Title</th>
	<th>Total Report</th>
	<th>Link</th>
	</tr>
	</thead>
	<tbody>';

    $args = array(
        'post_type' => 'post',
        'meta_query' => array(
            array(
                'key' => REPORTPOST,
                'value' => 0,
                'compare' => '>'
            )
        )
    );
	
    $query = new WP_Query($args);
    while ($query->have_posts()) : $query->the_post(); 
		
		$reports = get_total_post_reports();
		 
        echo '<tr>';
        echo '<td>' . get_the_ID() . '</td>';
        echo '<td>' . get_the_title() . '</td>';
        echo '<td>' . $reports . '</td>';
        echo '<td><a href="' . get_edit_post_link(get_the_ID()) . '" target="_blank">view</a></td>';
        echo '</tr>';
    endwhile;
    wp_reset_postdata();
    echo '</tbody></table></div>';
}

add_action('wp_dashboard_setup', 'add_reported_posts_dashboard_widget');

function add_reported_posts_dashboard_widget() {
    // Only show to users who can edit others' posts (editor/admin)
    if (!current_user_can('edit_others_posts')) {
        return;
    }

    wp_add_dashboard_widget(
        'reported_posts_widget',
        __('Posts Reports', TEXT_DOMAIN),
        'render_reported_posts_widget',
		null,	// control callback (optional)
		null,	// args (optional)
		'side',	// ← context: 'side' instead of default 'normal'
		'core'	// ← priority: 'core', 'high', 'low'
    );
}

function render_reported_posts_widget() {
    // Query posts that have at least one report
    $args = [
        'post_type'      => 'post',	// change to your CPT if needed (or use array for multiple)
        'post_status'    => 'any',
        'posts_per_page' => 15,
        'meta_query'     => [
            [
                'key'     => REPORTPOST,
                'value'   => 'a:',	// crude but fast way to find non-empty serialized arrays
                'compare' => 'LIKE',
            ],
        ], 
        'meta_key'       => REPORTPOST, 
		'order'	=> 'desc' 
    ];

    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        echo '<p>' . esc_html__('No reported posts at the moment.', TEXT_DOMAIN) . '</p>';
        return;
    }
    ?>
<div class="reported-posts-table-wrapper">
    <table class="widefat striped">
        <thead>
            <tr>
                <th><?php _e('Post', TEXT_DOMAIN); ?></th>
                <th style="width:80px;text-align:center;"><?php _e('Reports', TEXT_DOMAIN); ?></th>
                <th style="width:120px;"><?php _e('Latest report', TEXT_DOMAIN); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php
            while ($query->have_posts()) {
                $query->the_post();
                $post_id  = get_the_ID();
                $reports  = get_post_meta($post_id, REPORTPOST, true);
                $count    = is_array($reports) ? count($reports) : 0;

                // Get timestamp of the most recent report (assuming reports are stored with timestamp keys or as array of arrays)
                   
				if ($count > 0) {
					$latest_time = 0;
					foreach ($reports as $report) {
						$latest_time = $report['time']; 
					}
				}
				
				//$reports = get_post_meta($post->ID, REPORTPOST, true);
                //foreach ($reports as $r) : 
				//$latesttimes = $r['time']; 
				//endforeach;
                ?>
                <tr>
                    <td>
                        <strong><?php echo esc_html(get_the_title()); ?></strong>
                        <div class="row-actions">
                            <a href="<?php echo esc_url(get_edit_post_link($post_id) . '#post_reports'); ?>" target="_blank"><?php _e('View', TEXT_DOMAIN); ?></a>
							<!--|
                            <a href="<?php echo esc_url(get_permalink($post_id)); ?>" target="_blank"><?php _e('View', TEXT_DOMAIN); ?></a>
							-->
                        </div>
                    </td>
                    <td style="text-align:center;font-weight:700;color:crimson;font-size: 15px;">
                        <?php echo (int)$count; ?>
                    </td>
                    <td><?php echo date("M d, Y", strtotime($latest_time)); ?></td>
                </tr>
                <?php
            }
            wp_reset_postdata();
            ?>
        </tbody>
    </table>
</div>

    <p class="textright">
        <a href="<?php echo esc_url(admin_url('admin.php?page=reports-post')); ?>">
            <?php _e('All posts →', TEXT_DOMAIN); ?>
        </a>
    </p>
<style>
.reported-posts-table-wrapper {max-height: 250px;overflow-y: auto;border: 1px solid #c3c4c7;box-shadow: 0 1px 1px rgba(0,0,0,.04);background: #fff;}.reported-posts-table-wrapper table {margin: 0 !important;width: 100%;}.reported-posts-table-wrapper thead th {position: sticky;top: 0;background: #f1f1f1;z-index: 10;box-shadow: 0 1px 0 #c3c4c7;}
</style>
	
    <?php
}
