<?php
// Exit if accessed directly.
if (! defined('ABSPATH')) {
    exit;
}

if (! class_exists('INTEGRAZO_WCZO_Logs_Model')) {

    class INTEGRAZO_WCZO_Logs_Model
    {
        private $wpdb;
        private $table_name;

        public function __construct()
        {
            global $wpdb;
            $this->wpdb = $wpdb;
            $this->table_name = $wpdb->prefix . 'integrazo_wczo_logs';
        }
        public function add_log($integration_id, $category, $message, $submitted_data = '', $response_data = '', $retry_count = 0)
        {
            if (empty($integration_id) || empty($category)) {
                return false;
            }

            $data = [
                'integration_id' => $integration_id,
                'category'       => $category,
                'message'        => $message,
                'submitted_data' => maybe_serialize($submitted_data),
                'response_data'  => maybe_serialize($response_data),
                'retry_count'    => $retry_count,
                'created_at'     => current_time('mysql'),
                'updated_at'     => current_time('mysql'),
            ];

            $format = ['%d', '%s', '%s', '%s', '%s', '%d', '%s', '%s'];

            $inserted = $this->wpdb->insert($this->table_name, $data, $format);
            if ($category != "SUCCESS") {
                integrazo_wczo_send_error_log_details_email_by_log_id($this->wpdb->insert_id);
            }
            if ($inserted) {
                return $this->wpdb->insert_id; // Return last inserted ID
            } else {
                return false;
            }
        }
        public function update_log($log_id, $category = '', $message = '', $response_data = '')
        {
            if (empty($log_id)) {
                return false;
            }

            global $wpdb;

            $table_name = esc_sql($this->table_name);

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $retry_count = $wpdb->get_var(
                $wpdb->prepare(
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    "SELECT retry_count FROM `$table_name` WHERE id = %d",
                    $log_id
                )
            );

            if ($retry_count === null) {
                return false;
            }

            $new_retry_count = (int) $retry_count + 1;

            $data = [
                'category'      => $category,
                'message'       => $message,
                'response_data' => maybe_serialize($response_data),
                'retry_count'   => $new_retry_count,
                'updated_at'    => current_time('mysql'),
            ];

            $format = ['%s', '%s', '%s', '%d', '%s'];
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,
            $updated = $wpdb->update(
                $this->table_name,
                $data,
                ['id' => $log_id],
                $format,
                ['%d']
            );

            return $updated !== false;
        }


        // Retrieve an error log by ID
        public function get_error_log($id)
        {
            global $wpdb;

            // Sanitize the table name to ensure it’s safe.
            $table_name = esc_sql($this->table_name);

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $result = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d", intval($id)), OBJECT);


            return $result;
        }
        public function get_all_error_logs()
        {
            global $wpdb;

            // Get all records from the table without excluding any category
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching	
            $results = $wpdb->get_results(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                "SELECT * FROM {$this->table_name} ORDER BY updated_at DESC",
                ARRAY_A
            );

            return !empty($results) ? $results : [];
        }
        public function get_all_error_logs_with_timefilter($time_filter = '')
        {
            global $wpdb;

            $table_name = esc_sql($this->table_name);

            $query = "SELECT * FROM {$table_name}";
            $where_clauses = [];
            $query_params = [];

            $current_date = current_time('Y-m-d');

            switch ($time_filter) {
                case 'today':
                    $where_clauses[] = "DATE(created_at) = %s";
                    $query_params[] = $current_date;
                    break;
                case 'yesterday':
                    $where_clauses[] = "DATE(created_at) = DATE_SUB(%s, INTERVAL 1 DAY)";
                    $query_params[] = $current_date;
                    break;
                case 'last_7_days':
                    $where_clauses[] = "created_at >= DATE_SUB(%s, INTERVAL 7 DAY)";
                    $query_params[] = $current_date;
                    break;
                case 'last_30_days':
                    $where_clauses[] = "created_at >= DATE_SUB(%s, INTERVAL 30 DAY)";
                    $query_params[] = $current_date;
                    break;
            }

            if (!empty($where_clauses)) {
                $query .= " WHERE " . implode(' AND ', $where_clauses);
            }

            $query .= " ORDER BY updated_at DESC";

            // Prepare and fetch results
            if (!empty($query_params)) {
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
                $prepared_query = $wpdb->prepare($query, $query_params);
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $results = $wpdb->get_results($prepared_query, ARRAY_A);
            } else {
                // No params, safe to run directly
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared
                $results = $wpdb->get_results($query, ARRAY_A);
            }

            return $results ?: [];
        }

        /**
         * Get all unique integration IDs from the logs table.
         *
         * @return array List of unique integration IDs.
         */
        public function get_unique_integration_ids()
        {
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching	
            $results = $wpdb->get_col(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                "SELECT DISTINCT integration_id FROM {$this->table_name} ORDER BY integration_id ASC"
            );

            return !empty($results) ? array_map('intval', $results) : [];
        }

        /**
         * Get all unique error types (categories) from the logs table.
         *
         * @return array List of unique error categories.
         */
        public function get_unique_error_types()
        {
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching	
            $results = $wpdb->get_col(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                "SELECT DISTINCT category FROM {$this->table_name} ORDER BY category ASC"
            );

            return !empty($results) ? array_map('sanitize_text_field', $results) : [];
        }
        // Delete all error logs
        public function delete_all_error_logs()
        {
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            return $this->wpdb->query("DELETE FROM {$this->table_name}") !== false;
        }
        // Delete only records where error_type is "SUCCESS"
        public function delete_all_success_logs()
        {
            $table = $this->table_name;
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            return $this->wpdb->query("DELETE FROM {$table} WHERE category = 'SUCCESS'") !== false;
        }
        // Delete an error log by ID
        public function delete_error_log($id)
        {
            return $this->wpdb->delete(
                $this->table_name,
                ['id' => $id],
                ['%d']
            ) !== false;
        }
        /**
         * Delete logs older than a specific number of days.
         *
         * @param int $days Number of days to keep logs.
         * @return bool True if logs deleted, false on failure.
         */
        public function delete_old_logs($days)
        {
            if (! is_numeric($days) || $days <= 0) {
                return false;
            }

            $threshold_date = gmdate('Y-m-d H:i:s', strtotime("-{$days} days"));

            // Use prepare for safety.
            $query = $this->wpdb->prepare(
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                "DELETE FROM {$this->table_name} WHERE created_at < %s",
                $threshold_date
            );
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- already prepared above
            return $this->wpdb->query($query) !== false;
        }
    }
}
