<?php
/**
 * MTC — Location Map
 *
 * Display rated locations on an interactive map (Leaflet.js)
 *
 * @package My Trail Camera
 * @since 8.2.0
 */

if (!defined('ABSPATH')) exit;

// Process delete
if (isset($_POST['mtcam_delete_review']) && isset($_POST['review_id'])) {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Insufficient permissions.', 'my-trail-camera' ), '', 403 );
    }
    $mtcam_del_review_id = intval( wp_unslash( $_POST['review_id'] ) );
    check_admin_referer('mtcam_delete_review_' . $mtcam_del_review_id);
    mtcam_location_review_delete($mtcam_del_review_id);
    wp_safe_redirect( wp_nonce_url( admin_url('admin.php?page=mtcam-locations&deleted=1'), 'mtcam_settings_notice' ) );
    exit;
}

$mtcam_reviews = mtcam_location_reviews_get_all();
$mtcam_stats = mtcam_location_reviews_stats();

// Filter reviews with GPS only (for map) — technical issues are shown but styled differently
$mtcam_map_reviews = array_filter($mtcam_reviews, function($r) {
    return !empty($r['gps_lat']) && !empty($r['gps_lon']);
});
?>
<main class="wrap mtcam-wrap">
    <h1>🗺️ <?php esc_html_e( 'Location Map', 'my-trail-camera' ); ?></h1>
    
    <?php
    $mtcam_loc_nonce_valid = isset($_GET['_wpnonce']) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_settings_notice' );
    ?>
    <?php if ($mtcam_loc_nonce_valid && isset($_GET['saved'])): ?>
    <div class="notice notice-success is-dismissible" role="alert"><p>✅ <?php esc_html_e( 'Location review has been saved.', 'my-trail-camera' ); ?></p></div>
    <?php endif; ?>
    <?php if ($mtcam_loc_nonce_valid && isset($_GET['deleted'])): ?>
    <div class="notice notice-success is-dismissible" role="alert"><p><?php esc_html_e( 'Review has been deleted.', 'my-trail-camera' ); ?></p></div>
    <?php endif; ?>
    <?php if ($mtcam_loc_nonce_valid && isset($_GET['updated'])): ?>
    <div class="notice notice-success is-dismissible" role="alert"><p>✅ <?php esc_html_e( 'Review has been updated.', 'my-trail-camera' ); ?></p></div>
    <?php endif; ?>
    
    <?php if (empty($mtcam_reviews)): ?>
    <div class="mtcam-page-card">
        <p><?php esc_html_e( 'No location reviews yet.', 'my-trail-camera' ); ?></p>
        <p><?php echo wp_kses(
            sprintf(
                /* translators: %s: "End Monitoring" button label */
                __( 'Site reviews help you rate and compare locations where trail cameras have been placed based on wildlife activity, footage quality, and human disturbance. Once you\'ve finished monitoring a location, use the %s button in the camera details to create a review with statistics and scores.', 'my-trail-camera' ),
                '<strong>📊 ' . esc_html__( 'End Monitoring', 'my-trail-camera' ) . '</strong>'
            ),
            array( 'strong' => array() )
        ); ?></p>
    </div>
    <?php return; endif; ?>
    
    <!-- Stats bar -->
    <?php $mtcam_tech_count = intval( $mtcam_stats['technical'] ?? 0 ); ?>
    <div class="mtcam-location-stats">
        <div class="mtcam-location-stat">
            <span class="mtcam-stat-number">
                <?php echo intval($mtcam_stats['total']); ?>
                <?php if ( $mtcam_tech_count > 0 ) : ?>
                    <span class="mtcam-stat-excluded" title="<?php esc_attr_e( 'Reviews flagged as technical issue — excluded from score averages and chart', 'my-trail-camera' ); ?>">
                        ⚠️ <?php echo intval( $mtcam_tech_count ); ?>
                    </span>
                <?php endif; ?>
            </span>
            <span class="mtcam-stat-label">
                <?php esc_html_e( 'Reviews', 'my-trail-camera' ); ?>
                <?php if ( $mtcam_tech_count > 0 ) : ?>
                    <small class="mtcam-text-muted">
                        (<?php
                            printf(
                                /* translators: %d: number of reviews excluded from stats due to technical issues */
                                esc_html( _n( '%d excluded', '%d excluded', $mtcam_tech_count, 'my-trail-camera' ) ),
                                intval( $mtcam_tech_count )
                            );
                        ?>)
                    </small>
                <?php endif; ?>
            </span>
        </div>
        <div class="mtcam-location-stat">
            <span class="mtcam-stat-number"><?php echo esc_html( round( $mtcam_stats['avg_score'] ?? 0, 1 ) ); ?></span>
            <span class="mtcam-stat-label"><?php esc_html_e( 'Avg. Score', 'my-trail-camera' ); ?></span>
        </div>
        <div class="mtcam-location-stat">
            <span class="mtcam-stat-number"><?php echo intval($mtcam_stats['total_days']); ?></span>
            <span class="mtcam-stat-label"><?php esc_html_e( 'Total Days', 'my-trail-camera' ); ?></span>
        </div>
        <div class="mtcam-location-stat">
            <span class="mtcam-stat-number"><?php echo intval($mtcam_stats['total_videos']); ?></span>
            <span class="mtcam-stat-label"><?php esc_html_e( 'Total Videos', 'my-trail-camera' ); ?></span>
        </div>
    </div>
    
    <!-- Map -->
    <?php if (!empty($mtcam_map_reviews)): ?>
    <div class="mtcam-page-card">
        <div id="mtcam-locations-map" style="height:500px; border-radius: var(--mtcam-radius);"></div>
    </div>
    
    <?php
    $mtcam_map_data = array_values( array_map( function( $r ) {
        $weather_line = '';
        $is_tech = 0;
        return array(
            'lat' => floatval( $r['gps_lat'] ),
            'lon' => floatval( $r['gps_lon'] ),
            'name' => $r['location_name'],
            'cam' => $r['cam_id'],
            'days' => intval( $r['days_count'] ),
            'videos' => intval( $r['total_videos'] ),
            'interesting' => intval( $r['interesting_videos'] ),
            'people' => intval( $r['people_count'] ),
            'satisfaction' => intval( $r['satisfaction'] ),
            'score' => floatval( $r['score'] ),
            'rating' => $r['rating'],
            'date' => $r['end_date'],
            'color' => $is_tech ? '#9e9e9e' : mtcam_location_rating_color( $r['rating'] ),
            'emoji' => $is_tech ? '⚠️' : mtcam_location_rating_emoji( $r['rating'] ),
            'label' => $is_tech ? __( 'Technical issue', 'my-trail-camera' ) : mtcam_location_rating_label( $r['rating'] ),
            'weather' => $weather_line,
            'tech' => $is_tech,
        );
    }, $mtcam_map_reviews ) );

    $mtcam_map_i18n = array(
        'score'    => __( 'Score: ', 'my-trail-camera' ),
        'camera'   => __( 'Camera: ', 'my-trail-camera' ),
        'days'     => __( 'days in field', 'my-trail-camera' ),
        'videos'   => __( 'videos (', 'my-trail-camera' ),
        'notable'  => __( 'notable)', 'my-trail-camera' ),
        'people'   => __( 'people passages', 'my-trail-camera' ),
        'ended'    => __( 'Ended: ', 'my-trail-camera' ),
    );

    $mtcam_map_js = 'document.addEventListener("DOMContentLoaded", function() {'
        . 'var reviews = ' . wp_json_encode( $mtcam_map_data ) . ';'
        . 'var i18n = ' . wp_json_encode( $mtcam_map_i18n ) . ';'
        . 'if (!reviews.length) return;'
        . 'var map = L.map("mtcam-locations-map").setView([reviews[0].lat, reviews[0].lon], 10);'
        . 'L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {'
        . '  attribution: "© OpenStreetMap", maxZoom: 18'
        . '}).addTo(map);'
        . 'var bounds = [];'
        . 'reviews.forEach(function(r) {'
        . '  var stars = "\u2b50".repeat(r.satisfaction) + "\u2606".repeat(5 - r.satisfaction);'
        . '  var marker = L.circleMarker([r.lat, r.lon], {'
        . '    radius: 10, fillColor: r.color, color: "#fff", weight: 2, opacity: 1,'
        . '    fillOpacity: r.tech ? 0.5 : 0.85, dashArray: r.tech ? "3,3" : null'
        . '  }).addTo(map);'
        . '  marker.bindPopup('
        . '    "<div style=\"min-width:220px;\">"'
        . '    + "<strong style=\"font-size:14px;\">" + r.emoji + " " + r.name + "</strong><br>"'
        . '    + (r.tech'
        . '      ? "<span style=\"color:#9e9e9e; font-weight:bold;\">" + r.label + "</span><br>"'
        . '      : "<span style=\"color:" + r.color + "; font-weight:bold;\">" + i18n.score + r.score + "/100 (" + r.label + ")</span><br>")'
        . '    + "<hr style=\"margin:6px 0; border-color:#eee;\">"'
        . '    + "\ud83d\udcf7 " + i18n.camera + "<strong>" + r.cam + "</strong><br>"'
        . '    + "\ud83d\udcc5 " + r.days + " " + i18n.days + "<br>"'
        . '    + "\ud83c\udfac " + r.videos + " " + i18n.videos + r.interesting + " " + i18n.notable + "<br>"'
        . '    + "\ud83d\udc64 " + r.people + " " + i18n.people + "<br>"'
        . '    + (r.weather ? "\ud83c\udf24\ufe0f " + r.weather + "<br>" : "")'
        . '    + stars + "<br>"'
        . '    + "<small style=\"color:#999;\">" + i18n.ended + r.date + "</small>"'
        . '    + "</div>"'
        . '  );'
        . '  bounds.push([r.lat, r.lon]);'
        . '});'
        . 'if (bounds.length > 1) { map.fitBounds(bounds, {padding: [30, 30]}); }'
        . '});';

    wp_add_inline_script( 'leaflet', $mtcam_map_js );
    ?>
    <?php endif; ?>
    
    <!-- Score comparison bars -->
    <section class="mtcam-page-card" style="margin-top:20px;">
        <h2>📊 <?php esc_html_e( 'Score Comparison', 'my-trail-camera' ); ?></h2>
        <?php foreach ( $mtcam_reviews as $mtcam_bar_r ) :
            $mtcam_bar_score = floatval( $mtcam_bar_r['score'] );
            $mtcam_bar_color = mtcam_location_rating_color( $mtcam_bar_r['rating'] );
            $mtcam_bar_emoji = mtcam_location_rating_emoji( $mtcam_bar_r['rating'] );
        ?>
        <div class="mtcam-score-bar-row">
            <span class="mtcam-score-bar-label"><?php echo esc_html( $mtcam_bar_emoji . ' ' . $mtcam_bar_r['location_name'] ); ?></span>
            <div class="mtcam-score-bar-track">
                <div class="mtcam-score-bar-fill" style="width:<?php echo esc_attr( $mtcam_bar_score ); ?>%; background:<?php echo esc_attr( $mtcam_bar_color ); ?>;"></div>
            </div>
            <span class="mtcam-score-bar-value" style="color:<?php echo esc_attr( $mtcam_bar_color ); ?>;"><?php echo esc_html( $mtcam_bar_score ); ?></span>
        </div>
        <?php endforeach; ?>
    </section>

    <!-- Reviews table -->
    <section class="mtcam-page-card" style="margin-top:20px;">
        <h2>📋 <?php esc_html_e( 'All Reviews', 'my-trail-camera' ); ?></h2>
        <table class="widefat striped">
            <?php mtcam_table_caption( __( 'Location reviews', 'my-trail-camera' ) ); ?>
            <thead>
                <tr>
                    <th><?php esc_html_e( 'Location', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'Camera', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'Days', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'Videos', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'Vid/day', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'Notable %', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'People/day', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'Satisfaction', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'Score', 'my-trail-camera' ); ?></th>
                    <th><?php esc_html_e( 'Rating', 'my-trail-camera' ); ?></th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($mtcam_reviews as $mtcam_r):
                    $mtcam_color = mtcam_location_rating_color($mtcam_r['rating']);
                    $mtcam_emoji = mtcam_location_rating_emoji($mtcam_r['rating']);
                    $mtcam_tech = false;
                ?>
                <tr<?php if ( $mtcam_tech ) echo ' style="opacity:0.55;"'; ?>>
                    <td>
                        <strong><?php echo esc_html($mtcam_r['location_name']); ?></strong>
                    </td>
                    <td><code><?php echo esc_html($mtcam_r['cam_id']); ?></code></td>
                    <td><?php echo intval($mtcam_r['days_count']); ?><br><small class="mtcam-text-muted"><?php mtcam_echo_date_html( $mtcam_r['start_date'], 'j.m.' ); ?> – <?php mtcam_echo_date_html( $mtcam_r['end_date'], 'j.m.Y' ); ?></small></td>
                    <td><?php echo intval($mtcam_r['total_videos']); ?></td>
                    <td><?php echo esc_html( $mtcam_r['days_count'] > 0 ? round( $mtcam_r['total_videos'] / $mtcam_r['days_count'], 1 ) : 0 ); ?></td>
                    <td><?php echo esc_html( $mtcam_r['total_videos'] > 0 ? round( $mtcam_r['interesting_videos'] / $mtcam_r['total_videos'] * 100 ) . '%' : '0%' ); ?></td>
                    <td><?php echo esc_html( $mtcam_r['days_count'] > 0 ? round( $mtcam_r['people_count'] / $mtcam_r['days_count'], 1 ) : 0 ); ?></td>
					<td><?php echo esc_html( str_repeat( '⭐', intval( $mtcam_r['satisfaction'] ) ) ); ?></td>
                    <td><strong style="color: <?php echo esc_attr( $mtcam_color ); ?>;"><?php echo esc_html( floatval( $mtcam_r['score'] ) ); ?></strong></td>
                    <td>
						<span style="color: <?php echo esc_attr( $mtcam_color ); ?>;">
							<?php echo esc_html( $mtcam_emoji ); ?>
							<?php echo esc_html( $mtcam_r['rating'] ); ?>
						</span>
					</td>
                    <td style="white-space:nowrap;">
                        <form method="post" style="display:inline;" data-mtcam-confirm="<?php esc_attr_e( 'Are you sure you want to delete this review?', 'my-trail-camera' ); ?>">
                            <?php wp_nonce_field('mtcam_delete_review_' . $mtcam_r['id']); ?>
                            <input type="hidden" name="review_id" value="<?php echo intval($mtcam_r['id']); ?>">
                            <button type="submit" name="mtcam_delete_review" class="button button-small" aria-label="<?php esc_attr_e( 'Delete review', 'my-trail-camera' ); ?>">✕</button>
                        </form>
                    </td>
                </tr>
                <?php if (!empty($mtcam_r['notes'])): ?>
                <tr<?php if ( $mtcam_tech ) echo ' style="opacity:0.55;"'; ?>>
                    <td colspan="11"><small class="mtcam-text-muted">📝 <?php echo esc_html($mtcam_r['notes']); ?></small></td>
                </tr>
                <?php endif; ?>

                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>
