<?php
if (!isset($_SERVER['DOCUMENT_ROOT'])) {
    throw new Exception('DOCUMENT ROOT must be defined in the server environment.');
}
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php'); //Needed to use Wordpress core functions
/*
    Create a downloadable csv-file from an array
    with specified delimiter using WordPress filesystem
*/
if ( ! empty( $_POST ) ) {  
    if (empty($_POST['itemdata']) || empty($_POST['delimiter']) || empty($_POST['filename'])) {
        exit();
    }

    // Verify nonce for security
    if ( isset($_POST['security']) && !empty($_POST['security']) ) 
    {
        if ( ! wp_verify_nonce( $_POST['security'], 'csvtohtml_nonce_action' ) ) 
        {
            die( 'Permission denied: Invalid nonce.' );  // Or handle error as needed
        }
    } else {
        die( 'Permission denied: Nonce missing.' );  // Handle missing nonce case
    }
    
    // Sanitize and retrieve values
    $itemdata = isset($_POST['itemdata']) ? array_map('sanitize_text_field', $_POST['itemdata']) : [];  // Correct sanitization
    $delimiter = sanitize_text_field(wp_unslash( $_POST['delimiter'] ));
    $filename  = sanitize_file_name(wp_unslash( $_POST['filename'] ));

    // Prepare CSV content in memory
    $csv_content = '';
    foreach ( $itemdata as $it ) {
        $csv_content .= implode( $delimiter, explode( $delimiter, $it ) ) . PHP_EOL;
    }

    //Validations of incoming content
        
    //Basic validation content csv structure
    if (!strpos($csv_content, ',') && !strpos($csv_content, "\n")) {
        wp_die('Invalid CSV content'); 
    }

    //Validate the file extension for edge cases
    if (pathinfo($filename, PATHINFO_EXTENSION) !== 'csv') {
        wp_die('Invalid file type');
    }

    //Check file name for invalid paths
    if (strpos($filename, '..') !== false) {
        wp_die('Invalid file name'); // Reject invalid file names
    }

    //Verify file MIME type for edge cases
    $file_type = wp_check_filetype($filename);
    if ($file_type['ext'] !== 'csv' || $file_type['type'] !== 'text/csv') {
        wp_die('Invalid file type');
    }    

    // Get the WordPress Filesystem instance
    global $wp_filesystem;
    if ( ! function_exists( 'WP_Filesystem' ) ) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    WP_Filesystem();

    // Temporary file path for CSV
    $temp_file = wp_tempnam( 'csv_export_' . time() . '.csv' );

    //Is the file writeable?
    if ( ! $wp_filesystem->is_writable( $temp_file ) ) {
        wp_die('The directory is not writable');
    }

    // Write the CSV content to the temporary file using WP_Filesystem
    $wp_filesystem->put_contents( $temp_file, $csv_content, FS_CHMOD_FILE );

    // Read file contents via WP_Filesystem and output it
    $file_content = esc_textarea($wp_filesystem->get_contents( $temp_file ));

    // Send the file for download
    header( 'Content-Type: text/csv' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '";' );
    echo esc_html($file_content); // Output the file contents to the browser

    //Delete the temporary file after sending it to the browser
    $wp_filesystem->delete( $temp_file );
}
?>