<?php

namespace App\Http\Controllers\Parametres\Imports;

use App\Http\Controllers\Controller;
use App\Http\CSVAptimapEntetesConstants;
use App\Http\CSVAptimapEntetesSlugConstants;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use ROLE;
use Symfony\Component\HttpFoundation\Response;

class ImportCartographie extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
     */


    public function index()
    {
        if (!Auth::user()->hasRole(ROLE::SUPER_ADMINISTRATEUR)) {
            abort(Response::HTTP_FORBIDDEN);
        }
        $customers = DB::table('structures')
            ->select('id', 'nom')
            ->get()
            ->map(function ($item) {
                return [
                    'nom' => $item->nom,
                    'id' => $item->id,
                ];
            })
            ->toArray();
        return view('parametres.import-cartographie.index', [
            'customers' => $customers,
        ]);
    }

    public function store(Request $request)
    {
        if (!Auth::user()->hasRole(ROLE::SUPER_ADMINISTRATEUR)) {
            abort(Response::HTTP_FORBIDDEN);
        }

        $id = $request->get('customer');

        if ($request->hasFile('cartography')) {
            $file = $request->file('cartography');
            if ($file->isValid()) {
                $this->retrieveCsvClient($file, $id);
            } else {
                abort(Response::HTTP_UNPROCESSABLE_ENTITY);
            }
        } else {
            abort(Response::HTTP_BAD_REQUEST);
        }

        $headersCustomers = $this->retrieveHeadersClient($id);

        return view('parametres.import-cartographie.matching', [
            'headersAptimap' => CSVAptimapEntetesConstants::HEADERS_APTIMAP,
            'headersCustomers' => $headersCustomers,
        ]);
    }

    protected function retrieveHeadersClient($id): array
    {
        return DB::table('csv_client_entetes')
            ->select('id', 'nom')
            ->orderBy('nom', 'asc')
            ->where('structure_id', $id)
            ->get()
            ->map(function ($item) {
                return [
                    'nom' => $item->nom,
                    'id' => $item->id,
                ];
            })
            ->toArray();
    }
    protected function retrieveCsvClient(UploadedFile $file, $id)
    {
        if ($file->isValid()) {
            $extension = strtolower($file->getClientOriginalExtension());

            if ($extension === 'csv') {
                //If the file is a Csv file
                $handle = fopen($file->getPathname(), "r");
                $contentCsv = fgetcsv($handle);

                fclose($handle);

                $headers = explode(';', $contentCsv[0]);

                if ($this->retrieveHeadersClient($id)) {
                    $this->deleteHeadersClient($id);
                }

                foreach ($headers as $header) {
                    $this->addHeader($header, $id);
                }
            } else {
                abort(Response::HTTP_UNPROCESSABLE_ENTITY);
            }
        } else {
            abort(Response::HTTP_UNPROCESSABLE_ENTITY);
        }
    }
    protected function addHeader($herder, $id)
    {
        DB::table('csv_client_entetes')->insert([
            'nom' => $herder,
            'structure_id' => $id
        ]);
    }
    protected function deleteHeadersClient($id)
    {
        DB::delete('delete from csv_client_entetes where structure_id = ?', [$id]);
        DB::delete('delete from csv_donnees_client where structure_id = ?', [$id]);
    }

    public function matchingCSV(Request $request): RedirectResponse
    {
        if (!Auth::user()->hasRole(ROLE::SUPER_ADMINISTRATEUR)) {
            abort(Response::HTTP_FORBIDDEN);
        }


        $idHeadersCustomers = $request->get('headerCustomersSelected');

        $i = 0;
        foreach (CSVAptimapEntetesSlugConstants::SLUG_APTIMAP as $header => $slug) {
            $headersAptimap[$i] = $header;
            $i++;
        }
        $rowsAffected = 0;


        foreach ($headersAptimap as $index => $headerAptimap) {
            if (isset($idHeadersCustomers[$index])) {
                $affected = DB::table('csv_client_entetes')->where('id', '=', $idHeadersCustomers[$index])->update([
                    'csv_aptimap_entetes' => $headerAptimap
                ]);
                $rowsAffected += $affected;
            }
        }

        if ($rowsAffected > 0) {
            session()->flash('success', 'Le matching a bien été effectué.');
        }

        return redirect()->route('import-cartographie.index');
    }
}
