<?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

class CIPFA_Logs
{
   private static $enable_log_option_key = 'cipfa_enable_log';
   private static $log_file_name = 'cipfa-import-log.txt';
   private static $hash_file_name = 'cipfa-import-log-hashes.json';
   private static $logged_messages_cache = [];

   // Get path to the log file
   private static function cipfa_get_log_file_path()
   {
      $upload_dir = wp_upload_dir();
      $log_dir = trailingslashit($upload_dir['basedir']) . 'cipfa-logs';

      // Create directory if missing
      if (!file_exists($log_dir)) {
         wp_mkdir_p($log_dir);
      }

      $log_file = trailingslashit($log_dir) . self::$log_file_name;
      update_option('cipfa_current_log_path', $log_file, false);

      return $log_file;
   }

   // Get path to the hash file
   private static function cipfa_get_hash_file_path()
   {
      $upload_dir = wp_upload_dir();
      $log_dir = trailingslashit($upload_dir['basedir']) . 'cipfa-logs';

      if (!file_exists($log_dir)) {
         wp_mkdir_p($log_dir);
      }

      return trailingslashit($log_dir) . self::$hash_file_name;
   }

   // Log a message
   public static function cipfa_Log($message)
   {
      $enable_logging = get_option(self::$enable_log_option_key);
      if ($enable_logging !== 'yes') {
         return;
      }

      $hash = sha1($message);

      if (isset(self::$logged_messages_cache[$hash])) {
         return;
      }
      self::$logged_messages_cache[$hash] = true;

      $hash_file = self::cipfa_get_hash_file_path();
      $log_file  = self::cipfa_get_log_file_path();

      static $existing_hashes = null;
      if ($existing_hashes === null) {

         // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_file_get_contents
         // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_file_exists

         if (file_exists($hash_file)) {
            $json = file_get_contents($hash_file);
            $existing_hashes = json_decode($json, true);
            if (!is_array($existing_hashes)) {
               $existing_hashes = [];
            }
         } else {
            $existing_hashes = [];
         }

         // phpcs:enable
      }

      if (isset($existing_hashes[$hash])) {
         return;
      }

      $existing_hashes[$hash] = true;

      // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
      file_put_contents($hash_file, json_encode($existing_hashes), LOCK_EX);
      // phpcs:enable

      $timestamp = current_time('mysql');
      $formatted_message = "[$timestamp] $message" . PHP_EOL;

      // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_file_exists
      // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen
      // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fclose
      // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_filesize
      if (file_exists($log_file) && filesize($log_file) > 0) {

         $fh = fopen($log_file, 'rb');
         fseek($fh, -1, SEEK_END);
         $last_char = fgetc($fh);
         fclose($fh);

         if ($last_char !== "\n" && $last_char !== "\r") {
            $formatted_message = PHP_EOL . $formatted_message;
         }
      }
      // phpcs:enable

      // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
      file_put_contents($log_file, $formatted_message, FILE_APPEND | LOCK_EX);
      // phpcs:enable
   }

   // Retrieve all logs as an array
   public static function cipfa_get_logs()
   {
      $log_file = self::cipfa_get_log_file_path();

      if (!file_exists($log_file)) {
         return [];
      }

      $lines = file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      return is_array($lines) ? $lines : [];
   }

   // Clear logs and hash file
   public static function cipfa_clear_logs()
   {
      $log_file = self::cipfa_get_log_file_path();
      $hash_file = self::cipfa_get_hash_file_path();

      if (file_exists($log_file)) {
         wp_delete_file($log_file);
      }

      if (file_exists($hash_file)) {
         wp_delete_file($hash_file);
      }

      delete_option('cipfa_current_log_path');
      self::$logged_messages_cache = [];
   }
}
