<?php
 
 /**
 * =============================================================================
 * @package			    Blue Raven (Free Version)
 * @Plugin URI			https://enterrahost.com/plugins/blue-raven
 * 
 * @Author			    EnterraHost
 * @Author URI			https://enterrahost.com
 * @License			    GPL-2.0-or-later
 *  
 * @Copyright			(c) 2025 EnterraHost
 * @File Description	Admin Settings
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - WJ AJAX BLUE RAVEN SETTINGS
 * ||   - UPDATE ETYPE DEBUGGING
 * ||   - UPDATE FULL UNINSTALL SETTING
 * || 
 * =============================================================================
 */

if ( ! defined( 'ABSPATH' ) ) exit; 

/*
============================================================
    WJ AJAX BLUE RAVEN SETTINGS 
============================================================
*/

add_action('wp_ajax_blue_raven_settings', 'blue_raven_run_settings');

function blue_raven_run_settings() {
    
    ## =========== Security check =========== ##
    
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'blue_raven_admin_settings_nonce')) {
        wp_send_json_error(wp_create_nonce("blue_raven_admin_settings_nonce"));
        BlueRaven_SendError("ERROR", "blue-raven/includes/admin-settings.php", "blue_raven_run_settings", "Invalid nonce");
        wp_send_json_error('Invalid nonce');
    }
    
    ## =========== Get Page =========== ##
     
    $subaction = isset($_POST['subaction']) ? sanitize_text_field(wp_unslash($_POST['subaction'])) : '';

/*
============================================================
    UPDATE ETYPE DEBUGGING
============================================================
*/

    if($subaction == 'update etype debugging'){
    
        $value = isset($_POST['content']) ? sanitize_text_field( wp_unslash( $_POST['content'] )[0] ?? '' ) : '';

        global $wpdb;
        $table_name = $wpdb->prefix . 'BlueRavenConfig';
        $exists = $wpdb->get_var($wpdb->prepare(  "SELECT COUNT(*) FROM $table_name WHERE setting = %s",'eType_debugging'));
        
        if ($exists) {
            $wpdb->update($table_name,array('value' => $value),array('setting' => 'eType_debugging'),  array('%s'),array('%s'));
        } else {
            $wpdb->insert($table_name,array('setting' => 'eType_debugging',  'value' => $value,'created_at' => current_time('mysql'),  'updated_at' => current_time('mysql')   ),array('%s', '%s', '%s', '%s')  );
        }
        
        wp_send_json([ 'data' => 'Settings updated successfully' ]);

/*
============================================================
    DOWNLOAD LOGS
============================================================
*/

    }else if($subaction == 'download logs'){
        blueraven_generate_logs_pdf();
        
/*
============================================================
    UPDATE FULL UNINSTALL SETTING
============================================================
*/

    }else if($subaction == 'enable full uninstaller'){
        $value = isset($_POST['content']) ? sanitize_text_field(wp_unslash($_POST['content'])[0] ?? '') : '';
        $bool_value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
        update_option('blue_raven_remove_all_data', $bool_value);
        wp_send_json([ 'data' => 'Settings updated successfully' ]);
    }
}
        

function blueraven_generate_logs_pdf() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'BlueRavenLogs';
    $logs = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC");

    if (!$logs) wp_die('There are no logs.');

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=BlueRavenLogs.csv');
    $output = fopen('php://output', 'w');
    fputcsv($output, ['ID', 'Type', 'File', 'Context', 'Description', 'Created At']);

    foreach ($logs as $log) {
        fputcsv($output, [
            $log->id,
            $log->type,
            $log->file,
            $log->context,
            str_replace(["\r\n", "\r", "\n"], ' ', $log->description),
            $log->created_at
        ]);
    }

    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- closing php://output stream, not a real file
    fclose($output);
    return $csv_data;
    exit; 
}