<?php

namespace App\Http\Controllers;

use App\Repositories\LocationRepository;
use App\Models\Source;

class ExportController extends Controller
{
    protected $locationRepository;

    public function __construct(LocationRepository $locationRepository)
    {
        $this->locationRepository = $locationRepository;
    }

    public function exportIndex()
    {
        $heatArray = [90, 80, 70, 60, 50, 40, 30, 20];
        $sources   = Source::where("active", true)->get();
        $locations = $this->locationRepository->getActiveLocations();
        $list      = [];
        foreach ($heatArray as $rating) {
            $count = 0;
            foreach ($locations as $location) {
                $rate = $location->actions_count / count($sources);
                if ($rate * 100 >= $rating) {
                    $count++;
                }
            }
            array_push($list, ["heatRating" => $rating, "ratingCount" => $count]);
        }
        return view('front.exports', [
            'title' => "Exports",
            'list'  => $list
        ]);
    }

    //
    public function exportCSV($type, $percent)
    {
        $columns = [];
        $list    = [];

        $locations = $this->locationRepository->getActiveLocations();
        $sources   = Source::where("active", true)->get();
        if ($type == 'mastodon') {
            $columns = [
                'domain',
                'severity',
                'public_comment',
                'reject_media',
                'reject_reports',
                'obfuscate',
            ];
        };

        foreach ($locations as $location) {
            $rate = $location->actions_count / count($sources);
            if ($rate * 100 >= $percent) {
                if ($type == 'mastodon') {
                    //comman break teh CSV so just take them out
                    $comments = str_replace(",", ";", $location->description);

                    //remove extra white space
                    $comments = str_replace(["\n\r", "\n", "\r"], " ", $comments);
                    $comments = str_replace(['"', "'"], "", $comments);
                    //add to the export list
                    array_push($list, [$location->url, $location->rating, $comments, "FALSE", "FALSE", "FALSE"]);
                }
            }
        }

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename=' . $type . "-" . $percent);

        echo implode(',', $columns) . PHP_EOL;
        foreach ($list as $item) {
            echo implode(',', $item) . PHP_EOL;
        }
    }
}