<?php
namespace ONLINE_ADAv4;

use ONLINE_ADAv4\Helper;

add_action('rest_api_init', __NAMESPACE__ .'\\csv_page_download');
function csv_page_download()
{
    register_rest_route('ada-plugin/v1', '/pagecsv', array(
        'methods' => 'GET',
        'callback' => __NAMESPACE__ . '\\page_csv'
    ));
}

function page_csv($request)
{
    //Go through this 5 pages at a time and save 5 pages at a time to the CSV. Open it then append another 5 pages...

    $scan_id = $request->get_param('scan_id');
    if (empty($scan_id)) {
        return new \WP_Error('bad_request', 'scan_id is required.', array('status' => 400));
    }

    // Prevent directory traversal by ensuring scan_id is just a filename.
    $safe_scan_id = basename($scan_id);

    // If basename() stripped characters, it means a path was attempted.
    if ($safe_scan_id !== $scan_id) {
        return new \WP_Error('bad_request', 'Invalid scan_id.', array('status' => 400));
    }

    $offset = 0;
    $limit = 5;
    $total_rows = Helper::get_row_count($safe_scan_id);
    $articles = Helper::getWcagArticlesModel(2);
    $guidelines = Helper::getWcagArticlesModel(1, true);
    $csv_path = wp_upload_dir()["basedir"] . "/oadaas/csv_reports/";
    $filename = $safe_scan_id . "_csv_report.csv";
    $fullPath = $csv_path . $filename;

    
    while($offset <= $total_rows){
        $all_issues = Helper::get_scan_data($safe_scan_id, $offset, $limit);
        $false_positives = Helper::get_false_positives($safe_scan_id);
        if(empty($false_positives)){
            $false_positives = [];
        }

        if($offset === 0){
            //Create the CSV
            if(!file_exists($csv_path)){
                wp_mkdir_p($csv_path);
            }
            
            $csv = fopen($fullPath, 'w'); // phpcs:ignore
            //Header row
            fputcsv($csv, ["Issue #", "Page", "Article #", "WCAG Level", "Description", "Source Code"]);
            
        }else{
            //Retrieve and append to
            $csv = fopen($fullPath, 'a'); // phpcs:ignore
        }

        $formatted = formatResults($all_issues, $false_positives);

        foreach ($formatted as $array) {
            fputcsv($csv, $array);
        }

        fclose($csv); // phpcs:ignore

        $offset += $limit;
    }

    $scan_title = $request->get_param('scan_title');
    $title = sanitize_file_name($scan_title);
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $title . "-report.csv");
    
    echo wp_kses(file_get_contents($fullPath),wp_kses_allowed_html()); // phpcs:ignore
    die;
}

function formatResults($scan_data, $false_positives){
    $formatted = [];
    $issue_number = 1;
    foreach ($scan_data AS $cat_title => $cat_items) {
        if($cat_title == "issues"){ continue; }

        foreach($cat_items AS $item){
            if(in_array($item["issueID"], $false_positives)){ continue; }
            $page = "Homepage";
            if(isset($item["page"])){
                $page = home_url()."/".$item["page"];
            }
            $articles = "best practice";
            
            if(!empty($item["articles"])){
                $articles = '"';
                foreach($item["articles"] AS $index => $art){
                    $articles .= $art;
                    $articles .= ', ';
                }
                $articles = rtrim($articles, ", ");
                $articles .= '"';
            }

            $types = "BP";
            
            if(!empty($item["types"])){
                $types = '"';
                $convert = [
                    "wcag level A" => "A",
                    "wcag level AA" => "AA",
                    "contrast"  => "AA"
                ];
                
                foreach($item["types"] AS $index => $type){
                    if(empty($convert[$type])){continue;}
                    $types .= $convert[$type];
                    $types .= ', ';
                    
                }
                $types = rtrim($types, ", ");
                $types .= '"';
            }

            $html = stripslashes($item["html"]);
            if(strlen(stripslashes($item["html"])) > 300){
                $html = substr(stripslashes($item["html"]), 0, 300) . " [... truncated]";
            }

            $message = $item["message"];
            if(empty($message)){
                $message = $item["issueData"]["any"][0]["message"];
            }
            
            $formatted[] = [ $issue_number, $page, $articles, $types, $message, $html ];
            $issue_number++;   
        }
    }

    return $formatted;
}