<?php

/**
 * @package CsvImporterPlusforACF
 */

namespace CIPFA\base;

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

use DateTime;

class CIPFA_ACFSanitizer
{
   public static function cipfa_sanitize_acf_data($acf_data, $registered_map = [])
   {
      if (!is_array($acf_data)) {
         return array();
      }

      $sanitized_acf_data = array();
      $date_formats = ['d/m/Y', 'm/d/Y', 'F j, Y', 'Y-m-d'];

      foreach ($acf_data as $key => $value) {
         // Get the field object
         $field = acf_get_field($key);
         if (!$field) {
            // Handle case where acf field is not found
            continue;
         }
         $field_type = $field['type'];

         switch ($field_type) {
            case 'text':
            case 'textarea':
               $sanitized_acf_data[$key] = sanitize_text_field($value);
               break;
            case 'email':
               $sanitized_acf_data[$key] = sanitize_email($value);
               break;
            case 'url':
               $sanitized_acf_data[$key] = esc_url_raw($value);
               break;
            case 'number':
               $sanitized_acf_data[$key] = floatval($value);
               break;
            case 'range':
               $sanitized_acf_data[$key] = intval($value);
               break;
            case 'password':
               $sanitized_acf_data[$key] = sanitize_text_field($value);
               break;
            case 'image':
               if (is_array($value)) {
                  foreach ($value as $subkey => $subvalue) {
                     if (is_numeric($subvalue)) {
                        $sanitized_acf_data[$key][$subkey] = intval($subvalue);
                     } else {
                        $sanitized_acf_data[$key][$subkey] = CIPFA_PostProcessor::cipfa_find_attachment_id($subvalue, $registered_map);
                     }
                  }
               } else {
                  if (is_numeric($value)) {
                     $sanitized_acf_data[$key] = intval($value);
                  } else {
                     $sanitized_acf_data[$key] = CIPFA_PostProcessor::cipfa_find_attachment_id($value, $registered_map);
                  }
               }
               break;
            case 'select':
               $is_multiple = isset($field['multiple']) && $field['multiple'];
               if ($is_multiple) {
                  if (is_string($value) && strpos($value, ',') !== false) {
                     $value = array_map('trim', explode(',', $value));
                  }

                  $value = is_array($value) ? $value : array($value);
                  $sanitized_acf_data[$key] = array_filter(array_map('sanitize_text_field', $value));
               } else {
                  if (is_array($value)) {
                     $value = reset($value);
                  } elseif (is_string($value) && strpos($value, ',') !== false) {
                     $parts = array_map('trim', explode(',', $value));
                     $value = reset($parts);
                  }
                  $sanitized_acf_data[$key] = sanitize_text_field($value);
               }
               break;
            case 'boolean':
               $sanitized_acf_data[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
               break;
            case 'date_picker':
               $value = trim((string)$value);
               $date_obj = false;
               foreach ($date_formats as $format) {
                  $date_obj = DateTime::createFromFormat($format, $value);
                  if ($date_obj instanceof DateTime) {
                     $errors = DateTime::getLastErrors();
                     if (
                        $errors === false ||
                        ($errors['warning_count'] === 0 && $errors['error_count'] === 0)
                     ) {
                        $sanitized_acf_data[$key] = $date_obj->format('Ymd');
                        break;
                     }
                  }

                  $date_obj = false;
               }
               if (!$date_obj) {
                  $timestamp = strtotime($value);

                  if ($timestamp !== false) {
                     $sanitized_acf_data[$key] = wp_date('Ymd', $timestamp);
                  } else {
                     $sanitized_acf_data[$key] = '';
                  }
               }
               break;
            default:
               // Default sanitization
               $sanitized_acf_data[$key] = sanitize_text_field($value);
               break;
         }
      }
      return $sanitized_acf_data;
   }
}
