<?php
/**
 * MTC - Trail camera management (render helpers)
 * Rendering badges, statuses, GPS.
 *
 * DB layer moved to includes/cameras-repository.php
 *
 * @package My Trail Camera
 * @since 8.1.0
 */

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

// ============================================================================
// RENDERING
// ============================================================================

/**
 * Render status badge
 */
function mtcam_render_status_badge($cam) {
    // OPTIMIZATION: Use helper functions
    $is_tested = mtcam_is_tested($cam);
    $is_stolen = mtcam_is_stolen($cam);
    $is_active = mtcam_is_active($cam);

    if ($is_tested) {
        echo '<span class="mtcam-status-badge mtcam-status-test">' . esc_html(mtcam_label_tested()) . '</span>';
    } elseif ($is_stolen) {
        echo '<span class="mtcam-status-badge mtcam-status-stolen">' . esc_html(mtcam_label_stolen()) . '</span>';

        if (!empty($cam['stolen_date'])) {
            try {
                $date = new DateTime($cam['stolen_date']);
                echo ' <span class="mtcam-status-date">' . esc_html($date->format('d.m.Y')) . '</span>';
            } catch (Exception $e) {}
        }
        if (($cam['police_reported'] ?? 'no') === 'yes') {
            echo ' <span class="mtcam-police-badge" title="' . esc_attr__('Reported to police', 'my-trail-camera') . '">🚨</span>';
        }
    } elseif ($is_active) {
        echo '<span class="mtcam-status-badge mtcam-status-active">' . esc_html(mtcam_label_active()) . '</span>';
    } else {
        echo '<span class="mtcam-status-badge mtcam-status-home">' . esc_html(mtcam_label_at_home()) . '</span>';
    }
}

/**
 * Generic badge list renderer — DRY helper for files, security, GPS trackers.
 *
 * @param array  $cam         Camera data.
 * @param array  $fields_map  [ 'field_key' => 'label_function_name', ... ]
 * @param string $badge_class CSS class for each badge.
 * @param string $empty_text  Text shown when no badges apply.
 * @return bool  Whether any badges were rendered.
 */
function mtcam_render_badge_list( $cam, $fields_map, $badge_class, $empty_text ) {
    $items = array();
    foreach ( $fields_map as $field => $label_fn ) {
        if ( ( $cam[ $field ] ?? 'no' ) === 'yes' ) {
            $items[] = $label_fn();
        }
    }

    if ( ! empty( $items ) ) {
        foreach ( $items as $item ) {
            echo '<span class="' . esc_attr( $badge_class ) . '">' . esc_html( $item ) . '</span>';
        }
    } else {
        echo '<span class="mtcam-text-muted">' . esc_html( $empty_text ) . '</span>';
    }

    return ! empty( $items );
}

/**
 * Render file badges
 */
function mtcam_render_files( $cam ) {
    mtcam_render_badge_list( $cam, array(
        'bait_html' => 'mtcam_label_bait_html',
        'bait_tel'  => 'mtcam_label_bait_tel',
    ), 'mtcam-badge mtcam-badge-file', __( 'No files', 'my-trail-camera' ) );
}

/**
 * Render security badges
 */
function mtcam_render_security( $cam ) {
    mtcam_render_badge_list( $cam, array(
        'sec_box'      => 'mtcam_label_sec_box',
        'sec_cable'    => 'mtcam_label_sec_cable',
        'sec_padlock'  => 'mtcam_label_sec_padlock',
        'sec_password' => 'mtcam_label_sec_password',
        'sec_camera'   => 'mtcam_label_sec_camera',
    ), 'mtcam-sec-item', '—' );
}

/**
 * Render GPS tracker badges
 */
function mtcam_render_gps_trackers( $cam ) {
    return mtcam_render_badge_list( $cam, array(
        'gps_airtag'  => 'mtcam_label_gps_airtag',
        'gps_tile'    => 'mtcam_label_gps_tile',
        'gps_samsung' => 'mtcam_label_gps_smarttag',
        'gps_other'   => 'mtcam_label_gps_other',
    ), 'mtcam-badge mtcam-badge-gps', __( 'No tracker', 'my-trail-camera' ) );
}

/**
 * Render GPS coordinates with map link
 * @param array $cam Camera data
 * @param bool $inline If true, shows in one line without formatting
 */
function mtcam_render_gps($cam, $inline = false) {
    if (!empty($cam['gps_lat']) && !empty($cam['gps_lon'])) {
        if ($inline) {
            // Simple inline display for detail view
            echo esc_html($cam['gps_lat']) . '°, ' . esc_html($cam['gps_lon']) . '° ';
			echo '<a href="' . esc_url('https://www.google.com/maps/search/?api=1&query=' . $cam['gps_lat'] . ',' . $cam['gps_lon']) . '" target="_blank">';
            echo '(' . esc_html__('Map', 'my-trail-camera') . ')</a>';
        } else {
            // Original formatted display
            echo '<code class="mtcam-text-small">' . esc_html($cam['gps_lat']) . '°, ' . esc_html($cam['gps_lon']) . '°</code><br>';
			echo '<a href="' . esc_url('https://www.google.com/maps/search/?api=1&query=' . $cam['gps_lat'] . ',' . $cam['gps_lon']) . '" target="_blank" class="mtcam-text-small mtcam-link-map">';
            echo esc_html(MTCAM_ICON_MAP) . ' ' . esc_html__('Open in Map', 'my-trail-camera') . '</a>';
        }
    } else {
        echo '<span class="mtcam-text-muted">' . esc_html__('Not set', 'my-trail-camera') . '</span>';
    }
}

// ============================================================================
// TABLE CELL RENDERERS
// ============================================================================

/**
 * Render "Days in Field" table cell content.
 *
 * Shows days count, planned progress bar, overdue warning, and last-check info.
 *
 * @param array $cam        Camera data.
 * @param int   $days       Days in field.
 * @param bool  $is_stolen  Whether camera is stolen.
 */
function mtcam_render_days_cell( $cam, $days, $is_stolen ) {
	$planned = intval( $cam['planned_days'] ?? 0 );

	if ( $days > 0 ) {
		echo '<strong>' . esc_html( $days ) . '</strong>';
		if ( $planned > 0 ) {
			echo ' / ' . esc_html( $planned );
		}
		echo ' ';
		esc_html_e( 'days', 'my-trail-camera' );

		if ( $planned > 0 ) {
			$pct  = min( round( ( $days / $planned ) * 100 ), 100 );
			$over = $days > $planned;
			if ( $over || $pct >= 90 ) {
				$bar_color = '#d63638';
			} elseif ( $pct >= 70 ) {
				$bar_color = '#dba617';
			} else {
				$bar_color = '#00a32a';
			}
			echo '<div class="mtcam-plan-bar' . ( $over ? ' mtcam-plan-over' : '' ) . '" title="' . esc_attr( $pct ) . '% ' . esc_attr__( 'of planned stay', 'my-trail-camera' ) . '">';
			echo '<div class="mtcam-plan-fill" style="width: ' . (int) $pct . '%; background: ' . esc_attr( $bar_color ) . ';"></div>';
			echo '</div>';
			if ( $over ) {
				echo '<small style="color: #d63638; font-weight: 600;">⚠️ +' . esc_html( $days - $planned ) . ' ';
				esc_html_e( 'days', 'my-trail-camera' );
				echo '</small>';
			}
		}
	} elseif ( ! empty( $cam['deploy_date'] ) ) {
		echo '<strong>0</strong>';
		if ( $planned > 0 ) {
			echo ' / ' . esc_html( $planned );
		}
		echo ' ';
		esc_html_e( 'days', 'my-trail-camera' );
		if ( $planned > 0 ) {
			echo '<div class="mtcam-plan-bar"><div class="mtcam-plan-fill" style="width:0%;background:#00a32a;"></div></div>';
		}
	} else {
		echo '<span class="mtcam-text-muted">—</span>';
	}

	// Last check info.
	$last_checked = $cam['last_checked'] ?? '';
	if ( ! empty( $last_checked ) && ! $is_stolen ) {
		$check_days  = max( 0, intval( ( time() - strtotime( $last_checked ) ) / 86400 ) );
		$check_color = $check_days > 30 ? '#d63638' : ( $check_days > 14 ? '#dba617' : '#999' );
		echo '<small style="color:' . esc_attr( $check_color ) . ';">🔍 ';
		if ( 0 === $check_days ) {
			esc_html_e( 'Checked today', 'my-trail-camera' );
		} else {
			/* translators: %d: number of days since last check */
			echo esc_html( sprintf( __( 'Check %d d ago', 'my-trail-camera' ), $check_days ) );
		}
		echo '</small>';
	}
}

/**
 * Render security/protection icons for table overview column.
 *
 * @param array $cam Camera data.
 */
function mtcam_render_security_icons( $cam ) {
	$icon_map = array(
		'bait_html'    => array( '🌐', __( 'HTML bait', 'my-trail-camera' ) ),
		'bait_tel'     => array( '☎️', __( 'Tel bait', 'my-trail-camera' ) ),
		'sec_box'      => array( '🛡️', __( 'Metal Box', 'my-trail-camera' ) ),
		'sec_cable'    => array( '🔗', __( 'Cable Lock', 'my-trail-camera' ) ),
		'sec_padlock'  => array( '🔐', __( 'Padlock', 'my-trail-camera' ) ),
		'sec_password' => array( '🔑', __( 'Password', 'my-trail-camera' ) ),
		'sec_camera'   => array( '📷', __( 'Monitoring', 'my-trail-camera' ) ),
		'gps_airtag'   => array( '🍎', 'AirTag' ),
		'gps_tile'     => array( '📍', 'Tile' ),
		'gps_samsung'  => array( '🏷️', 'SmartTag' ),
		'gps_other'    => array( '🔍', __( 'Other GPS tracker', 'my-trail-camera' ) ),
	);

	$icons = array();
	foreach ( $icon_map as $field => $meta ) {
		if ( ( $cam[ $field ] ?? '' ) === 'yes' ) {
			$icons[] = '<span title="' . esc_attr( $meta[1] ) . '">' . $meta[0] . '</span>';
		}
	}

	echo ! empty( $icons ) ? wp_kses_post( implode( ' ', $icons ) ) : '<span class="mtcam-text-muted">—</span>';
}

/**
 * Render action buttons for camera table row (Edit, Bait, Delete).
 *
 * @param string $cam_id    Camera ID.
 * @param array  $cam       Camera data.
 * @param string $zone_name Zone name if camera is in a zone, empty otherwise (PRO).
 */
function mtcam_render_actions_cell( $cam_id, $cam, $extra_label = '' ) {
	// Edit button.
	echo '<a href="' . esc_url( wp_nonce_url( admin_url( 'admin.php?page=mtcam-dashboard&edit=' . $cam_id ), 'mtcam_edit_camera' ) ) . '" class="button button-small mtcam-mr-5">';
	echo '✏️ ';
	esc_html_e( 'Edit', 'my-trail-camera' );
	echo '</a>';

	// Bait download (non-stolen only).
	if ( empty( $cam['stolen_date'] ) ) {
		echo '<form method="post" style="display:inline;">';
		wp_nonce_field( 'mtcam_generate_bait_' . $cam_id );
		echo '<input type="hidden" name="action" value="generate_bait">';
		echo '<input type="hidden" name="cam_id" value="' . esc_attr( $cam_id ) . '">';

		$bait_gen = $cam['bait_generated'] ?? '';
		$bait_old = ! empty( $bait_gen ) && ( time() - strtotime( $bait_gen ) ) > 180 * 86400;
		$bait_title = __( 'Download bait files for SD card', 'my-trail-camera' );
		if ( $bait_old ) {
			/* translators: %s: date when bait files were last generated */
			$bait_title .= ' — ' . sprintf( __( 'Last generated: %s (outdated!)', 'my-trail-camera' ), mtcam_format_date( $bait_gen ) );
		} elseif ( ! empty( $bait_gen ) ) {
			/* translators: %s: date when bait files were last generated */
			$bait_title .= ' — ' . sprintf( __( 'Last generated: %s', 'my-trail-camera' ), mtcam_format_date( $bait_gen ) );
		}

		echo '<button type="submit" class="button button-small' . ( $bait_old ? ' mtcam-bait-outdated' : '' ) . '" title="' . esc_attr( $bait_title ) . '">🪤';
		if ( $bait_old ) {
			echo ' <span style="color:#d63638;">!</span>';
		}
		echo '</button>';
		echo '</form>';

	}

	// Delete button.
	$del_confirm = __( 'Are you sure you want to delete this camera?', 'my-trail-camera' );

	echo '<form method="post" style="display:inline;" data-mtcam-confirm="' . esc_attr( $del_confirm ) . '">';
	wp_nonce_field( 'delete_custom_camera_' . $cam_id );
	echo '<input type="hidden" name="action" value="delete_custom">';
	echo '<input type="hidden" name="cam_id" value="' . esc_attr( $cam_id ) . '">';
	echo '<input type="hidden" name="from" value="dashboard">';
	echo '<button type="submit" class="button button-small">🗑️ ';
	esc_html_e( 'Delete', 'my-trail-camera' );
	echo '</button>';
	echo '</form>';
}

// ============================================================================
// AJAX: Check duplicate camera ID
// ============================================================================

add_action( 'wp_ajax_mtcam_check_cam_id', 'mtcam_ajax_check_cam_id' );

/**
 * AJAX handler — check if a camera ID already exists.
 */
function mtcam_ajax_check_cam_id() {
    check_ajax_referer( 'mtcam_cam_id_nonce' );
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( '', 403 );
    }

    $cam_id = strtoupper( sanitize_text_field( wp_unslash( $_POST['cam_id'] ?? '' ) ) );
    if ( empty( $cam_id ) ) {
        wp_send_json_success( array( 'exists' => false ) );
    }

    wp_send_json_success( array( 'exists' => mtcam_camera_exists( $cam_id ) ) );
}

