<?php
/**
 * MTC - Camera maintenance and backup
 * AJAX export, orphan cleanup.
 * @package My Trail Camera
 * @since 8.1.0
 */

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

// ============================================================================
// AJAX EXPORT — fresh data from DB (not cached from page load)
// ============================================================================

add_action('wp_ajax_mtcam_export_backup', 'mtcam_ajax_export_backup');

/**
 * AJAX handler for backup export — always fresh data from DB
 */
function mtcam_ajax_export_backup() {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('Insufficient permissions.', 'my-trail-camera'), 403);
    }

    check_ajax_referer('mtcam_export_backup');

    global $wpdb;

    // Invalidate cache — we want fresh data
    mtcam_invalidate_cameras_cache();

    $settings = array(
        'notifications'           => get_option('mtcam_notifications', 'yes'),
        'notify_email'            => get_option('mtcam_notify_email', ''),
        'custom_text'             => get_option('mtcam_email_custom_text', ''),
        'show_ip'                 => get_option('mtcam_show_ip', 'yes'),
        'show_photo'              => get_option('mtcam_show_photo', 'yes'),
        'show_battery_stolen'     => get_option('mtcam_show_battery_stolen', 'yes'),
        'ip_source'               => get_option('mtcam_ip_source', 'remote_addr'),
        'data_retention'          => get_option('mtcam_data_retention', 90),
        'gps_required'            => get_option('mtcam_gps_required', 'no'),
        'manage_other_cameras'    => get_option('mtcam_manage_other_cameras', 'no'),
        'auto_mark_stolen'        => get_option('mtcam_auto_mark_stolen', 'yes'),
        'theft_alert_radius'      => get_option('mtcam_theft_alert_radius', '1'),
        'auto_report'             => get_option('mtcam_auto_report', 'no'),
        'weather_check_frequency' => get_option('mtcam_weather_check_frequency', '1'),
        'isp_lookup_enabled'      => get_option('mtcam_isp_lookup_enabled', 'yes'),
        'email_enabled'           => get_option('mtcam_email_enabled', 'no'),
        'email_imap_host'         => get_option('mtcam_email_imap_host', ''),
        'email_imap_port'         => get_option('mtcam_email_imap_port', '993'),
        'email_imap_encryption'   => get_option('mtcam_email_imap_encryption', 'ssl'),
        'email_imap_user'         => get_option('mtcam_email_imap_user', ''),
        'email_allowed_senders'   => get_option('mtcam_email_allowed_senders', ''),
        'email_pin'               => get_option('mtcam_email_pin', ''),
    );

    // Public widget visibility — all fields for stolen + active widgets
    $widget_fields = array('name', 'manufacturer', 'imei', 'location', 'gps', 'dates', 'baits', 'security', 'gps_trackers', 'photo');
    foreach (array('stolen', 'active') as $widget_type) {
        foreach ($widget_fields as $field) {
            $key = 'public_' . $widget_type . '_show_' . $field;
            $settings[$key] = get_option('mtcam_' . $key, '');
        }
    }
    $settings['public_stolen_show_police'] = get_option('mtcam_public_stolen_show_police', 'yes');

    $detections = mtcam_db_get_results(
        'SELECT * FROM `' . $wpdb->prefix . 'mtcam_detections` ORDER BY id ASC',
        ARRAY_A
    );

    $file_tokens = mtcam_db_get_results(
        'SELECT cam_id, file_token, file_name, created_at FROM `' . $wpdb->prefix . 'mtcam_file_tokens` ORDER BY id ASC',
        ARRAY_A
    );

    $data = array(
        'version'     => defined('MTCAM_VERSION') ? MTCAM_VERSION : '?',
        'exported'    => current_time('c'),
        'cameras'     => mtcam_get_cameras(),
        'settings'    => $settings,
        'detections'  => $detections ? $detections : array(),
        'file_tokens' => $file_tokens ? $file_tokens : array(),
        'location_reviews' => function_exists('mtcam_location_reviews_get_all') ? mtcam_location_reviews_get_all() : array(),
        'custom_profiles'  => get_option('mtcam_custom_profiles', array()),
    );

    wp_send_json_success($data);
}

// ============================================================================
// ORPHAN CLEANUP — orphaned records from deleted cameras
// ============================================================================

/**
 * Count orphaned records for cameras that no longer exist
 *
 * @param array $existing_ids List of existing cam_id values
 * @return array Counts of orphaned records
 */
function mtcam_count_orphaned_records($existing_ids) {
    global $wpdb;

    $result = array('reviews' => 0, 'detections' => 0, 'total' => 0);

    if (empty($existing_ids)) {
        $result['reviews']    = intval( mtcam_db_get_var( 'SELECT COUNT(*) FROM `' . $wpdb->prefix . 'mtcam_location_reviews`' ) );
        $result['detections'] = intval( mtcam_db_get_var( 'SELECT COUNT(*) FROM `' . $wpdb->prefix . 'mtcam_detections`' ) );
        $result['total'] = $result['reviews'] + $result['detections'];
        return $result;
    }

    $result['reviews'] = intval( mtcam_db_get_var( $wpdb->prepare(
        'SELECT COUNT(*) FROM `' . $wpdb->prefix . 'mtcam_location_reviews` WHERE cam_id NOT IN ('
        . implode( ',', array_fill( 0, count( $existing_ids ), '%s' ) ) . ')',
        ...$existing_ids
    ) ) );

    $result['detections'] = intval( mtcam_db_get_var( $wpdb->prepare(
        'SELECT COUNT(*) FROM `' . $wpdb->prefix . 'mtcam_detections` WHERE device_id NOT IN ('
        . implode( ',', array_fill( 0, count( $existing_ids ), '%s' ) ) . ')',
        ...$existing_ids
    ) ) );

    $result['total'] = $result['reviews'] + $result['detections'];
    return $result;
}

/**
 * Delete all orphaned records for cameras that no longer exist
 *
 * @param array $existing_ids List of existing cam_id values
 * @return array Counts of deleted records
 */
function mtcam_cleanup_orphaned_records($existing_ids) {
    global $wpdb;

    $deleted = array('reviews' => 0, 'detections' => 0);

    if (empty($existing_ids)) {
        $deleted['reviews']    = intval( mtcam_db_get_var( 'SELECT COUNT(*) FROM `' . $wpdb->prefix . 'mtcam_location_reviews`' ) );
        $deleted['detections'] = intval( mtcam_db_get_var( 'SELECT COUNT(*) FROM `' . $wpdb->prefix . 'mtcam_detections`' ) );

        mtcam_db_query( 'TRUNCATE TABLE `' . $wpdb->prefix . 'mtcam_location_reviews`' );

        mtcam_cleanup_orphan_detections_all($wpdb, $deleted);

        return $deleted;
    }

    $all_rv = mtcam_db_get_col( 'SELECT DISTINCT cam_id FROM `' . $wpdb->prefix . 'mtcam_location_reviews`' );
    foreach ( array_diff( $all_rv, $existing_ids ) as $oid ) {
        $deleted['reviews'] += intval( mtcam_db_delete( $wpdb->prefix . 'mtcam_location_reviews', array( 'cam_id' => $oid ) ) );
    }

    $all_dt    = mtcam_db_get_col( 'SELECT DISTINCT device_id FROM `' . $wpdb->prefix . 'mtcam_detections`' );
    $orphan_dt = array_diff( $all_dt, $existing_ids );
    if ( ! empty( $orphan_dt ) ) {
        $orphan_log_ids = mtcam_db_get_col( $wpdb->prepare(
            'SELECT id FROM `' . $wpdb->prefix . 'mtcam_detections` WHERE device_id IN ('
            . implode( ',', array_fill( 0, count( $orphan_dt ), '%s' ) ) . ')',
            ...array_values($orphan_dt)
        ));

        $deleted['detections'] = intval( mtcam_db_query( $wpdb->prepare(
            'DELETE FROM `' . $wpdb->prefix . 'mtcam_detections` WHERE device_id IN ('
            . implode( ',', array_fill( 0, count( $orphan_dt ), '%s' ) ) . ')',
            ...array_values($orphan_dt)
        )));
    }

    return $deleted;
}

/**
 * Helper: delete all detections when there are no cameras
 */
function mtcam_cleanup_orphan_detections_all($wpdb, &$deleted) {
    mtcam_db_query( 'TRUNCATE TABLE `' . $wpdb->prefix . 'mtcam_detections`' );
}
