<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Testi;
use App\DataTables\TestiDataTable;
use App\DataTables\TestiDataTableEditor;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class TestiController extends Controller
{
    public static $permission_group = "Testi";
    public static $permissions = [
        'view-testi' => 'Vedi',
        'create-testi' => 'Crea',
        'edit-testi' => 'Modifica',
        'delete-testi' => 'Elimina',
        'show-testi-cliente' => 'Cliente Vede',
    ];
    public static function middleware(): array
    {
        return [
            new Middleware('permission:view-testi', only: ['index']),
            new Middleware('permission:create-testi|edit-testi|delete-testi', only: ['store', 'update', 'destroy']),
            new Middleware('permission:show-testi-cliente', only: ['show_cliente']),
        ];
    }

    public function index(TestiDataTable $dataTable)
    {
        $dataTable->attivita_id = Session::get('attivita_attuale');
        return $dataTable->render('testi.index');
    }

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

    public function show_cliente(Request $request)
    {
        switch($request->get('oggetto')){
            case 'privacy':
                $testi = Testi::where('ambiente', 'cliente')
                ->where('tipo', 'privacy')
                ->where('is_attivo', true)
                ->orderBy('created_at', 'desc')
                ->first();
                break;
            default:
                $testi = Testi::find($request->get('testi_id'));
                break;
        }

  
        return view('testi.show', compact('testi'));
    }
}
