<?php

/**

 * SensFRX Debug Logger

 *

 * Comprehensive logging system for debugging SensFRX API integration

 * This file should be removed in production release

 *

 * @package SensFRX

 * @subpackage SensFRX/includes

 */



if (!defined('ABSPATH')) {

    die('Direct access not permitted');

}



class SensFRX_Debug_Logger {



    private static $log_file = '/tmp/sensfrx_debug.log';



    /**

     * Check if debug logging is enabled in settings

     */

    private static function is_enabled() {

        $options = get_option('sensfrx_options', []);

        return isset($options['sensfrx_debug_enabled']) && $options['sensfrx_debug_enabled'] == 1;

    }



    /**

     * Initialize debug logger

     */

    public static function init() {

        if (self::is_enabled()) {

            // Ensure log file exists with proper permissions

            if (!file_exists(self::$log_file)) {

                @touch(self::$log_file);

                @chmod(self::$log_file, 0666);

            }



            // Add action hooks to log various events

            add_action('wp_login_failed', [__CLASS__, 'log_login_failed'], 1, 2);

            add_action('wp_login', [__CLASS__, 'log_login_success'], 1, 2);

        }

    }



    /**

     * Main logging function

     */

    public static function log($message, $data = null, $level = 'INFO') {

        // Check if debug is enabled via settings

        if (!self::is_enabled()) {

            return;

        }



        $timestamp = date('Y-m-d H:i:s');

        $log_entry = "[{$timestamp}] [{$level}] {$message}\n";



        if ($data !== null) {

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

                $log_entry .= "Data: " . json_encode($data, JSON_PRETTY_PRINT) . "\n";

            } else {

                $log_entry .= "Data: {$data}\n";

            }

        }



        $log_entry .= str_repeat('-', 80) . "\n";



        @file_put_contents(self::$log_file, $log_entry, FILE_APPEND);

    }



    /**

     * Log API Request

     */

    public static function log_api_request($url, $method, $headers, $body) {

        self::log("API REQUEST - {$method} {$url}", [

            'method' => $method,

            'url' => $url,

            'headers' => $headers,

            'body' => $body,

            'curl' => self::generate_curl($url, $method, $headers, $body)

        ], 'API');

    }



    /**

     * Log API Response

     */

    public static function log_api_response($url, $http_code, $response_body) {

        self::log("API RESPONSE - HTTP {$http_code} from {$url}", [

            'http_code' => $http_code,

            'response' => $response_body,

            'parsed' => @json_decode($response_body, true)

        ], 'API');

    }



    /**

     * Log Login Failed Event

     */

    public static function log_login_failed($username, $error) {

        self::log("WordPress Login Failed", [

            'username' => $username,

            'error_code' => $error->get_error_code(),

            'error_message' => $error->get_error_message(),

            'ip' => self::get_client_ip(),

            'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : 'unknown',

        ], 'LOGIN');

    }



    /**

     * Log Login Success Event

     */

    public static function log_login_success($username, $user) {

        self::log("WordPress Login Success", [

            'username' => $username,

            'user_id' => $user->ID,

            'ip' => self::get_client_ip(),

            'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : 'unknown',

        ], 'LOGIN');

    }



    /**

     * Log OAuth Flow

     */

    public static function log_oauth($step, $data) {

        self::log("OAuth Flow - {$step}", $data, 'OAUTH');

    }



    /**

     * Log Credentials

     */

    public static function log_credentials($action, $property_id, $property_secret) {

        self::log("Credentials {$action}", [

            'property_id' => $property_id,

            'property_secret' => substr($property_secret, 0, 4) . '...' . substr($property_secret, -4),

            'full_secret_length' => strlen($property_secret)

        ], 'AUTH');

    }



    /**

     * Generate cURL command for debugging

     */

    private static function generate_curl($url, $method, $headers, $body) {

        $curl = "curl -X {$method} '{$url}' \\\n";



        foreach ($headers as $key => $value) {

            $curl .= "  -H '{$key}: {$value}' \\\n";

        }



        if ($body) {

            $curl .= "  -d '" . str_replace("'", "'\\''", $body) . "'";

        }



        return $curl;

    }



    /**

     * Get client IP

     */

    private static function get_client_ip() {

        $ip = '';

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {

            $ip = sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']);

        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {

            $ip = sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);

        } elseif (isset($_SERVER['REMOTE_ADDR'])) {

            $ip = sanitize_text_field($_SERVER['REMOTE_ADDR']);

        }

        return $ip;

    }



    /**

     * Get log file path for download

     */

    public static function get_log_file() {

        return self::$log_file;

    }



    /**

     * Clear debug log

     */

    public static function clear_log() {

        @file_put_contents(self::$log_file, '');

        self::log("=== DEBUG LOG CLEARED ===");

    }



    /**

     * Get log contents

     */

    public static function get_log_contents($lines = 100) {

        if (!file_exists(self::$log_file)) {

            return "Log file not found.";

        }



        $content = @file_get_contents(self::$log_file);



        // Return last N lines

        $log_lines = explode("\n", $content);

        $last_lines = array_slice($log_lines, -$lines);



        return implode("\n", $last_lines);

    }

}



// Initialize debug logger

SensFRX_Debug_Logger::init();

SensFRX_Debug_Logger::log("=== SENSFRX DEBUG LOGGER INITIALIZED ===");

