<?php
/**
 * MTC - Import/Export Service
 * Import backup logic.
 *
 * @package My Trail Camera
 * @since 8.2.0
 */

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

class Mtcam_Import_Export_Service {

    /** @var My_Trail_Camera Main plugin instance. */
    private $tracker;

    public function __construct($tracker) {
        $this->tracker = $tracker;
    }

    /**
     * Process backup import from POST data.
     * Returns true on success, false on error, null if import was not requested.
     */
    public function process_import() {
        if (!isset($_POST['mtcam_import_submit']) || !isset($_POST['mtcam_import_data'])) {
            return null;
        }

        check_admin_referer('mtcam_settings');

        $raw_json = wp_unslash( $_POST['mtcam_import_data'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON string, sanitized per-field after decoding below
        $import = json_decode( $raw_json, true );

        if (!$import || !isset($import['cameras']) || !isset($import['settings'])) {
            wp_safe_redirect( wp_nonce_url( admin_url( 'admin.php?page=mtcam-settings&import_error=1' ), 'mtcam_settings_notice' ) );
            exit;
        }

        // Cameras
        foreach ($import['cameras'] as $cam_id => $cam_data) {
            $cam_id = sanitize_text_field($cam_id);
            if (empty($cam_id) || !is_array($cam_data)) continue;
            $cam_data = array_map(function($v) {
                return is_array($v) ? array_map('sanitize_text_field', $v) : sanitize_text_field($v);
            }, $cam_data);
            mtcam_save_camera($cam_id, $cam_data);
        }

        // File tokens — bait file authentication for already-deployed SD cards
        if (!empty($import['file_tokens']) && is_array($import['file_tokens'])) {
            global $wpdb;
            $tokens_table = $wpdb->prefix . 'mtcam_file_tokens';
            mtcam_db_query( 'TRUNCATE TABLE `' . $tokens_table . '`' );
            foreach ($import['file_tokens'] as $row) {
                if (!is_array($row) || empty($row['cam_id']) || empty($row['file_token'])) continue;
                mtcam_db_insert($tokens_table, array(
                    'cam_id'     => sanitize_text_field($row['cam_id']),
                    'file_token' => sanitize_text_field($row['file_token']),
                    'file_name'  => sanitize_text_field($row['file_name'] ?? ''),
                    'created_at' => !empty($row['created_at']) ? sanitize_text_field($row['created_at']) : current_time('mysql'),
                ));
            }
        }

        // Detections — preserve IDs so phone log_id references stay valid
        if (!empty($import['detections']) && is_array($import['detections'])) {
            global $wpdb;
            $det_table = $wpdb->prefix . 'mtcam_detections';
            mtcam_db_query( 'TRUNCATE TABLE `' . $det_table . '`' );
            wp_cache_delete( 'mtcam_total_records' );
            $det_text_cols = array('time', 'ip', 'lat', 'lon', 'acc', 'device_id', 'file_name', 'file_type', 'sys_user', 'os_info', 'ram_info', 'screen_res', 'timezone', 'cpu_cores', 'isp_info');
            foreach ($import['detections'] as $row) {
                if (!is_array($row) || empty($row['id'])) continue;
                $insert = array('id' => intval($row['id']));
                foreach ($det_text_cols as $col) {
                    $insert[$col] = isset($row[$col]) ? sanitize_text_field($row[$col]) : '';
                }
                $insert['ua']         = isset($row['ua']) ? sanitize_textarea_field($row['ua']) : '';
                $insert['extra_data'] = isset($row['extra_data']) ? sanitize_textarea_field($row['extra_data']) : '';
                mtcam_db_insert($det_table, $insert);
            }
        }

        // Location reviews — direct insert to preserve weather_data snapshot,
        // technical_issue flag, and stored score/rating (which depend on weather)
        if (!empty($import['location_reviews']) && is_array($import['location_reviews']) && function_exists('mtcam_locations_table')) {
            global $wpdb;
            $loc_table = $wpdb->prefix . 'mtcam_location_reviews';
            mtcam_db_query( 'TRUNCATE TABLE `' . $loc_table . '`' );
            wp_cache_delete( 'mtcam_location_reviews_all' );
            wp_cache_delete( 'mtcam_location_reviews_stats' );
            foreach ($import['location_reviews'] as $lr) {
                if (!is_array($lr)) continue;
                $row = array(
                    'cam_id'             => sanitize_text_field($lr['cam_id'] ?? ''),
                    'location_name'      => sanitize_text_field($lr['location_name'] ?? ''),
                    'gps_lat'            => sanitize_text_field($lr['gps_lat'] ?? ''),
                    'gps_lon'            => sanitize_text_field($lr['gps_lon'] ?? ''),
                    'start_date'         => sanitize_text_field($lr['start_date'] ?? ''),
                    'end_date'           => sanitize_text_field($lr['end_date'] ?? ''),
                    'days_count'         => intval($lr['days_count'] ?? 0),
                    'total_videos'       => intval($lr['total_videos'] ?? 0),
                    'interesting_videos' => intval($lr['interesting_videos'] ?? 0),
                    'people_count'       => intval($lr['people_count'] ?? 0),
                    'satisfaction'       => intval($lr['satisfaction'] ?? 3),
                    'score'              => floatval($lr['score'] ?? 0),
                    'rating'             => sanitize_text_field($lr['rating'] ?? 'C'),
                    'notes'              => sanitize_textarea_field($lr['notes'] ?? ''),
                    'weather_data'       => isset($lr['weather_data']) ? wp_kses_post( (string) $lr['weather_data'] ) : '',
                    'profile'            => sanitize_text_field($lr['profile'] ?? ''),
                    'created_at'         => !empty($lr['created_at']) ? sanitize_text_field($lr['created_at']) : current_time('mysql'),
                );
                mtcam_db_insert($loc_table, $row);
            }
        }

        // Custom profiles
        if (isset($import['custom_profiles']) && is_array($import['custom_profiles'])) {
            $sanitized_profiles = array();
            foreach ($import['custom_profiles'] as $key => $profile) {
                $skey = sanitize_text_field($key);
                $sanitized_profiles[$skey] = is_array($profile)
                    ? array_map('sanitize_text_field', $profile)
                    : sanitize_text_field($profile);
            }
            update_option('mtcam_custom_profiles', $sanitized_profiles);
        }

        // Settings
        $setting_map = array(
            'notifications'           => 'mtcam_notifications',
            'notify_email'            => 'mtcam_notify_email',
            'custom_text'             => 'mtcam_email_custom_text',
            'show_ip'                 => 'mtcam_show_ip',
            'show_photo'              => 'mtcam_show_photo',
            'show_battery_stolen'     => 'mtcam_show_battery_stolen',
            'ip_source'               => 'mtcam_ip_source',
            'data_retention'          => 'mtcam_data_retention',
            'gps_required'            => 'mtcam_gps_required',
            'manage_other_cameras'    => 'mtcam_manage_other_cameras',
            'auto_mark_stolen'        => 'mtcam_auto_mark_stolen',
            'theft_alert_radius'      => 'mtcam_theft_alert_radius',
            'auto_report'             => 'mtcam_auto_report',
            'weather_check_frequency' => 'mtcam_weather_check_frequency',
            'isp_lookup_enabled'      => 'mtcam_isp_lookup_enabled',
            'email_enabled'           => 'mtcam_email_enabled',
            'email_imap_host'         => 'mtcam_email_imap_host',
            'email_imap_port'         => 'mtcam_email_imap_port',
            'email_imap_encryption'   => 'mtcam_email_imap_encryption',
            'email_imap_user'         => 'mtcam_email_imap_user',
            'email_allowed_senders'   => 'mtcam_email_allowed_senders',
            'email_pin'               => '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;
                $setting_map[$key] = 'mtcam_' . $key;
            }
        }
        $setting_map['public_stolen_show_police'] = 'mtcam_public_stolen_show_police';

        foreach ($setting_map as $key => $option_name) {
            if (isset($import['settings'][$key])) {
                update_option($option_name, sanitize_text_field($import['settings'][$key]));
            }
        }

        wp_safe_redirect( wp_nonce_url( admin_url( 'admin.php?page=mtcam-settings&import_success=1' ), 'mtcam_settings_notice' ) );
        exit;
    }
}
