<?php
if (!defined('ABSPATH')) exit;

$mtcam_show_deleted_notice = isset( $_GET['deleted'], $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_logs_notice' );
$mtcam_show_reset_notice   = isset( $_GET['reset'], $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_logs_notice' );

$mtcam_current_filter = 'all';
if ( isset( $_GET['_filter_nonce'], $_GET['filter'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_filter_nonce'] ) ), 'mtcam_logs_filter' ) ) {
    $mtcam_current_filter = sanitize_text_field( wp_unslash( $_GET['filter'] ) );
}
?>
<div class="wrap mtcam-wrap">
    <?php if ($mtcam_show_deleted_notice): ?>
        <div class="notice notice-success is-dismissible" role="alert"><p><?php esc_html_e('Record deleted.', 'my-trail-camera'); ?></p></div>
    <?php endif; ?>
    <?php if ($mtcam_show_reset_notice): ?>
        <div class="notice notice-success is-dismissible" role="alert"><p><strong><?php echo '✓ '; esc_html_e('All records deleted! Numbering reset to 1.', 'my-trail-camera'); ?></strong></p></div>
    <?php endif; ?>
    <div class="mtcam-flex-between">
        <h1><span class="dashicons dashicons-shield-alt mtcam-icon-lg" aria-hidden="true"></span> <?php esc_html_e('MTC Detection Records', 'my-trail-camera'); ?></h1>

        <?php if (!empty($logs)): ?>
        <form method="post" style="display:inline;" data-mtcam-confirm="<?php echo esc_attr(__("WARNING!\n\nYou will delete ALL records and reset numbering to 1.\n\nAre you sure?", 'my-trail-camera')); ?>">
            <?php wp_nonce_field('reset_all_logs'); ?>
            <input type="hidden" name="action" value="reset_all">
            <button type="submit" class="button button-secondary mtcam-btn-danger"><?php echo '🗑️ '; esc_html_e('Delete All Records', 'my-trail-camera'); ?></button>
        </form>
        <?php endif; ?>
    </div>

    <!-- FILTER BY OWNERSHIP -->
    <div class="mtcam-filter-bar">
        <form method="get" action="" class="mtcam-flex-gap-15">
            <input type="hidden" name="page" value="mtcam-logs">
            <?php wp_nonce_field( 'mtcam_logs_filter', '_filter_nonce', false ); ?>

            <label for="camera_filter" class="mtcam-filter-label">
                <?php echo '📂 '; esc_html_e('Camera Filter:', 'my-trail-camera'); ?>
            </label>

            <select name="filter" id="camera_filter" data-mtcam-autosubmit
                    class="mtcam-filter-select">
                <option value="all" <?php selected($mtcam_current_filter, 'all'); ?>>
                    <?php echo '📋 '; esc_html_e('All Cameras', 'my-trail-camera'); ?>
                </option>
                <option value="my" <?php selected($mtcam_current_filter, 'my'); ?>>
                    <?php echo '📷 '; esc_html_e('My Cameras Only', 'my-trail-camera'); ?>
                </option>
            </select>

            <?php
            // Apply filter
            $mtcam_filter = sanitize_text_field($mtcam_current_filter);
            $mtcam_logs = mtcam_filter_logs($logs, $cameras, $mtcam_filter);
            $mtcam_cameras_filtered = mtcam_filter_cameras($cameras, $mtcam_filter);

            // Show active filter info
            if ($mtcam_filter !== 'all'):
                $mtcam_filter_text = __('My Cameras', 'my-trail-camera');
                $mtcam_total_logs = count($mtcam_logs);
                ?>
                <div class="mtcam-filter-active">
					<?php echo '✅ ' . esc_html__( 'Showing:', 'my-trail-camera' ); ?> <?php echo esc_html( $mtcam_filter_text ); ?> (<?php echo esc_html( $mtcam_total_logs ); ?> <?php esc_html_e( 'records', 'my-trail-camera' ); ?>)
                </div>
            <?php endif; ?>
        </form>
    </div>

    <div class="mtcam-page-card">
        <h2 class="mtcam-mt-0">
    <?php
    /* translators: %d: Total number of detections */
    $mtcam_logs_title = sprintf( esc_html__( 'All Detections (%d)', 'my-trail-camera' ), count( $mtcam_logs ) );
    echo '📋 ' . esc_html( $mtcam_logs_title );
    ?>
</h2>

        <?php if (empty($mtcam_logs)): ?>
            <p class="mtcam-empty-state">
                <span class="dashicons dashicons-info mtcam-empty-icon" aria-hidden="true"></span><br><br>
                <?php esc_html_e('No detections yet. Waiting for first bait file access.', 'my-trail-camera'); ?>
            </p>
        <?php else: ?>

            <?php
            ?>

            <?php
?>

            <?php

            ?>

            <?php foreach ($mtcam_logs as $mtcam_log):
                $mtcam_cam = $tracker->get_camera_info($mtcam_log->device_id);
                $mtcam_recovery = $tracker->calculate_recovery_chance($mtcam_log);
                $mtcam_recovery_color = $mtcam_recovery['percentage'] >= 70 ? '#4CAF50' : ($mtcam_recovery['percentage'] >= 40 ? '#FF9800' : '#f44336');

            ?>

            <div class="mtcam-log-card" style="border-left-color:<?php echo esc_attr(MTCAM_DEFAULT_COLOR); ?>;"
                 data-mtcam-toggle="detail-<?php echo intval($mtcam_log->id); ?>"
                 data-mtcam-toggle-icon="icon-<?php echo intval($mtcam_log->id); ?>"
                 aria-expanded="false"
                 role="button"
                 tabindex="0">

                <div class="mtcam-flex-between">
                    <div class="mtcam-flex-1">
                        <strong style="font-size:16px; color:<?php echo esc_attr( MTCAM_DEFAULT_COLOR ); ?>;">#<?php echo esc_html( $mtcam_log->id ); ?></strong>
                        <span class="mtcam-detail-separator">|</span>
                        <span class="mtcam-text-gray"><?php echo wp_kses_post( mtcam_format_datetime_html( $mtcam_log->time, 'j.m.Y - H:i:s', 'Y-m-d\\TH:i:s' ) ); ?></span>
                        <span class="mtcam-detail-separator">|</span>
                        <code class="mtcam-code-inline"><?php echo esc_html($mtcam_log->ip); ?></code>
                        <span class="mtcam-detail-separator">|</span>
                        <span style="background:<?php echo esc_attr(MTCAM_DEFAULT_COLOR); ?>; color:#fff; padding:3px 10px; border-radius:12px; font-size:11px; font-weight:bold;">
                            <?php echo esc_html($mtcam_log->device_id); ?>
                        </span>
                    </div>

                    <div class="mtcam-flex-gap-15">
                        <?php
?>
                        <span style="background:<?php echo esc_attr($mtcam_recovery_color); ?>; color:#fff; padding:4px 10px; border-radius:12px; font-size:12px; font-weight:bold;">
                            <?php echo esc_html( $mtcam_recovery['percentage'] ); ?>% <?php esc_html_e( 'Chance', 'my-trail-camera' ); ?>
                        </span>
                        <?php if ($mtcam_log->lat != '?' && $mtcam_log->lon != '?'): ?>
                            <span class="mtcam-indicator mtcam-indicator-gps" title="<?php esc_attr_e('GPS Available', 'my-trail-camera'); ?>" aria-label="<?php esc_attr_e('GPS Available', 'my-trail-camera'); ?>">📍</span>
                        <?php endif; ?>
                        <span id="icon-<?php echo intval($mtcam_log->id); ?>" aria-hidden="true">➕</span>
                    </div>
                </div>

                <!-- DETAIL VIEW -->
                <div id="detail-<?php echo intval($mtcam_log->id); ?>" style="display:none; margin-top:20px; padding-top:20px; border-top:2px solid <?php echo esc_attr(MTCAM_DEFAULT_COLOR); ?>;">

                    <div style="background:<?php echo esc_attr($mtcam_recovery_color); ?>15; border-left:4px solid <?php echo esc_attr($mtcam_recovery_color); ?>; padding:20px; margin-bottom:20px; border-radius:6px;">
                        <h3 style="margin-top:0; color:<?php echo esc_attr($mtcam_recovery_color); ?>;"><?php echo '📊 '; esc_html_e('Recovery Chance Analysis', 'my-trail-camera'); ?></h3>
                        <div style="font-size:48px; font-weight:bold; text-align:center; color:<?php echo esc_attr($mtcam_recovery_color); ?>; margin:20px 0;">
                            <?php echo esc_html( $mtcam_recovery['percentage'] ); ?>%
                        </div>
                        <div class="mtcam-recovery-bar-bg">
							<div style="background:<?php echo esc_attr( $mtcam_recovery_color ); ?>; height:100%; width:<?php echo esc_attr( $mtcam_recovery['percentage'] ); ?>%; transition:width 0.3s;"></div>
                        </div>
                        <p class="mtcam-recovery-text">
                            <?php echo wp_kses_post( $mtcam_recovery['recommendation']['text'] ); ?>
                        </p>

                    </div>

                    <?php
?>

                    <div class="mtcam-det-grid">
                        <div>
                            <h3 class="mtcam-det-section-title"><?php echo '💻 '; esc_html_e('Device Information', 'my-trail-camera'); ?></h3>
                            <table class="mtcam-detail-table">
                                <tr><td class="mtcam-det-label"><?php esc_html_e('Camera:', 'my-trail-camera'); ?></td><td><span style="background:<?php echo esc_attr(MTCAM_DEFAULT_COLOR); ?>; color:#fff; padding:4px 10px; border-radius:4px;"><?php echo esc_html($mtcam_log->device_id); ?></span></td></tr>
                                <tr><td class="mtcam-det-label"><?php esc_html_e('File:', 'my-trail-camera'); ?></td><td><code><?php echo esc_html($mtcam_log->file_name); ?></code></td></tr>
                                <tr><td class="mtcam-det-label">OS:</td><td><?php echo esc_html($mtcam_log->os_info); ?></td></tr>
                                <tr><td class="mtcam-det-label"><?php esc_html_e('User:', 'my-trail-camera'); ?></td><td><?php echo esc_html($mtcam_log->sys_user); ?></td></tr>
                                <tr><td class="mtcam-det-label"><?php esc_html_e('Screen:', 'my-trail-camera'); ?></td><td><?php echo esc_html($mtcam_log->screen_res); ?></td></tr>
                                <tr><td class="mtcam-det-label">RAM:</td><td><?php
                                if ( $mtcam_log->ram_info && $mtcam_log->ram_info !== '?' ) {
                                    echo esc_html( $mtcam_log->ram_info );
                                } else {
                                    ?><span class="mtcam-text-muted"><?php esc_html_e('Chromium only', 'my-trail-camera'); ?></span><?php
                                }
                                ?></td></tr>
                                <?php
                                $mtcam_extra = ! empty( $mtcam_log->extra_data ) ? json_decode( $mtcam_log->extra_data, true ) : array();
                                ?>
                                <?php if ( ! empty( $mtcam_extra['gpu'] ) && $mtcam_extra['gpu'] !== '?' ) : ?>
                                <tr><td class="mtcam-det-label">GPU:</td><td><?php echo esc_html( $mtcam_extra['gpu'] ); ?></td></tr>
                                <?php endif; ?>
                                <?php if ( ! empty( $mtcam_extra['canvas'] ) && $mtcam_extra['canvas'] !== '?' ) : ?>
                                <tr><td class="mtcam-det-label"><?php esc_html_e('Fingerprint:', 'my-trail-camera'); ?></td><td><code><?php echo esc_html( $mtcam_extra['canvas'] ); ?></code></td></tr>
                                <?php endif; ?>
                                <?php if ( ! empty( $mtcam_extra['touch'] ) && intval( $mtcam_extra['touch'] ) > 0 ) : ?>
                                <tr><td class="mtcam-det-label"><?php esc_html_e('Touch:', 'my-trail-camera'); ?></td><td><?php echo esc_html( $mtcam_extra['touch'] ); ?> <?php esc_html_e('points', 'my-trail-camera'); ?> (<?php echo intval( $mtcam_extra['touch'] ) >= 5 ? esc_html__('phone/tablet', 'my-trail-camera') : esc_html__('PC', 'my-trail-camera'); ?>)</td></tr>
                                <?php endif; ?>
                                <tr><td class="mtcam-det-label"><?php esc_html_e('Battery:', 'my-trail-camera'); ?></td><td><?php
                                if ( ! empty( $mtcam_extra['bat'] ) ) {
                                    echo esc_html( $mtcam_extra['bat'] );
                                    if ( ! empty( $mtcam_extra['bat_charge'] ) && $mtcam_extra['bat_charge'] === 'yes' ) { echo ' ⚡'; }
                                } else {
                                    ?><span class="mtcam-text-muted"><?php esc_html_e('Chromium only', 'my-trail-camera'); ?></span><?php
                                }
                                ?></td></tr>
                            </table>
                        </div>

                        <div>
                            <h3 class="mtcam-det-section-title"><?php echo '🌍 '; esc_html_e('Network & Location', 'my-trail-camera'); ?></h3>
                            <table class="mtcam-detail-table">
                                <tr><td class="mtcam-det-label">IP:</td><td><code><?php echo esc_html($mtcam_log->ip); ?></code></td></tr>
                                <?php
                                if ( empty( $mtcam_extra ) ) {
                                    $mtcam_extra = ! empty( $mtcam_log->extra_data ) ? json_decode( $mtcam_log->extra_data, true ) : array();
                                }
                                ?>
                                <tr><td class="mtcam-det-label"><?php esc_html_e('Connection:', 'my-trail-camera'); ?></td><td><?php
                                if ( ! empty( $mtcam_extra['net_type'] ) || ! empty( $mtcam_extra['net_eff'] ) ) {
                                    $mtcam_conn_parts = array();
                                    if ( ! empty( $mtcam_extra['net_type'] ) && $mtcam_extra['net_type'] !== '?' ) { $mtcam_conn_parts[] = $mtcam_extra['net_type']; }
                                    if ( ! empty( $mtcam_extra['net_eff'] ) && $mtcam_extra['net_eff'] !== '?' ) { $mtcam_conn_parts[] = $mtcam_extra['net_eff']; }
                                    if ( ! empty( $mtcam_extra['net_dl'] ) ) { $mtcam_conn_parts[] = $mtcam_extra['net_dl']; }
                                    echo esc_html( implode( ' / ', $mtcam_conn_parts ) );
                                } else {
                                    ?><span class="mtcam-text-muted"><?php esc_html_e('Chromium only', 'my-trail-camera'); ?></span><?php
                                }
                                ?></td></tr>
                                <tr><td class="mtcam-det-label">GPS:</td><td>
                                    <?php if ($mtcam_log->lat != '?' && $mtcam_log->lon != '?'): ?>
                                        <?php echo esc_html($mtcam_log->lat); ?>, <?php echo esc_html($mtcam_log->lon); ?>
                                        <?php if (!empty($mtcam_log->acc) && $mtcam_log->acc != '?'): ?>
                                            <br><small class="mtcam-text-muted"><?php esc_html_e('Accuracy:', 'my-trail-camera'); ?> <?php echo esc_html($mtcam_log->acc); ?>m</small>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <?php esc_html_e('Not available', 'my-trail-camera'); ?>
                                    <?php endif; ?>
                                </td></tr>
                                <?php if ($mtcam_log->lat != '?' && $mtcam_log->lon != '?'): ?>
                                <tr><td colspan="2" >
                                    <a href="https://www.google.com/maps?q=<?php echo esc_attr($mtcam_log->lat); ?>,<?php echo esc_attr($mtcam_log->lon); ?>" target="_blank"
                                       class="mtcam-btn-maps">
                                        <?php echo '📍 '; esc_html_e('Open in Google Maps', 'my-trail-camera'); ?>
                                    </a>
                                </td></tr>
                                <?php endif; ?>
                            </table>
                        </div>
                    </div>

                    <div class="mtcam-det-actions">

                        <form method="post" style="display:inline;" data-mtcam-confirm="<?php echo esc_attr(__('Are you sure you want to delete this record?', 'my-trail-camera')); ?>">
                            <?php wp_nonce_field('delete_log_' . $mtcam_log->id); ?>
                            <input type="hidden" name="action" value="delete_record">
                            <input type="hidden" name="log_id" value="<?php echo intval($mtcam_log->id); ?>">
                            <button type="submit" class="mtcam-btn-delete"><?php echo '🗑️ '; esc_html_e('Delete Record', 'my-trail-camera'); ?></button>
                        </form>
                    </div>

                </div>
            </div>

            <?php endforeach; ?>

        <?php endif; ?>
    </div>
</div>
