<?php

/**
 * @package CsvImporterPlusforACF
 */

namespace CIPFA\base;

use League\Csv\Reader;


// make sure we don't expose any info if called directly
if (!defined('ABSPATH')) exit; // Exit if accessed directly

class CIPFA_CsvImporter
{

   public static function cipfa_register()
   {
      add_action('init', array(__CLASS__, 'cipfa_initialize_import_count'));
      add_action('wp_ajax_cipfa_data', array(__CLASS__, 'cipfa_data_ajax'));
   }

   // Initialize total imported posts count option
   public static function cipfa_initialize_import_count()
   {
      if (get_option('cipfa_total_imported_so_far') === false) {
         update_option('cipfa_total_imported_so_far', 0);
      }
   }

   // Function to handle CSV import AJAX request
   public static function cipfa_data_ajax()
   {
      // Check nonce
      check_ajax_referer('cipfa_nonce', 'cipfa_nonce_field');

      $mapping = isset($_POST['mapping']) ? array_map('sanitize_text_field', wp_unslash($_POST['mapping'])) : array();

      // Get selected post type
      $post_type = isset($_POST['post_type']) ? sanitize_text_field(wp_unslash($_POST['post_type'])) : 'post';

      // Get current chunk index
      $current_chunk = isset($_POST['current_chunk']) ? intval($_POST['current_chunk']) : 0;

      // Get the edit_existing flag
      $edit_existing = isset($_POST['edit_existing']) && $_POST['edit_existing'] === '1';

      // Get the flush_cache flag
      $flush_cache = get_option('cipfa_flush_cache') === 'yes';

      // Get chunk size from request or default to 10
      $chunk_size = isset($_POST['chunk_size']) ? intval($_POST['chunk_size']) : 10;
      $total_imported = 0;

      // Get CSV File
      $csv_file = get_option('cipfa_csv_file_path');

      // Get CSV data and mapping
      if (!isset($csv_file) || !file_exists($csv_file)) {
         wp_die(esc_html__('CSV file is missing.', 'csv-importer-plus-for-acf'));
      }

      // Reset total imported posts count at the start of a new import process
      if ($current_chunk === 0) {
         CIPFA_Logs::cipfa_clear_logs();
         update_option('cipfa_total_imported_so_far', 0);
         $upload_dir = wp_upload_dir();
         $duplicates_dir = trailingslashit($upload_dir['basedir']) . 'cipfa-duplicates/';
         // Delete duplicate file
         if (file_exists($duplicates_dir)) {
            $old_files = glob($duplicates_dir . '*.json');

            if (!empty($old_files)) {
               foreach ($old_files as $file) {
                  wp_delete_file($file);
               }
            }
         }
         delete_option('cipfa_duplicate_media_path');
         delete_option('cipfa_imported_categories');
         delete_option('cipfa_imported_tags');
         delete_option('cipfa_imported_user');
         self::cipfa_find_and_store_duplicates($csv_file);
      }

      // Get total imported posts count from options
      $cipfa_total_imported_so_far = get_option('cipfa_total_imported_so_far', 0);

      $csv = Reader::createFromPath($csv_file, 'r');
      $csv->setHeaderOffset(0);

      $headers = $csv->getHeader();

      // Clean column names
      $clean_headers = array_map(['CIPFA\base\CIPFA_FileHandler', 'cipfa_clean_column_name'], $headers);

      $records = [];
      foreach ($csv->getRecords() as $row) {
         $cleaned_row = [];
         foreach ($clean_headers as $i => $clean_key) {
            $value = array_values($row)[$i] ?? '';
            $cleaned_row[$clean_key] = $value;
         }
         $records[] = $cleaned_row;
      }

      // Calculate total chunks and get current chunk
      $total_records = count($records);
      $total_chunks = ceil($total_records / $chunk_size);

      $chunk = array_slice($records, $current_chunk * $chunk_size, $chunk_size);

      // Process the chunk if it's not empty
      if (!empty($chunk)) {
         // Process the chunk
         $total_imported_for_chunk = CIPFA_PostProcessor::cipfa_process_chunk($chunk, $mapping, $post_type, $edit_existing);
         $total_imported += $total_imported_for_chunk;

         // Update total imported count
         $cipfa_total_imported_so_far += $total_imported_for_chunk;

         // Save the updated total imported count back to options
         update_option('cipfa_total_imported_so_far', $cipfa_total_imported_so_far);

         // Increment the current chunk counter
         $current_chunk++;
      }

      // Log
      $logs = CIPFA_Logs::cipfa_get_logs();
      $log_count = count($logs);
      $display_limit = 10;
      $display_logs = array_slice($logs, 0, $display_limit, true);

      $html_log_list = '';
      if (!empty($display_logs)) {
         $html_log_list = '<ul class="list-disc pl-5">';
         foreach ($display_logs as $log) {
            $html_log_list .= '<li class="text-black text-sm">' . esc_html($log) . '</li>';
         }
         $html_log_list .= '</ul>';
      }

      // Log downloadable log file
      $upload_dir = wp_upload_dir();
      $log_dir = trailingslashit($upload_dir['basedir']) . 'cipfa-logs/';
      if (!file_exists($log_dir)) {
         wp_mkdir_p($log_dir);
      }

      $log_file = get_option('cipfa_current_log_path');
      if ($log_file && file_exists(dirname($log_file))) {
         file_put_contents($log_file, implode("\n", $logs));
      }

      // Log URL for download
      $log_download_url = trailingslashit($upload_dir['baseurl']) . 'cipfa-logs/' . basename($log_file);

      // Check if this is the last chunk
      $is_last_chunk = ($current_chunk) >= $total_chunks;

      // If it is the last chunk, reset the total imported count
      if ($is_last_chunk) {
         update_option('cipfa_total_imported_so_far', 0);
         update_option('cipfa_csv_file_path', '');
         if ($post_type === 'product' && function_exists('wc_update_product_lookup_tables')) {
            wc_update_product_lookup_tables();
            wc_delete_product_transients();
            \wc_cache_helper::invalidate_cache_group('products');
            delete_transient('wc_attribute_taxonomies');
         }
         if ($flush_cache) {
            wp_cache_flush();
         } else {
            wp_cache_set('last_changed', microtime(), 'posts');
            wp_cache_set('last_changed', microtime(), 'post_meta');

            wp_cache_delete('all_posts', 'posts');
            wp_cache_delete('recent_posts', 'posts');
            wp_cache_delete('get_pages', 'posts');
         }

         $imported_categories = get_option('cipfa_imported_categories', false);
         $imported_tags = get_option('cipfa_imported_tags', false);
         $imported_custom_taxonomies = get_option('cipfa_imported_custom_taxonomies', false);
         $imported_user = get_option('cipfa_imported_user', false);


         if ($imported_categories || $imported_tags || $imported_custom_taxonomies) {
            wp_cache_set('last_changed', microtime(), 'terms');
            wp_cache_set('last_changed', microtime(), 'term_meta');

            wp_cache_delete('all_ids', 'terms');
            wp_cache_delete('get_terms', 'terms');
            wp_cache_delete('get_term', 'terms');

            // Delete "_children" options for all taxonomies
            foreach (get_taxonomies([], 'names') as $taxonomy) {
               delete_option("{$taxonomy}_children");
            }
         }
         if ($imported_user) {
            wp_cache_set('last_changed', microtime(), 'users');
            wp_cache_set('last_changed', microtime(), 'user_meta');

            wp_cache_delete('all_users', 'users');
            wp_cache_delete('useremail', 'users');
            wp_cache_delete('userlogins', 'users');
         }
      }

      $success_message_template = esc_html__('posts imported successfully! Total chunks imported: ', 'csv-importer-plus-for-acf');
      $success_message = intval($cipfa_total_imported_so_far) . ' ' . $success_message_template . intval($total_chunks);

      // Send response back to the client after the chunk is processed
      wp_send_json_success(array(
         'cipfa_total_imported_so_far' => intval($cipfa_total_imported_so_far),
         'total_chunks' => intval($total_chunks),
         'current_chunk' => intval($current_chunk),
         'chunk_size' => intval($chunk_size),
         'message' => sanitize_text_field($success_message),
         'logs' => wp_kses_post($html_log_list),
         'log_download_url' => esc_url_raw($log_download_url),
         'log_count' => intval($log_count)
      ));
   }

   //Store duplicate media
   public static function cipfa_find_and_store_duplicates($csv_file)
   {
      $csv = Reader::createFromPath($csv_file, 'r');
      $file_pattern = '/\.(jpg|jpeg|png|gif|bmp|webp|ico|svg|txt|pdf|docx?|pptx?|odt|xls|xlsx|mp3|m4a|ogg|wav|mp4|mov|wmv|avi|mpg|ogv|3gp|webm|zip|tar|gz|woff2?|csv|json)$/i';

      $media_urls = [];
      $duplicate_media = [];

      foreach ($csv as $row) {
         foreach ($row as $value) {
            $value = esc_url_raw(trim($value));

            if (preg_match($file_pattern, $value)) {

               $validated_url =
                  CIPFA_PostProcessor::cipfa_validate_and_log_url($value);
               if (!$validated_url) {
                  continue;
               }

               if (isset($media_urls[$validated_url])) {
                  $duplicate_media[$validated_url] = '';
               } else {
                  $media_urls[$validated_url] = true;
               }
            }
         }
      }

      // Save duplicates to a JSON file if found
      if (!empty($duplicate_media)) {
         $upload_dir = wp_upload_dir();
         $dir = trailingslashit($upload_dir['basedir']) . 'cipfa-duplicates/';
         if (!file_exists($dir)) {
            wp_mkdir_p($dir);
         }

         $file = trailingslashit($dir) . 'duplicates-current.json';
         file_put_contents($file, wp_json_encode($duplicate_media, JSON_PRETTY_PRINT));
         update_option('cipfa_duplicate_media_path', $file, false);
      } else {
         delete_option('cipfa_duplicate_media_path');
      }

      return ['media' => $duplicate_media];
   }
}
