<?php

namespace App\Http\Controllers;

use App\Models\dati;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;


class DatiController extends Controller
{
   private function getDatiCount($Dati) {
       return match ($Dati->name) {
           'test' =>300,
           default => 50
       };
   }

    public function index(Request $request)
    {
        $Datis = Dati::all();

        return view('welcome', ['Datis' => $Datis]);
    }

    public function ajaxDati(Request $request) {
        $datis= Dati::query();

        return DataTables::eloquent($datis)
                ->addColumn('custom_data', function (Dati $Dati){
                    return 'Dati ' . $Dati->title . ' ir ' . $this->getDatiCount($Dati) . ' dati';
                })
                ->toJson();
    }

    public function ajaxPost(Request $request) {
        $updating = $request->id !== null;
        $success = true;
        $message = "";

        if (!$updating) {
            $Dati = new Dati();
            $Dati->create($request->all());
        } else {
            $Dati = Dati::find($request->id);
            $Dati->update($request->all());
            $Dati->save();
        }

        return [
            'success' => $success,
            'message' => $message,

        ];
    }

    public function ajaxDestroy(Request $request)
    {
        $success = true;
        $message = "";

        $Dati = Dati::find($request->id);
        $Dati->delete();

        return [
            'success' => $success,
            'message' => $message,


        ];
    }
}


