<?php
/**
 * MTC — Camera Table
 * @package My Trail Camera
 * @since 8.1.0
 */

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

function mtcam_render_camera_table($cameras, $tracker) {
    // Sorting: active on top (newest first), stolen at bottom (most recent theft first)
    uasort($cameras, function($a, $b) {
        $a_stolen = !empty($a['stolen_date']);
        $b_stolen = !empty($b['stolen_date']);

        // Stolen always at the bottom
        if ($a_stolen !== $b_stolen) return $a_stolen ? 1 : -1;

        // Among stolen: most recent theft first
        if ($a_stolen && $b_stolen) {
            return strcmp($b['stolen_date'] ?? '', $a['stolen_date'] ?? '');
        }

        // Among active: most recently added first
        return strcmp($b['created_date'] ?? '', $a['created_date'] ?? '');
    });

    // ⚡ Batch load detection counts instead of N+1 queries.
    $detection_counts = $tracker->get_detection_counts();

    // ⚡ Batch battery calculation for all cameras at once (1 weather API call per unique GPS).
    $mtcam_battery_cache = array();
    $show_bat_stolen = get_option('mtcam_show_battery_stolen', 'yes') === 'yes';
    foreach ($cameras as $mtcam_bid => $mtcam_bcam) {
        $mtcam_bcam_stolen = mtcam_is_stolen($mtcam_bcam);
        if (mtcam_is_my_camera($mtcam_bcam) && mtcam_is_active($mtcam_bcam) && !empty($mtcam_bcam['gps_lat']) && !empty($mtcam_bcam['gps_lon']) && (!$mtcam_bcam_stolen || $show_bat_stolen)) {
            $mtcam_battery_cache[$mtcam_bid] = mtcam_estimate_battery_simple($mtcam_bcam);
        }
    }

    // Context passed to detail partials to avoid re-querying.
    $detail_context = array(
        'cameras' => $cameras,
    );
    ?>

    <table class="wp-list-table widefat striped">
        <?php mtcam_table_caption( __( 'Trail cameras', 'my-trail-camera' ) ); ?>
        <thead>
            <tr>
                <th><?php esc_html_e('Trail Camera ID', 'my-trail-camera'); ?></th>
                <th><?php esc_html_e('Location', 'my-trail-camera'); ?></th>
                <th><?php esc_html_e('Days in Field', 'my-trail-camera'); ?></th>
                <th>🔋</th>
                <th>🛡️</th>
                <th><?php esc_html_e('Status', 'my-trail-camera'); ?></th>
                <th><?php esc_html_e('Alerts', 'my-trail-camera'); ?></th>
                <th><?php esc_html_e('Actions', 'my-trail-camera'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($cameras as $cam_id => $cam):
                $is_stolen = mtcam_is_stolen($cam);
                $is_active = mtcam_is_active($cam);
                $days_in_field = mtcam_get_days_in_field($cam['deploy_date'] ?? '', $cam['stolen_date'] ?? '');
                $detection_count = $detection_counts[$cam_id] ?? 0;
                $has_detections = $detection_count > 0;
                $row_class = $has_detections ? 'mtcam-has-detections' : '';
            ?>
            <tr data-mtcam-toggle="details-<?php echo esc_attr( $cam_id ); ?>" class="<?php echo esc_attr( $row_class ); ?> mtcam-clickable" title="<?php esc_attr_e( 'Click for detail', 'my-trail-camera' ); ?>" aria-expanded="false" role="button" tabindex="0">
                <td>
                    <div class="mtcam-flex-center mtcam-gap-8">
                        <?php if (mtcam_is_my_camera($cam)): ?>
                            <code class="mtcam-camera-badge"><?php echo esc_html($cam_id); ?></code>
                        <?php else: ?>
                            <code class="mtcam-camera-badge mtcam-badge-hidden">●●●●●●</code>
                        <?php endif; ?>
                        <?php
                        $pt = $cam['power_type'] ?? 'lithium';
                        echo '<span title="' . esc_attr( mtcam_get_power_label( $pt ) ) . '">' . esc_html( mtcam_get_power_icon( $pt ) ) . '</span>';
                        ?>
                        <?php mtcam_render_owner_badge($cam); ?>
                    </div>
                </td>
                <td>
                    <small class="mtcam-text-muted"><?php echo esc_html($cam['location']); ?></small>
                </td>
                <td><?php mtcam_render_days_cell( $cam, $days_in_field, $is_stolen ); ?></td>
                <td>
                    <?php
                    if (isset($mtcam_battery_cache[$cam_id])) {
                        $bat = $mtcam_battery_cache[$cam_id];
                        $bp = $bat['battery_pct'];
                        $bp_display = number_format($bp, 1);
                        $bc = mtcam_battery_color($bp);
                        echo '<div class="mtcam-flex-center mtcam-gap-4" title="' . esc_attr($bat['weather'] . ' | ' . $bat['temperature'] . '°C') . '">';
                        echo '<div class="mtcam-battery-bar-bg mtcam-battery-bar-xs">';
						echo '<div class="mtcam-battery-bar-fill mtcam-battery-bar-fill-xs" style="width: ' . intval( $bp ) . '%; background: ' . esc_attr( $bc ) . ';"></div>';
                        echo '</div>';
                        echo '<small class="mtcam-font-bold" style="color: ' . esc_attr( $bc ) . ';">' . esc_html( $bp_display ) . '%</small>';
                        echo '</div>';
                    } else {
                        echo '<span class="mtcam-text-muted">—</span>';
                    }
                    ?>
                </td>
                <td><?php mtcam_render_security_icons( $cam ); ?></td>
                <td><?php mtcam_render_status_badge($cam); ?></td>
                <td>
                    <?php if ($has_detections): ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-logs&filter=my' ) ); ?>" class="mtcam-detection-badge" title="<?php esc_attr_e( 'Click to view theft alerts', 'my-trail-camera' ); ?>">
                            🔴 <?php echo esc_html( $detection_count ); ?> ▼
                        </a>
                    <?php else: ?>
                        <span class="mtcam-text-muted"><?php echo esc_html( $detection_count ); ?></span>
                    <?php endif; ?>
                </td>
                <td><?php
                    mtcam_render_actions_cell( $cam_id, $cam, '' );
                ?></td>
            </tr>

            <!-- Expandable Details -->
            <?php mtcam_render_camera_details($cam_id, $cam, $days_in_field, $detection_count, isset($mtcam_battery_cache[$cam_id]) ? $mtcam_battery_cache[$cam_id] : null, $detail_context); ?>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php
}
