<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Location;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\Auth;
use League\Csv\Reader;

class LocationController extends Controller
{
    //url to oli's unified tier 3 list
    private $three = 'https://codeberg.org/oliphant/blocklists/raw/branch/main/blocklists/_unified_tier3_blocklist.csv';

    //url to oli's domain audit containin block counts per domain
    private $defed = 'https://codeberg.org/oliphant/blocklists/raw/branch/main/blocklists/other/domain_audit_file.csv';

    public function addLocation(Request $request)
    {
        $fields = $request->validate([
            'name'        => ['required'],
            'url'         => ['required'],
            'description' => ['required'],
            'tags'        => ['required'],
        ]);

        if ($fields) {
            $examples = [];
            $files    = $request->files->get("loc_examples");
            if ($request->hasfile('loc_examples')) {
                foreach ($request->file('loc_examples') as $file) {
                    $path = $file->store('reference');
                    array_push($examples, ["path" => $path]);
                }
            }
            $request->merge(['active' => true]);
            $request->merge(['uuid' => Uuid::uuid4()]);
            $request->merge(['images' => json_encode($examples)]);
            $request->merge(['added_by' => Auth::user()->id]);
            //NOTE: Laravel gets funky if sequencing isn't explicitly set
            $new = Location::create($request->all());
            if ($new) {
                return back()->with('message', 'New Location Added. Take a break!');
            } else {
                return back()->withErrors([
                    'error' => 'Uh oh. There was an inssue',
                ]);
            }
        } else {
            return back()->withErrors([
                'error' => 'All fields are required',
            ]);
        }
    }

    public function updateLocations()
    {
        //$fresh = file($this->three);
        //$deny  = Reader::createFromPath($fresh, "r");
        //$deny->setHeaderOffset(0);
        //$list        = $deny->getRecords();
        //$recordCount = count($fresh);
        $duplicates = 0;
        $fresh      = 0;
        $denycount  = array_map('str_getcsv', file($this->defed));
        $denylist   = array_map('str_getcsv', file($this->three));

        foreach ($denylist as $item) {
            $blockCount = 0;
            //get block count for item
            foreach ($denycount as $line) {
                if ($line[0] == $item[0]) {
                    $blockcount = $line[1];
                }
            }
            $location = Location::where("url", $item[0])->first();
            if ($location) {
                ++$duplicates;
                //update block count for existing item
                $location->block_count = $blockcount;
                $location->save();
            } else {
                // make new entries for instances not present
                if ($item[0] != 'domain') {
                    ++$fresh;
                    $new = Location::create([
                        'uuid'        => Uuid::uuid4(),
                        'name'        => $item[0],
                        'url'         => $item[0],
                        'description' => 'no description',
                        'active'      => true,
                        'rating'      => $item[1],
                        'added_by'    => 1,
                        'tags'        => 'poor moderation, hate speech',
                        'block_count' => $blockcount
                    ]);
                }
            }
        }

        return back()->with('message', $duplicates . ' UPDATED - ' . $fresh . ' CREATED');

        //$domain = $csv[1000][0];
        //$record = null;

        /*
        foreach ($blockcount as $line) {
            if ($line[0] == $domain) {
                $record = $line;
            }
        }
        if ($record != null) {
            return back()->with('message', $domain . ' has ' . $record[1] . ' blocks.');
        } else {
            return back()->with('message', 'NO MATCHES');
        }
        */
    }
}
