<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ListinoPrezzi;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\DataTables\ListinoPrezziDataTable;
use App\DataTables\ListinoPrezziDataTableEditor;


class ListinoPrezziController extends Controller
{
    public static $permission_group = "Listino Prezzi";
    public static $permissions = [
        'view-listino_prezzi' => 'Vedi',
        'create-listino-prezzi' => 'Crea',
        'edit-listino-prezzi' => 'Modifica',
        'delete-listino-prezzi' => 'Elimina',
    ];
    
    public static function middleware(): array
    {
        return  [
                    new Middleware('role:superadmin', ['only' => ['index', 'store']]),
                    new Middleware('role:amministratore', ['only' => ['show_listino_cliente']]),
                ];
    }

    public function index(ListinoPrezziDataTable $dataTable)
    {
        return $dataTable->render('listino_prezzi.index');
    }

    public function store(ListinoPrezziDataTableEditor $editor)
    {
        if(!Auth::user()->hasRole('superadmin')){
            return 403;
        }

            $request = request();
            $input = $request->all();
            if($request->has('action')){
                switch($input['action']){
                    case 'create':
                        if(!Auth::user()->can('create-listino-prezzi')) return;
                        break;
                    case 'edit':
                        if(!Auth::user()->can('edit-listino-prezzi')) return;
                        break;
                    case 'remove':
                        if(!Auth::user()->can('delete-listino-prezzi')) return;
                        break;
                }
            }
            return $editor->process($request);
    }

    public function show_listino_cliente()
    {
        $listino_prezzi = ListinoPrezzi::all();
        return view('listino_prezzi.cliente.show', compact('listino_prezzi'));
    }

    public function show_listino_pubblico()
    {
        $listino_prezzi = ListinoPrezzi::all();
        return view('listino_prezzi.pubblico.show', compact('listino_prezzi'));
    }

    public function export_listino_pubblico_pdf(\App\Services\ListinoPrezzi\ListinoPubblicoPdfExporter $exporter)
    {
        try {
            $html = $exporter->renderPageHtml(ListinoPrezzi::all());
            $pdfPath = $exporter->exportFromHtml($html);
        } catch (\Throwable $e) {
            report($e);
            return redirect()
                ->route('listino-prezzi.show')
                ->with('error', 'Impossibile generare il PDF: '.$e->getMessage());
        }

        return response()
            ->download($pdfPath, 'listino-segrestafest-local-cloud.pdf', [
                'Content-Type' => 'application/pdf',
            ])
            ->deleteFileAfterSend(true);
    }
}
