<?php

namespace App\Http\Controllers\Api\Restaurant;

use App\Helpers\FileHelper;
use App\Http\Controllers\Controller;
use App\Models\Menu;
use App\Models\MenuStep;
use App\Models\Restaurant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Response;
use Exception;
use Illuminate\Support\Facades\DB;

class MenuController extends Controller
{
    public function getMenuAll($slug)
    {

        try {
            $queryDetail = Restaurant::join('menu_steps', 'menu_steps.restaurant_id', '=', 'restaurants.restaurant_id')
                ->where('restaurants.slug', $slug)
                ->select(
                    'restaurants.restaurant_id',
                    'restaurants.name',
                    'restaurants.address',
                    'restaurants.logo_url',
                    'menu_steps.current_step',
                )
                ->first();
            if (!$queryDetail) {
                return response()->json(['error' => "No existe el restaurante"], 500);
            }
            $menuQuery = Menu::whereHas('restaurant', function ($query) use ($slug) {
                $query->where('slug', $slug);
            })
                ->with([
                    'categories.subcategories.articles.category',
                    'categories.articles.category'
                ])
                ->first();
            $queryDetail->menu = $menuQuery;

            $socials = DB::table('social_links')
                ->where('restaurant_id', $queryDetail->restaurant_id)
                ->pluck('url', 'platform');
            $queryDetail->socials = $socials;
            return $queryDetail;
        } catch (Exception $ex) {
            return response()->json(['error' => "Error al consultar los del restaurante"], 500);
        }
    }

    public function updateInformationMenu(Request $request)
    {
        try {
            $validatedData = Validator::make($request->all(), [
                'menu_id' => 'required|integer|exists:menus,menu_id',
                'type_background' => 'nullable|string|max:800',
                'color_background' => 'nullable|string|max:1000',
                'background_file' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5048',
                'background_url' => 'nullable|string|max:600',
                'color_text' => 'nullable|string|max:1000',
                'img_main_file' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5048',
                'img_main_url' => 'nullable|string|max:600',
                'color_nav' => 'nullable|string|max:600',
                'restaurant_id' => 'required|integer|exists:restaurants,restaurant_id',
            ]);

            if ($validatedData->fails()) {
                return response()->json(['error' => $validatedData->errors()->toArray()], 400);
            }

            DB::beginTransaction();

            $queryGetMenu = Menu::where("menu_id", $request->menu_id)
                ->first();
            if (!$queryGetMenu) {
                return response()->json(['error' => "No existe el menú"], 500);
            }

            $backgroundPath = null;
            if ($request->hasFile('background_file')) {
                $backgroundPath = FileHelper::replace(
                    $request->file('background_file'),
                    $queryGetMenu->background_url,
                    'menus'
                );
            }

            if ((!$request->background_url && !$request->hasFile('background_file')) && $queryGetMenu->background_url) {
                FileHelper::delete($queryGetMenu->background_url);
            }

            $imgMainPath = null;
            if ($request->hasFile('img_main_file')) {
                $imgMainPath = FileHelper::replace(
                    $request->file('img_main_file'),
                    $queryGetMenu->img_main_url,
                    'main_menus'
                );
            }

            if ((!$request->img_main_url && !$request->hasFile('img_main_file')) && $queryGetMenu->img_main_url) {
                FileHelper::delete($queryGetMenu->img_main_url);
            }

            $queryGetMenu->update([
                "type_background" => $request->type_background ?? "",
                "color_background" => $request->color_background ?? "",
                "color_nav" => $request->color_nav ?? "",
                "color_text" => $request->color_text ?? "",
                "background_url" => ($backgroundPath) ? $backgroundPath : $request->background_url,
                "img_main_url" => ($imgMainPath) ? $imgMainPath : $request->img_main_url,
            ]);

            $menuUpdate = MenuStep::where("restaurant_id", $request->restaurant_id)->first();
            if (!$menuUpdate) {
                return response()->json(['error' => "No se pudo actualizar el proceso del menú"], 500);
            }
            $menuUpdate->current_step = 4;
            $menuUpdate->save();

            DB::commit();
            return response()->json([
                'message' => "Se actualizo el diseño del menú exitosamente",
                'number_step' => $menuUpdate->current_step,
            ], Response::HTTP_OK);
        } catch (Exception $ex) {
            DB::rollBack();
            return response()->json(['error' => "No se pudo actualizar la información"], 500);
        }
    }
}
