<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Create error log table
 * NOTE: Call this from main plugin file on activation
 * @Since 1.0.0
 */

function gshfjf_create_error_log_table()
{
    global $wpdb;

    $table = $wpdb->prefix . 'gshfjf_error_logs';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE {$table} (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        error_id VARCHAR(191) NOT NULL,
        code INT NOT NULL,
        message TEXT NOT NULL,
        details LONGTEXT NULL,
        created_at DATETIME NOT NULL,
        PRIMARY KEY (id),
        KEY error_id (error_id),
        KEY code (code)
    ) {$charset};";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql);
}

if (!class_exists('GSHFJF_JetForm_Error_Logs')) {

    class GSHFJF_JetForm_Error_Logs
    {

        public function __construct()
        {

            //Clear logs action
            add_action('admin_post_gshfjf_jetform_clear_logs', [$this, 'gshfjf_jetform_clear_logs']);

            // Download logs action
            add_action('admin_post_gshfjf_download_logs', [$this, 'gshfjf_download_logs']);
        }

        /**
         * STATIC ENTRY POINT
         * @Since 1.0.0
         */

        public static function gshfjf_render_page()
        {
            (new self())->gshfjf_render_page_html();
        }

        /**
         * MAIN DB LOGGER
         * @Since 1.0.0
         */

        public static function log_to_db($error_id, $code, $message, $details = [])
        {
            global $wpdb;

            $table = $wpdb->prefix . 'gshfjf_error_logs';

            if ($wpdb->get_var(
                $wpdb->prepare(
                    "SHOW TABLES LIKE %s",
                    $wpdb->prefix . 'gshfjf_error_logs'
                )
            ) !== $wpdb->prefix . 'gshfjf_error_logs') {
                return false;
            }

            // 🔥 IMPORTANT FIX START
            if (is_string($details)) {
                $decoded = json_decode($details, true);

                if (json_last_error() === JSON_ERROR_NONE) {
                    $details = $decoded; // already JSON → convert to array
                } else {
                    $details = ['raw_error' => $details];
                }
            }
            // 🔥 IMPORTANT FIX END

            return $wpdb->insert(
                $table,
                [
                    'error_id'   => (string) $error_id,
                    'code'       => (int) $code,
                    'message'    => (string) $message,
                    'details'    => wp_json_encode($details, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                    'created_at' => current_time('mysql'),
                ],
                ['%s', '%d', '%s', '%s', '%s']
            );
        }

        /**
         * Capture request context for error logging
         * @Since 1.0.0
         */

        public static function get_request_context()
        {
            return [
                'request_url' => isset($_SERVER['REQUEST_URI'])
                    ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']))
                    : '',

                'request_method' => isset($_SERVER['REQUEST_METHOD'])
                    ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD']))
                    : '',
                'status_code'    => http_response_code(),
                'remote_ip'  => isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '',
                'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
                'referrer'   => isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : '',
                'timestamp'      => current_time('mysql'),
            ];
        }

        /**
         * DEBUG → DB NORMALIZER
         * @Since 1.0.0
         */

        public static function gshfjf_log_from_debug($error)
        {
            // JSON string hoy to decode try karo
            if (is_string($error)) {
                $decoded = json_decode($error, true);

                if (json_last_error() === JSON_ERROR_NONE) {
                    $error = $decoded;
                }
            }

            if (is_array($error) || is_object($error)) {

                self::log_to_db(
                    'jetform_gsheet_error',
                    500,
                    'JetForm Google Sheets Error',
                    (array) $error
                );
            } else {

                self::log_to_db(
                    'jetform_gsheet_error',
                    500,
                    'JetForm Google Sheets Error',
                    [
                        'type'      => 'error',
                        'raw_error' => trim((string) $error),
                    ]
                );
            }
        }

        /**
         * ADMIN PAGE
         * @Since 1.0.0
         */

        public function gshfjf_render_page_html()
        {
            global $wpdb;
            // $table = $wpdb->prefix . 'gshfjf_error_logs';

            if ($wpdb->get_var($wpdb->prepare(
                "SHOW TABLES LIKE %s",
                $wpdb->prefix . 'gshfjf_error_logs'
            )) !== $wpdb->prefix . 'gshfjf_error_logs') {

                echo '<div class="notice notice-error"><p>Log table not found.</p></div>';
                return;
            }
            $logs = $wpdb->get_results(
                "SELECT * FROM {$wpdb->prefix}gshfjf_error_logs ORDER BY created_at DESC",
                ARRAY_A
            );
?>
            <div class="error-log-main shadow-box mt-40 p-30">

                <div class="error-log-head flex-wrap gap-20">
                    <div class="heading mt-0 mb-0"><?php echo esc_html__("Debug Log", 'gsheetconnector-for-jetform'); ?> </div>

                    <div class="errorlog-button-list">
                        <a href="<?php echo esc_url(
                                        wp_nonce_url(
                                            admin_url('admin-post.php?action=gshfjf_jetform_clear_logs'),
                                            'gshfjf_clear_logs_nonce'
                                        )
                                    ); ?>" class="button btn-logs"><?php echo esc_html__("Clear Logs", 'gsheetconnector-for-jetform'); ?></a>

                        <a href="<?php echo esc_url(
                                        wp_nonce_url(
                                            admin_url('admin-post.php?action=gshfjf_download_logs'),
                                            'gshfjf_download_logs_nonce'
                                        )
                                    ); ?>" class="button button-primary"><?php echo esc_html__("Download CSV", 'gsheetconnector-for-jetform'); ?></a>

                        <button type="button" id="gshfjf-copy-logs" class="button btn-logs"><?php echo esc_html__("Copy Logs", 'gsheetconnector-for-jetform'); ?></button>
                        <div class="gshfjf-copy-msg d-none"></div>
                    </div>

                </div> <!-- error head #end -->

                <div class="debug-log-div">
                    <table class="widefat striped error-log-table mt-30">
                        <thead>
                            <tr>
                                <th><?php echo esc_html__("Date", 'gsheetconnector-for-jetform'); ?></th>
                                <th><?php echo esc_html__("Error ID", 'gsheetconnector-for-jetform'); ?></th>
                                <th><?php echo esc_html__("Code", 'gsheetconnector-for-jetform'); ?></th>
                                <th><?php echo esc_html__("Message", 'gsheetconnector-for-jetform'); ?></th>
                                <th><?php echo esc_html__("Details", 'gsheetconnector-for-jetform'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($logs): foreach ($logs as $log): ?>
                                    <tr>
                                        <td><?php
                                            $format = get_option('date_format') . ' ' . get_option('time_format');

                                            // mysql2date() returns formatted date using WP timezone settings
                                            echo esc_html(mysql2date($format, $log['created_at'], false));
                                            ?></td>
                                        <td><?php echo esc_html($log['error_id']); ?></td>
                                        <td>
                                            <span class="sb-error-code" data-code="<?php echo esc_attr($log['code']); ?>">
                                                <?php echo esc_html($log['code']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo esc_html($log['message']); ?></td>
                                        <td>
                                            <?php
                                            $details = json_decode($log['details'], true);

                                            if (json_last_error() === JSON_ERROR_NONE && is_array($details)) :
                                            ?>
                                                <div class="gsc-error-details">
                                                    <div class="more-error-display">

                                                        <?php
                                                        $decoded = json_decode($log['details'], true);
                                                        $display = '';

                                                        if (is_array($decoded) && !empty($decoded['raw_error'])) {

                                                            $raw = $decoded['raw_error'];

                                                            // Extract text after "message:"
                                                            if (strpos($raw, 'message:') !== false) {
                                                                $parts = explode('message:', $raw);
                                                                $display = trim(end($parts));
                                                            } else {
                                                                $display = $raw;
                                                            }
                                                        } else {
                                                            $display = $log['details'];
                                                        }

                                                        echo esc_html($display);
                                                        ?>
                                                    </div>
                                                </div>

                                            <?php else: ?>
                                                <?php echo esc_html($log['details']); ?>
                                            <?php endif; ?>

                                        </td>
                                    </tr>
                                <?php endforeach;
                            else: ?>
                                <tr>
                                    <td colspan="5"><?php echo esc_html__("No logs found", 'gsheetconnector-for-jetform'); ?></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
<?php
        }

        /**
         * Clear logs action
         * @Since 1.0.0
         */

        public function gshfjf_jetform_clear_logs()
        {
            if (!current_user_can('manage_options')) {
                wp_die('Permission denied.');
            }

            check_admin_referer('gshfjf_clear_logs_nonce');

            global $wpdb;
            $wpdb->query("TRUNCATE TABLE {$wpdb->prefix}gshfjf_error_logs");

            wp_safe_redirect(wp_get_referer());
            exit;
        }

        /**
         * Log JavaScript errors sent via AJAX
         * @Since 1.0.0
         */

        public static function gshfjf_log_js_error()
        {
            if (!current_user_can('manage_options')) {
                wp_send_json_error();
            }
            //   Nonce check
            if (!isset($_POST['security'])) {
                wp_send_json_error('Nonce missing');
            }

            if (!wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['security'])),
                'gshfjf_js_error_nonce'
            )) {
                wp_send_json_error('Invalid nonce');
            }
            $log = isset($_POST['log']) ? sanitize_text_field(wp_unslash($_POST['log'])) : [];

            if (is_string($log)) {
                $decoded = json_decode($log, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $log = $decoded;
                }
            }

            self::log_to_db(
                'js_error',
                intval($log['status'] ?? 400),
                sanitize_text_field($log['message'] ?? 'JavaScript Error'),
                [
                    'type'    => $log['type'] ?? 'js',
                    'request' => self::get_request_context(),
                    'payload' => $log,
                ]
            );

            wp_send_json_success();
        }

        /**
         * Donwload logs as CSV
         * @Since 1.0.0
         */

        public function gshfjf_download_logs()
        {

            if (! current_user_can('manage_options')) {
                wp_die(esc_html__('Permission denied.', 'gsheetconnector-for-jetform'));
            }

            check_admin_referer('gshfjf_download_logs_nonce');

            global $wpdb;
            // $table = $wpdb->prefix . 'gshfjf_error_logs';

            $logs = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}gshfjf_error_logs", ARRAY_A);

            if (empty($logs)) {
                wp_safe_redirect(wp_get_referer());
                exit;
            }

            nocache_headers();

            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=gsc-jetform-error-logs.csv');

            $output = fopen('php://output', 'w');

            if (false === $output) {
                exit;
            }

            // CSV Header Row
            fputcsv($output, array('Date', 'Error ID', 'Code', 'Message', 'Details'));

            foreach ($logs as $log) {
                fputcsv($output, array(
                    $log['created_at'],
                    $log['error_id'],
                    $log['code'],
                    $log['message'],
                    $log['details'],
                ));
            }

            // fclose optional here (php://output auto closes)
            exit;
        }
    }

    new GSHFJF_JetForm_Error_Logs();
}
add_action('wp_ajax_gshfjf_log_js_error', ['GSHFJF_JetForm_Error_Logs', 'gshfjf_log_js_error']);
