<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Bacheca;
use App\DataTables\BachecaDataTable;
use App\DataTables\BachecaDataTableEditor;
use Illuminate\Support\Facades\Auth;
use App\DataTables\ContenutoBachecaDataTable;
use Illuminate\Support\Facades\Session;

class BachecaController extends Controller
{
    public static $permission_group = "Bacheca";
    public static $permissions = [
        'view-bacheca' => 'Vedi',
        'create-bacheca' => 'Crea',
        'edit-bacheca' => 'Modifica',
        'delete-bacheca' => 'Elimina',
    ];
    
    public static function middleware(): array
    {
        return [
            new Middleware('permission:view-bacheca', only: ['index']),
            new Middleware('permission:create-bacheca|edit-bacheca|delete-bacheca', only: ['store', 'update', 'destroy']),
        ];
    }
    
    public function index(BachecaDataTable $dataTable)
    {
        $dataTable->attivita_id = Session::get('attivita_attuale');
        return $dataTable->render('bacheca.index');
    }
    
    public function store(BachecaDataTableEditor $editor)
    {
        $request = request();
        $input = $request->all();
        if($request->has('action')){
            switch($input['action']){
                case 'create':
                    if(!Auth::user()->can('create-bacheca')) return;
                    break;
                case 'edit':
                    if(!Auth::user()->can('edit-bacheca')) return;
                    break;
                case 'remove':
                    if(!Auth::user()->can('delete-bacheca')) return;
                    break;
            }
        }
        return $editor->process($request);
    }
    
    public function show(ContenutoBachecaDataTable $datatable, Request $request)
    {
        $bacheca = Bacheca::find($request->get('bacheca_id'));
        $datatable->bacheca_id = $bacheca->id;
        return $datatable->render('bacheca.show', ['bacheca' => $bacheca]);
    }
}
