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

// Load camera presentation functions
require_once plugin_dir_path(__FILE__) . 'page-camera-list.php';
// ============================================================
// DASHBOARD TEMPLATE
// ============================================================
?>

<main class="wrap mtcam-wrap">

 <?php
 // Check if editing a camera
 if ( isset( $_GET['edit'] ) && ! empty( $_GET['edit'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_edit_camera' ) ) {
 $mtcam_edit_cam_id = sanitize_text_field( wp_unslash( $_GET['edit'] ) );
 $mtcam_cameras_all = $tracker->get_cameras();

 if (isset($mtcam_cameras_all[$mtcam_edit_cam_id])) {
 // Show edit form
 ?>
 <h2>✏️ <?php esc_html_e('Edit Camera:', 'my-trail-camera'); ?> <?php echo esc_html($mtcam_edit_cam_id); ?></h2>

 <p><a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-dashboard' ) ); ?>" class="button">
    &larr; <?php esc_html_e( 'Back to Dashboard', 'my-trail-camera' ); ?>
</a></p>

 <form method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-dashboard' ) ); ?>">
 <?php wp_nonce_field('mtcam_settings'); ?>
 <input type="hidden" name="redirect_to" value="dashboard">
 <?php mtcam_render_edit_camera_form($mtcam_edit_cam_id, $mtcam_cameras_all[$mtcam_edit_cam_id]); ?>
 </form>

 </main>
 <?php
 return;
 } else {
 echo '<div class="notice notice-error" role="alert"><p>' . esc_html__('Camera not found.', 'my-trail-camera') . '</p></div>';
 }
 }
 ?>

 <?php
 $mtcam_cameras = $tracker->get_cameras();
 $mtcam_damage_data = mtcam_calculate_stolen_damage($mtcam_cameras, 'my');
 $mtcam_total_damage = $mtcam_damage_data['total_damage'];
 $mtcam_stolen_count = $mtcam_damage_data['stolen_count'];
 ?>

 <h1>🏠 My Trail Camera</h1>

 <?php if ( isset( $_GET['camera_added'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_dashboard_notice' ) ) : ?>
 <div class="notice notice-success is-dismissible" role="alert"><p><?php echo esc_html__('Camera', 'my-trail-camera'); ?> <strong><?php echo esc_html( sanitize_text_field( wp_unslash( $_GET['camera_added'] ) ) ); ?></strong> <?php echo esc_html__('was successfully added!', 'my-trail-camera'); ?></p></div>
 <?php endif; ?>
 <?php if ( isset( $_GET['camera_deleted'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_dashboard_notice' ) ) : ?>
 <div class="notice notice-success is-dismissible" role="alert"><p><?php esc_html_e('Camera was deleted.', 'my-trail-camera'); ?></p></div>
 <?php endif; ?>
 <?php if ( isset( $_GET['camera_checked'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_dashboard_notice' ) ) : ?>
 <div class="notice notice-success is-dismissible" role="alert"><p><?php echo esc_html__('Camera check for', 'my-trail-camera'); ?> <strong><?php echo esc_html( sanitize_text_field( wp_unslash( $_GET['camera_checked'] ) ) ); ?></strong> <?php echo esc_html__('was recorded in history.', 'my-trail-camera'); ?></p></div>
 <?php endif; ?>
 <?php if ( isset( $_GET['camera_check_error'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_dashboard_notice' ) ) : ?>
 <div class="notice notice-error is-dismissible" role="alert"><p>❌ <?php echo esc_html__('Camera check failed — trail camera', 'my-trail-camera'); ?> <strong><?php echo esc_html( sanitize_text_field( wp_unslash( $_GET['camera_check_error'] ) ) ); ?></strong> <?php echo esc_html__('was not found.', 'my-trail-camera'); ?></p></div>
 <?php endif; ?>
 <?php if ( isset( $_GET['camera_updated'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_dashboard_notice' ) ) : ?>
 <div class="notice notice-success is-dismissible" role="alert"><p><?php esc_html_e('Camera was updated.', 'my-trail-camera'); ?></p></div>
 <?php endif; ?>

 <?php
 $mtcam_my_cameras = mtcam_filter_cameras($mtcam_cameras, 'my');
 $mtcam_other_cameras = mtcam_filter_cameras($mtcam_cameras, 'other');
 $mtcam_manage_other = get_option('mtcam_manage_other_cameras', 'yes');

 // Snow cover check — use first active camera with GPS
 $mtcam_snow_warning = false;
 foreach ($mtcam_my_cameras as $mtcam_cam) {
     if (mtcam_is_active($mtcam_cam) && !empty($mtcam_cam['gps_lat']) && !empty($mtcam_cam['gps_lon'])) {
         $mtcam_battery = mtcam_estimate_battery_simple($mtcam_cam);
         if (!empty($mtcam_battery['snow_cover'])) {
             $mtcam_snow_warning = true;
         }
         break; // Check only one camera (same region)
     }
 }
 ?>

 <?php if ($mtcam_snow_warning): ?>
 <div class="mtcam-snow-warning">
     <span aria-hidden="true">❄️</span> <strong><?php esc_html_e('Snow cover detected in the camera area', 'my-trail-camera'); ?></strong> — <?php esc_html_e('We do not recommend checking or replacing cameras. Footprints in the snow reveal camera locations and make theft easier.', 'my-trail-camera'); ?>
 </div>
 <?php endif; ?>

 <?php if (empty($mtcam_my_cameras) && empty($mtcam_other_cameras)): ?>
 <!-- Welcome / Getting Started Section -->
 <div class="mtcam-welcome-box">
 <h2 class="mtcam-text-info"><?php esc_html_e('Welcome to My Trail Camera', 'my-trail-camera'); ?></h2>
 <p class="mtcam-text-md">
 <strong>My Trail Camera</strong> <?php esc_html_e('helps you manage, monitor, and protect your trail cameras — all from one place.', 'my-trail-camera'); ?>
 </p>

 <h3><?php esc_html_e('Quick Start', 'my-trail-camera'); ?></h3>
 <div class="mtcam-welcome-steps">
 <div class="mtcam-welcome-step">
 <span class="mtcam-welcome-step-number">1</span>
 <div>
 <strong><a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-add-camera' ) ); ?>"><?php esc_html_e('Add your first camera', 'my-trail-camera'); ?></a></strong>
 <p><?php esc_html_e('Enter camera details — name, model, location, and deployment date.', 'my-trail-camera'); ?></p>
 </div>
 </div>
 <div class="mtcam-welcome-step">
 <span class="mtcam-welcome-step-number">2</span>
 <div>
 <strong><a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-settings&tab=security' ) ); ?>"><?php esc_html_e('Generate bait files for SD card', 'my-trail-camera'); ?></a></strong>
 <p><?php esc_html_e('Create honeypot HTML files that silently collect data if a thief opens them. Download the ZIP and copy to SD card.', 'my-trail-camera'); ?></p>
 </div>
 </div>
 <div class="mtcam-welcome-step">
 <span class="mtcam-welcome-step-number">3</span>
 <div>
 <strong><?php esc_html_e('Deploy & monitor', 'my-trail-camera'); ?></strong>
 <p><?php esc_html_e('Once cameras are added, this dashboard shows a live overview — battery status, days in field, and alerts.', 'my-trail-camera'); ?></p>
 </div>
 </div>
 </div>

 <div class="mtcam-welcome-grid">
 <a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-add-camera' ) ); ?>" class="mtcam-welcome-card">
 <h4>📷 <?php esc_html_e('Camera Management', 'my-trail-camera'); ?></h4>
 <p><?php esc_html_e('Add cameras, edit details, monitor battery and days in the field.', 'my-trail-camera'); ?></p>
 </a>
 <a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-locations' ) ); ?>" class="mtcam-welcome-card">
 <h4>📍 <?php esc_html_e('GPS & Locations', 'my-trail-camera'); ?></h4>
 <p><?php esc_html_e('Record GPS coordinates and review deployment locations.', 'my-trail-camera'); ?></p>
 </a>
 <div class="mtcam-welcome-card">
 <h4>🔋 <?php esc_html_e('Battery Estimate', 'my-trail-camera'); ?></h4>
 <p><?php esc_html_e('Automatic battery calculation based on weather, consumption, and solar panel.', 'my-trail-camera'); ?></p>
 </div>
 <a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-settings&tab=security' ) ); ?>" class="mtcam-welcome-card">
 <h4>🛡️ <?php esc_html_e('Camera Protection', 'my-trail-camera'); ?></h4>
 <p><?php esc_html_e('Generate honeypot files that capture thief data when opened.', 'my-trail-camera'); ?></p>
 </a>
 </div>

 <div class="mtcam-welcome-cta">
 <a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-add-camera' ) ); ?>" class="button button-primary">
 ➕ <?php esc_html_e('Add First Camera', 'my-trail-camera'); ?>
 </a>
 <p><?php esc_html_e('After adding cameras, a clear overview table will appear here.', 'my-trail-camera'); ?></p>
 </div>
 </div>
 <?php endif; ?>

 <!-- MY CAMERAS SECTION -->
 <?php if (!empty($mtcam_my_cameras)): ?>
 <section class="mtcam-page-card">
 <header class="mtcam-section-header">
 <h2>📷 <?php esc_html_e('My Cameras', 'my-trail-camera'); ?></h2>
 <div class="mtcam-section-actions">
 <?php if ($mtcam_stolen_count > 0 && $mtcam_total_damage > 0): ?>
 <div class="mtcam-damage-widget">
 <div class="mtcam-damage-label">💰 <?php esc_html_e('Total Damage', 'my-trail-camera'); ?></div>
 <div class="mtcam-damage-amount"><?php echo esc_html(number_format($mtcam_total_damage, 2, ',', ' ')); ?> €</div>
 <div class="mtcam-damage-count">📷 <?php echo esc_html( $mtcam_stolen_count ); ?> <?php esc_html_e( 'stolen', 'my-trail-camera' ); ?></div>
 </div>
 <?php endif; ?>
 <a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-add-camera' ) ); ?>" class="button button-primary">
 ➕ <?php esc_html_e('Add Camera', 'my-trail-camera'); ?>
 </a>
 </div>
 </header>
 <?php mtcam_render_camera_table($mtcam_my_cameras, $tracker); ?>
 </section>
 <?php endif; ?>

 <!-- OTHER CAMERAS SECTION (only if enabled) -->
 <?php if ($mtcam_manage_other === 'yes' && !empty($mtcam_other_cameras)): ?>
 <section class="mtcam-page-card">
 <header class="mtcam-section-header">
 <h2>👥 <?php esc_html_e('Other Cameras', 'my-trail-camera'); ?></h2>
 </header>
 <?php mtcam_render_camera_table($mtcam_other_cameras, $tracker); ?>
 </section>
 <?php endif; ?>

 <!-- ═══ DASHBOARD STATUS PANEL ═══ -->
 <?php if ( ! empty( $mtcam_my_cameras ) ) : ?>
 <?php
 // --- Collect dashboard data ---
 global $wpdb;

 // Stats
 $mtcam_dash_total      = count( $mtcam_cameras );
 $mtcam_dash_active     = count( array_filter( $mtcam_cameras, 'mtcam_is_active' ) );
 $mtcam_dash_stolen     = count( array_filter( $mtcam_cameras, 'mtcam_is_stolen' ) );
 $mtcam_dash_value      = array_sum( array_map( 'mtcam_get_camera_total_value', $mtcam_my_cameras ) );
 $mtcam_dash_detections = intval( mtcam_db_get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}mtcam_detections" ) );

 // Low battery cameras (active, under 30%)
 $mtcam_dash_low_bat = array();
 foreach ( $mtcam_my_cameras as $mtcam_dc_id => $mtcam_dc ) {
     if ( ! mtcam_is_active( $mtcam_dc ) || ! empty( $mtcam_dc['stolen_date'] ) ) continue;
     $mtcam_dc_bat = mtcam_estimate_battery_simple( $mtcam_dc );
     if ( $mtcam_dc_bat['battery_pct'] < 30 ) {
         $mtcam_dash_low_bat[] = array(
             'cam_id'  => $mtcam_dc_id,
             'name'    => $mtcam_dc['name'] ?: $mtcam_dc_id,
             'pct'     => $mtcam_dc_bat['battery_pct'],
             'color'   => mtcam_battery_color( $mtcam_dc_bat['battery_pct'] ),
         );
     }
 }
 usort( $mtcam_dash_low_bat, function( $a, $b ) { return $a['pct'] <=> $b['pct']; } );

 // Cameras nearing planned monitoring end
 $mtcam_dash_ending = array();
 foreach ( $mtcam_my_cameras as $mtcam_dc_id => $mtcam_dc ) {
     if ( ! mtcam_is_active( $mtcam_dc ) || empty( $mtcam_dc['deploy_date'] ) ) continue;
     $mtcam_dc_planned = intval( $mtcam_dc['planned_days'] ?? 0 );
     if ( $mtcam_dc_planned < 1 ) continue;
     $mtcam_dc_days = mtcam_get_days_in_field( $mtcam_dc['deploy_date'] );
     $mtcam_dc_remaining = $mtcam_dc_planned - $mtcam_dc_days;
     if ( $mtcam_dc_remaining <= 7 ) {
         $mtcam_dash_ending[] = array(
             'cam_id'    => $mtcam_dc_id,
             'name'      => $mtcam_dc['name'] ?: $mtcam_dc_id,
             'remaining' => max( 0, $mtcam_dc_remaining ),
             'days'      => $mtcam_dc_days,
             'planned'   => $mtcam_dc_planned,
         );
     }
 }
 usort( $mtcam_dash_ending, function( $a, $b ) { return $a['remaining'] <=> $b['remaining']; } );

 // Cameras without GPS
 $mtcam_dash_no_gps = array();
 foreach ( $mtcam_my_cameras as $mtcam_dc_id => $mtcam_dc ) {
     if ( ! mtcam_is_active( $mtcam_dc ) ) continue;
     if ( empty( $mtcam_dc['gps_lat'] ) || empty( $mtcam_dc['gps_lon'] ) ) {
         $mtcam_dash_no_gps[] = $mtcam_dc['name'] ?: $mtcam_dc_id;
     }
 }

 // Any action needed?
 $mtcam_dash_has_alerts = ! empty( $mtcam_dash_low_bat ) || ! empty( $mtcam_dash_ending ) || ! empty( $mtcam_dash_no_gps );
 ?>

 <section class="mtcam-page-card" style="margin-top:16px;">
 <header class="mtcam-section-header">
     <h2>📊 <?php esc_html_e( 'Overview', 'my-trail-camera' ); ?></h2>
 </header>

 <!-- Stats row -->
 <div class="mtcam-about-stats-grid" style="margin:0 0 16px 0;">
     <div class="mtcam-about-stat mtcam-about-stat-blue">
         <div class="mtcam-about-stat-icon">📷</div>
         <div class="mtcam-about-stat-value"><?php echo esc_html( $mtcam_dash_total ); ?></div>
         <div class="mtcam-about-stat-label"><?php esc_html_e( 'Total', 'my-trail-camera' ); ?></div>
     </div>
     <div class="mtcam-about-stat mtcam-about-stat-green">
         <div class="mtcam-about-stat-icon">🌿</div>
         <div class="mtcam-about-stat-value"><?php echo esc_html( $mtcam_dash_active ); ?></div>
         <div class="mtcam-about-stat-label"><?php esc_html_e( 'Active', 'my-trail-camera' ); ?></div>
     </div>
     <div class="mtcam-about-stat mtcam-about-stat-red">
         <div class="mtcam-about-stat-icon">🚨</div>
         <div class="mtcam-about-stat-value"><?php echo esc_html( $mtcam_dash_stolen ); ?></div>
         <div class="mtcam-about-stat-label"><?php esc_html_e( 'Stolen', 'my-trail-camera' ); ?></div>
     </div>
     <div class="mtcam-about-stat mtcam-about-stat-orange">
         <div class="mtcam-about-stat-icon">🪤</div>
         <div class="mtcam-about-stat-value"><?php echo esc_html( $mtcam_dash_detections ); ?></div>
         <div class="mtcam-about-stat-label"><?php esc_html_e( 'Theft Alerts', 'my-trail-camera' ); ?></div>
     </div>
     <div class="mtcam-about-stat mtcam-about-stat-teal">
         <div class="mtcam-about-stat-icon">💰</div>
         <div class="mtcam-about-stat-value"><?php echo esc_html( number_format( $mtcam_dash_value, 0, ',', ' ' ) ); ?> €</div>
         <div class="mtcam-about-stat-label"><?php esc_html_e( 'Value', 'my-trail-camera' ); ?></div>
     </div>
 </div>

 <?php
 $mtcam_dash_has_extra = false;
 $mtcam_dash_has_extra_section = $mtcam_dash_has_extra;
 ?>
 <?php if ( $mtcam_dash_has_alerts || $mtcam_dash_has_extra_section ) : ?>
 <div style="display:grid; grid-template-columns:<?php echo $mtcam_dash_has_extra_section && $mtcam_dash_has_alerts ? '1fr 1fr' : '1fr'; ?>; gap:16px;">

     <!-- Alerts column -->
     <?php if ( $mtcam_dash_has_alerts ) : ?>
     <div>
         <!-- Low battery -->
         <?php if ( ! empty( $mtcam_dash_low_bat ) ) : ?>
         <div style="background:#fff3e0;border-left:4px solid #ff9800;padding:10px 14px;border-radius:4px;margin-bottom:10px;font-size:12px;">
             <strong>🔋 <?php esc_html_e( 'Low Battery', 'my-trail-camera' ); ?></strong>
             <ul style="margin:6px 0 0 16px;padding:0;">
                 <?php foreach ( $mtcam_dash_low_bat as $mtcam_lb ) : ?>
                 <li>
                     <strong><?php echo esc_html( $mtcam_lb['name'] ); ?></strong>
                     — <span style="color:<?php echo esc_attr( $mtcam_lb['color'] ); ?>;font-weight:700;"><?php echo esc_html( $mtcam_lb['pct'] ); ?>%</span>
                 </li>
                 <?php endforeach; ?>
             </ul>
         </div>
         <?php endif; ?>

         <!-- Ending monitoring -->
         <?php if ( ! empty( $mtcam_dash_ending ) ) : ?>
         <div style="background:#e3f2fd;border-left:4px solid #2196f3;padding:10px 14px;border-radius:4px;margin-bottom:10px;font-size:12px;">
             <strong>📅 <?php esc_html_e( 'Monitoring Ending', 'my-trail-camera' ); ?></strong>
             <ul style="margin:6px 0 0 16px;padding:0;">
                 <?php foreach ( $mtcam_dash_ending as $mtcam_de ) : ?>
                 <li>
                     <strong><?php echo esc_html( $mtcam_de['name'] ); ?></strong>
                     — <?php
                     if ( $mtcam_de['remaining'] <= 0 ) {
                         echo '<span style="color:#c62828;font-weight:700;">' . esc_html__( 'overdue', 'my-trail-camera' ) . '</span>';
                     } else {
                         echo esc_html( sprintf(
                             /* translators: %d: days remaining */
                             _n( '%d day left', '%d days left', $mtcam_de['remaining'], 'my-trail-camera' ),
                             $mtcam_de['remaining']
                         ) );
                     }
                     ?>
                     <span style="color:#999;">(<?php echo esc_html( $mtcam_de['days'] . '/' . $mtcam_de['planned'] ); ?>)</span>
                 </li>
                 <?php endforeach; ?>
             </ul>
         </div>
         <?php endif; ?>

         <!-- No GPS -->
         <?php if ( ! empty( $mtcam_dash_no_gps ) ) : ?>
         <div style="background:#f5f5f5;border-left:4px solid #9e9e9e;padding:10px 14px;border-radius:4px;font-size:12px;">
             <strong>📍 <?php esc_html_e( 'Missing GPS', 'my-trail-camera' ); ?></strong>
             — <?php echo esc_html( implode( ', ', $mtcam_dash_no_gps ) ); ?>
             <div style="color:#999;font-size:11px;margin-top:4px;"><?php esc_html_e( 'Snow detection, solar estimate and theft proximity alerts require GPS.', 'my-trail-camera' ); ?></div>
         </div>
         <?php endif; ?>
     </div>
     <?php endif; ?>

 </div>
 <?php endif; ?>

 </section>
 <?php endif; ?>

</main>
