__( 'Permission denied.', 'ahmadraza360-lead-manager' ) ) ); } if ( empty( $_FILES['csv_file']['tmp_name'] ) ) { wp_send_json_error( array( 'message' => __( 'Please select a valid CSV or JSON file to upload.', 'ahmadraza360-lead-manager' ) ) ); } $file = sanitize_text_field( wp_unslash( $_FILES['csv_file']['tmp_name'] ) ); $file_name = isset( $_FILES['csv_file']['name'] ) ? sanitize_text_field( wp_unslash( $_FILES['csv_file']['name'] ) ) : ''; $file_info = pathinfo( $file_name ); $ext = isset( $file_info['extension'] ) ? strtolower( $file_info['extension'] ) : ''; if ( ! in_array( $ext, array( 'csv', 'json' ), true ) ) { wp_send_json_error( array( 'message' => __( 'Only CSV (.csv) and JSON (.json) files are supported.', 'ahmadraza360-lead-manager' ) ) ); } $upload_dir = wp_upload_dir(); $import_dir = $upload_dir['basedir'] . '/ahmadraza360-lead-manager/imports'; if ( ! file_exists( $import_dir ) ) { wp_mkdir_p( $import_dir ); file_put_contents( $import_dir . '/index.php', '\ndeny from all\n" ); } $headers = array(); $preview_rows = array(); if ( 'json' === $ext ) { $raw_content = file_get_contents( $file ); $json_data = json_decode( $raw_content, true ); if ( ! is_array( $json_data ) ) { wp_send_json_error( array( 'message' => __( 'Invalid JSON structure. Please ensure the file contains valid JSON array records.', 'ahmadraza360-lead-manager' ) ) ); } // If wrapped in root object like { "leads": [...] } or { "data": [...] } if ( ! isset( $json_data[0] ) ) { foreach ( $json_data as $key => $sub_array ) { if ( is_array( $sub_array ) && isset( $sub_array[0] ) ) { $json_data = $sub_array; break; } } } if ( empty( $json_data ) || ! is_array( $json_data ) ) { wp_send_json_error( array( 'message' => __( 'No records found in uploaded JSON file.', 'ahmadraza360-lead-manager' ) ) ); } // Gather all unique keys across records $keys = array(); foreach ( $json_data as $item ) { if ( is_array( $item ) ) { $keys = array_merge( $keys, array_keys( $item ) ); } } $headers = array_values( array_unique( $keys ) ); // Build preview of up to 5 items $row_count = 0; foreach ( $json_data as $item ) { if ( $row_count >= 5 ) { break; } $row = array(); foreach ( $headers as $h ) { $val = isset( $item[ $h ] ) ? $item[ $h ] : ''; $row[] = is_array( $val ) ? wp_json_encode( $val ) : sanitize_text_field( (string) $val ); } $preview_rows[] = $row; $row_count++; } $temp_filename = 'import_' . uniqid() . '.json'; $temp_filepath = $import_dir . '/' . $temp_filename; if ( ! copy( $file, $temp_filepath ) ) { wp_send_json_error( array( 'message' => __( 'Failed to save temporary import file.', 'ahmadraza360-lead-manager' ) ) ); } } else { // CSV parsing $handle = fopen( $file, 'r' ); if ( ! $handle ) { wp_send_json_error( array( 'message' => __( 'Unable to open CSV file.', 'ahmadraza360-lead-manager' ) ) ); } // Check BOM $bom = fread( $handle, 3 ); if ( $bom !== "\xEF\xBB\xBF" ) { rewind( $handle ); } $raw_headers = fgetcsv( $handle, 0, ',' ); if ( empty( $raw_headers ) ) { fclose( $handle ); wp_send_json_error( array( 'message' => __( 'CSV file seems empty or invalid.', 'ahmadraza360-lead-manager' ) ) ); } $headers = array_map( 'trim', (array) $raw_headers ); $row_count = 0; while ( ( $row = fgetcsv( $handle, 0, ',' ) ) !== false && $row_count < 5 ) { $preview_rows[] = array_map( 'sanitize_text_field', (array) $row ); $row_count++; } fclose( $handle ); $temp_filename = 'import_' . uniqid() . '.csv'; $temp_filepath = $import_dir . '/' . $temp_filename; if ( ! copy( $file, $temp_filepath ) ) { wp_send_json_error( array( 'message' => __( 'Failed to save temporary import file.', 'ahmadraza360-lead-manager' ) ) ); } } wp_send_json_success( array( 'filepath' => $temp_filepath, 'headers' => $headers, 'preview' => $preview_rows, ) ); } /** * Run the CSV or JSON parsing, mapping, and database entries. */ public static function ajax_handle_run_import() { check_ajax_referer( 'ahmadraza360_lm_import_nonce', 'security' ); if ( ! Ahmadraza360_LM_Permissions::check( 'ahmadraza360_lm_import_submissions' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'ahmadraza360-lead-manager' ) ) ); } $filepath = isset( $_POST['filepath'] ) ? sanitize_text_field( wp_unslash( $_POST['filepath'] ) ) : ''; $mappings = isset( $_POST['mapping'] ) ? (array) $_POST['mapping'] : array(); $duplicates = isset( $_POST['duplicates'] ) ? sanitize_key( $_POST['duplicates'] ) : 'import_all'; $default_status = isset( $_POST['default_status'] ) ? sanitize_key( $_POST['default_status'] ) : 'new'; $default_priority = isset( $_POST['default_priority'] ) ? sanitize_key( $_POST['default_priority'] ) : 'medium'; $default_form_name = isset( $_POST['default_form_name'] ) ? sanitize_text_field( wp_unslash( $_POST['default_form_name'] ) ) : 'Imported Lead'; if ( empty( $filepath ) || ! file_exists( $filepath ) ) { wp_send_json_error( array( 'message' => __( 'Import file not found. Please upload again.', 'ahmadraza360-lead-manager' ) ) ); } $stats = array( 'success' => 0, 'skipped' => 0, 'errors' => 0, ); global $wpdb; $table_sub = Ahmadraza360_LM_Database::table( 'submissions' ); $table_fld = Ahmadraza360_LM_Database::table( 'fields' ); $current_user_id = get_current_user_id(); $statuses = Ahmadraza360_LM_Lead_Manager::get_statuses(); $priorities = Ahmadraza360_LM_Lead_Manager::get_priorities(); $ext = strtolower( pathinfo( $filepath, PATHINFO_EXTENSION ) ); if ( 'json' === $ext ) { $raw_content = file_get_contents( $filepath ); $json_data = json_decode( $raw_content, true ); if ( ! isset( $json_data[0] ) && is_array( $json_data ) ) { foreach ( $json_data as $sub_array ) { if ( is_array( $sub_array ) && isset( $sub_array[0] ) ) { $json_data = $sub_array; break; } } } if ( ! is_array( $json_data ) ) { wp_send_json_error( array( 'message' => __( 'Invalid JSON records to import.', 'ahmadraza360-lead-manager' ) ) ); } foreach ( $json_data as $row_data ) { if ( ! is_array( $row_data ) ) { continue; } self::process_import_row( $row_data, $mappings, $duplicates, $default_status, $default_priority, $default_form_name, $statuses, $priorities, $table_sub, $table_fld, $current_user_id, $stats ); } } else { $handle = fopen( $filepath, 'r' ); if ( ! $handle ) { wp_send_json_error( array( 'message' => __( 'Failed to open import file.', 'ahmadraza360-lead-manager' ) ) ); } $bom = fread( $handle, 3 ); if ( $bom !== "\xEF\xBB\xBF" ) { rewind( $handle ); } $headers = fgetcsv( $handle, 0, ',' ); $headers = array_map( 'trim', (array) $headers ); while ( ( $row = fgetcsv( $handle, 0, ',' ) ) !== false ) { $row_data = array(); foreach ( $headers as $index => $header_name ) { $row_data[ $header_name ] = isset( $row[ $index ] ) ? trim( $row[ $index ] ) : ''; } self::process_import_row( $row_data, $mappings, $duplicates, $default_status, $default_priority, $default_form_name, $statuses, $priorities, $table_sub, $table_fld, $current_user_id, $stats ); } fclose( $handle ); } // Remove temp file if ( file_exists( $filepath ) ) { @unlink( $filepath ); } // Save import history log $history = get_option( 'ahmadraza360_lm_import_history', array() ); $history[] = array( 'date' => current_time( 'mysql' ), 'filename' => basename( $filepath ), 'success' => $stats['success'], 'skipped' => $stats['skipped'], 'errors' => $stats['errors'], ); update_option( 'ahmadraza360_lm_import_history', array_slice( (array) $history, -10 ) ); wp_send_json_success( $stats ); } /** * Process a single data row and insert/update lead record. */ private static function process_import_row( $row_data, $mappings, $duplicates, $default_status, $default_priority, $default_form_name, $statuses, $priorities, $table_sub, $table_fld, $current_user_id, &$stats ) { global $wpdb; $name = isset( $mappings['name'] ) && isset( $row_data[ $mappings['name'] ] ) ? sanitize_text_field( (string) $row_data[ $mappings['name'] ] ) : 'Imported Lead'; $email = isset( $mappings['email'] ) && isset( $row_data[ $mappings['email'] ] ) ? sanitize_email( (string) $row_data[ $mappings['email'] ] ) : ''; $phone = isset( $mappings['phone'] ) && isset( $row_data[ $mappings['phone'] ] ) ? sanitize_text_field( (string) $row_data[ $mappings['phone'] ] ) : ''; $subject = isset( $mappings['subject'] ) && isset( $row_data[ $mappings['subject'] ] ) ? sanitize_text_field( (string) $row_data[ $mappings['subject'] ] ) : ''; $message = isset( $mappings['message'] ) && isset( $row_data[ $mappings['message'] ] ) ? sanitize_textarea_field( (string) $row_data[ $mappings['message'] ] ) : ''; $status = isset( $mappings['status'] ) && isset( $row_data[ $mappings['status'] ] ) ? sanitize_key( strtolower( (string) $row_data[ $mappings['status'] ] ) ) : $default_status; $priority = isset( $mappings['priority'] ) && isset( $row_data[ $mappings['priority'] ] ) ? sanitize_key( strtolower( (string) $row_data[ $mappings['priority'] ] ) ) : $default_priority; $created_at = isset( $mappings['date'] ) && ! empty( $row_data[ $mappings['date'] ] ) ? sanitize_text_field( (string) $row_data[ $mappings['date'] ] ) : current_time( 'mysql' ); $form_title = isset( $mappings['form_title'] ) && ! empty( $row_data[ $mappings['form_title'] ] ) ? sanitize_text_field( (string) $row_data[ $mappings['form_title'] ] ) : $default_form_name; if ( ! isset( $statuses[ $status ] ) ) { $status = $default_status; } if ( ! isset( $priorities[ $priority ] ) ) { $priority = $default_priority; } $created_timestamp = strtotime( $created_at ); $valid_created_at = $created_timestamp ? gmdate( 'Y-m-d H:i:s', $created_timestamp ) : current_time( 'mysql' ); // Duplicate Check by email if ( 'import_all' !== $duplicates && ! empty( $email ) ) { $duplicate_id = $wpdb->get_var( $wpdb->prepare( "SELECT sub.id FROM $table_sub sub INNER JOIN $table_fld fld ON sub.id = fld.submission_id WHERE fld.field_key = '_lead_email' AND fld.field_value = %s LIMIT 1", $email ) ); if ( $duplicate_id ) { if ( 'skip' === $duplicates ) { $stats['skipped']++; return; } elseif ( 'overwrite' === $duplicates ) { $wpdb->update( $table_sub, array( 'status' => $status, 'priority' => $priority, 'created_at' => $valid_created_at, ), array( 'id' => $duplicate_id ) ); $wpdb->update( $table_fld, array( 'field_value' => $name ), array( 'submission_id' => $duplicate_id, 'field_key' => '_lead_name' ) ); $wpdb->update( $table_fld, array( 'field_value' => $phone ), array( 'submission_id' => $duplicate_id, 'field_key' => '_lead_phone' ) ); $wpdb->update( $table_fld, array( 'field_value' => $subject ), array( 'submission_id' => $duplicate_id, 'field_key' => '_lead_subject' ) ); $wpdb->update( $table_fld, array( 'field_value' => $message ), array( 'submission_id' => $duplicate_id, 'field_key' => '_lead_message' ) ); Ahmadraza360_LM_Database::log_activity( $duplicate_id, $current_user_id, 'imported_update', 'Lead updated via import wizard.' ); $stats['success']++; return; } } } $sub_payload = array( 'form_id' => 0, 'form_title' => $form_title, 'status' => $status, 'priority' => $priority, 'is_spam' => 0, 'ip_address' => '', 'user_agent' => 'Import Engine', 'page_url' => '', 'referrer' => '', 'created_at' => $valid_created_at, ); $fields_payload = array( '_lead_name' => $name, '_lead_email' => $email, '_lead_phone' => $phone, '_lead_subject' => $subject, '_lead_message' => $message, ); // Append any unmapped extra columns $mapped_cols = array_values( array_filter( $mappings ) ); foreach ( $row_data as $h => $v ) { if ( ! in_array( $h, $mapped_cols, true ) ) { $fields_payload[ $h ] = is_array( $v ) ? wp_json_encode( $v ) : (string) $v; } } $inserted_id = Ahmadraza360_LM_Database::insert_submission( $sub_payload, $fields_payload ); if ( $inserted_id ) { Ahmadraza360_LM_Database::log_activity( $inserted_id, $current_user_id, 'imported', 'Lead created via import wizard.' ); $stats['success']++; } else { $stats['errors']++; } } }