<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Piatto;
use App\Models\PiattoHasAllergene;
use App\DataTables\PiattoDataTable;
use App\DataTables\PiattoDataTableEditor;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class PiattoController extends Controller
{
    public static $permission_group = "Piatti";
    public static $permissions = [
        'view-piatto' => 'Vedi',
        'create-piatto' => 'Crea',
        'edit-piatto' => 'Modifica',
        'delete-piatto' => 'Elimina',
    ];

    public static function middleware(): array
    {
        return [
            new Middleware('permission:view-piatto', only: ['index']),
            new Middleware('permission:create-piatto|edit-piatto|delete-piatto', only: ['store', 'update', 'destroy']),
        ];
    }

    public function index(PiattoDataTable $dataTable , Request $request){
      $dataTable->attivita_id = Session::get('attivita_attuale');

        if (request()->boolean('dashboard')) {
            $dataTable->dashboard = true;
        }

        if (request()->has('cucina_id')) {
            $dataTable->cucina_id = (int) request()->get('cucina_id');
        }

        return $dataTable->render('piatto.index');
    }

    public function datatable(PiattoDataTable $dataTable , Request $request){
      $dataTable->attivita_id = Session::get('attivita_attuale');

      if(request()->has('cucina_id')){
        $dataTable->cucina_id = request()->get('cucina_id');
      }
      if(request()->has('dashboard')){
        $dataTable->dashboard = true;
      }

        return $dataTable->render('piatto.datatable');
    }
    // public function datatable(PiattoDataTable $dataTable){
    //   $dataTable->menu_id = request()->get('menu_id');
    //   return $dataTable->render('piatto.datatable');
    // }

    public function store(PiattoDataTableEditor $editor)
    {
      $request = request();

      if ($request->has('action')) {
        $action = $request->input('action');

        switch ($action) {
          case 'create':
            if (! Auth::user()->can('create-piatto')) return;
            break;

          case 'edit':
            if (! Auth::user()->can('edit-piatto')) return;
            break;

          case 'remove':
            if (! Auth::user()->can('remove-piatto')) return;
            break;
        }
      }

      return $editor->process($request);
    }

    /**
     * Metodo helper per aggiornare la pivot `piatto_allergene`.
     * (L'update principale avviene in `PiattoDataTableEditor`.)
     */
    public function allergeni(Request $request)
    {
      // Payload DataTables Editor (edit) -> request->get('data') format:
      // { "<piatto_id>": { "allergeni": [1,2,...], ... }, ... }
      $payload = $request->get('data', []);

      if (! is_array($payload)) {
        return response()->json(['ok' => false, 'error' => 'Invalid payload'], 422);
      }

      foreach ($payload as $piattoId => $data) {
        $piattoId = (int) $piattoId;
        $allergenIds = $data['allergeni'] ?? [];

        if (is_string($allergenIds)) {
          $allergenIds = array_filter(array_map('trim', explode(',', $allergenIds)));
        }

        if (! is_array($allergenIds)) {
          $allergenIds = [];
        }

        $allergenIds = array_values(array_unique(array_map(static fn ($id) => (int) $id, $allergenIds)));
        $allergenIds = array_values(array_filter($allergenIds, static fn ($id) => $id > 0));

        PiattoHasAllergene::where('piatto_id', $piattoId)->delete();

        if (! empty($allergenIds)) {
          $rows = array_map(static function ($allergeneId) use ($piattoId) {
            return [
              'piatto_id' => $piattoId,
              'allergene_id' => $allergeneId,
            ];
          }, $allergenIds);

          PiattoHasAllergene::insert($rows);
        }
      }

      return response()->json(['ok' => true]);
    }
}
