<?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 App\Models\SocialLink;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class RestaurantController extends Controller
{
    public function allRestaurants($idUser)
    {
        try {
            $queryAll = Restaurant::where("user_id", $idUser)->select("restaurant_id as id", "name", "slug", "address", "logo_url")->limit(100)->get();
            return $queryAll;
        } catch (Exception $ex) {
            return response()->json(['error' => "Error al consultar tus restaurantes"], 500);
        }
    }

    public function detailRestaurant($slugRestaurant)
    {
        try {
            $queryDetail = Restaurant::join('menu_steps', 'menu_steps.restaurant_id', '=', 'restaurants.restaurant_id')
                ->where('restaurants.slug', $slugRestaurant)
                ->select(
                    'restaurants.restaurant_id as id',
                    'restaurants.slug',
                    'restaurants.name',
                    'restaurants.address',
                    'restaurants.logo_url',
                    'menu_steps.current_step',
                )
                ->first();

            $menuQuery = Menu::where('menus.restaurant_id', $queryDetail->id)
                ->select('menu_id',)
                ->first();
            $queryDetail->menu_id = $menuQuery->menu_id;

            $socials = DB::table('social_links')
                ->where('restaurant_id', $queryDetail->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 getMenuDetail($slug)
    {
        try {
            $menu = Menu::with([
                'categories.subcategories.articles.category', // subcategoría -> artículo -> categoría -> padre
                'categories.articles.category' // artículos ligados a categoría principal
            ])
                ->whereHas('restaurant', function ($query) use ($slug) {
                    $query->where('slug', $slug);
                })
                ->first();
            return $menu;
        } catch (Exception $ex) {
            return response()->json(['error' => "Error al obtener el menú del restaurante"], 500);
        }
    }

    public function createInformation(Request $request)
    {
        try {
            $validatedData = Validator::make($request->all(), [
                'name' => 'required|string|max:800',
                'address' => 'nullable|string|max:1000',
                'logo_file' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5048',
                'slug' => 'required|string|max:255|unique:restaurants,slug',
                'user_id' => 'required|integer|exists:users,id',
                'facebook' => 'nullable|string|max:300',
                'instagram' => 'nullable|string|max:300',
            ]);
            if ($validatedData->fails()) {
                return response()->json(['error' => $validatedData->errors()->toArray()], 400);
            }
            DB::beginTransaction();
            $logoPath = null;
            if ($request->hasFile('logo_file')) {
                $logoPath = FileHelper::replace(
                    $request->file('logo_file'),
                    '',
                    'logos'
                );
            }
            $newRestaurant = Restaurant::create([
                "name" => $request->name,
                "address" => $request->address,
                "logo_url" => $logoPath ?? '',
                "slug" => $request->slug,
                "user_id" => $request->user_id
            ]);
            $idRestaurant = $newRestaurant->restaurant_id;
            if ($idRestaurant) {
                SocialLink::create([
                    "platform" => "facebook",
                    "url" => $request->facebook,
                    "restaurant_id" => $idRestaurant,
                ]);
                SocialLink::create([
                    "platform" => "instagram",
                    "url" => $request->instagram,
                    "restaurant_id" => $idRestaurant,
                ]);
                $firstStep = MenuStep::create([
                    "current_step" => 3,
                    "restaurant_id" => $idRestaurant
                ]);
                if (!$firstStep->menustep_id) {
                    DB::rollBack();
                    return response()->json(['error' => "Lo sentimos, estamos teniendo dificultades tecnicas"], 500);
                }
                $firstMenu = Menu::create([
                    "restaurant_id" => $idRestaurant
                ]);
                if (!$firstMenu->menu_id) {
                    DB::rollBack();
                    return response()->json(['error' => "Lo sentimos, estamos teniendo dificultades tecnicas"], 500);
                }
                DB::commit();
                return response()->json([
                    'message' => "Se creo el restaurante exitosamente",
                    'restaurant' => $newRestaurant
                ], Response::HTTP_OK);
            }
        } catch (Exception $ex) {
            DB::rollBack();
            return response()->json(['error' => "Error al guardar la información"], 500);
        }
    }

    public function updateInformation(Request $request)
    {
        try {
            $validatedData = Validator::make($request->all(), [
                'id' => 'required|integer|exists:restaurants,restaurant_id',
                'name' => 'required|string|max:800',
                'address' => 'nullable|string|max:1000',
                'logo_file' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5048',
                'logo_url' => 'nullable|string|max:600',
                'user_id' => 'required|integer|exists:users,id',
                'facebook' => 'nullable|string|max:300',
                'instagram' => 'nullable|string|max:300',
            ]);

            if ($validatedData->fails()) {
                return response()->json(['error' => $validatedData->errors()->toArray()], 400);
            }
            DB::beginTransaction();
            $queryGetRestaurant = Restaurant::where("user_id", $request->user_id)
                ->where("restaurant_id", $request->id)->first();
            if (!$queryGetRestaurant) {
                return response()->json(['error' => "No existe el restaurante"], 500);
            }
            $logoPath = null;
            if ($request->hasFile('logo_file')) {
                $logoPath = FileHelper::replace(
                    $request->file('logo_file'),
                    $queryGetRestaurant->logo_url,
                    'logos'
                );
            }

            if ((!$request->logo_url && !$request->hasFile('logo_file')) && $queryGetRestaurant->logo_url) {
                FileHelper::delete($queryGetRestaurant->logo_url);
            }

            $queryGetRestaurant->update([
                "name" => $request->name,
                "address" => $request->address ?? "",
                "logo_url" => ($logoPath) ? $logoPath : $request->logo_url,
            ]);
            $facebookUpdate = SocialLink::where("platform", "facebook")
                ->where("restaurant_id", $queryGetRestaurant->restaurant_id)->first();
            if ($facebookUpdate) {
                $facebookUpdate->url = $request->facebook ?? "";
                $facebookUpdate->save();
            }
            $instagramUpdate = SocialLink::where("platform", "instagram")
                ->where("restaurant_id", $queryGetRestaurant->restaurant_id)->first();
            if ($instagramUpdate) {
                $instagramUpdate->url = $request->instagram ?? "";
                $instagramUpdate->save();
            }
            DB::commit();
            return response()->json([
                'message' => "Se actualizo la información exitosamente",
            ], Response::HTTP_OK);
        } catch (Exception $ex) {
            DB::rollBack();
            return response()->json(['error' => "Lo sentimos no pudimos actualizar la información"], 500);
        }
    }

    public function updateStep(Request $request)
    {
        try {
            $validatedData = Validator::make($request->all(), [
                'slug' => 'required|string|max:255|exists:restaurants,slug',
                'current_step' => 'required|integer|min:1|max:4',
            ]);

            if ($validatedData->fails()) {
                return response()->json(['error' => $validatedData->errors()->toArray()], 400);
            }
            $slug = $request->slug;
            $menuUpdate = MenuStep::whereHas('restaurant', function ($query) use ($slug) {
                    $query->where('slug', $slug);
                })
                ->first();
            if (!$menuUpdate) {
                return response()->json(['error' => "No existe el restaurante"], 500);
            }
            $menuUpdate->current_step = $request->current_step;
            $menuUpdate->save();
            return response()->json([
                'message' => "Ya puedes continuar con el siguiente paso",
            ], Response::HTTP_OK);
        } catch (Exception $ex) {
            return response()->json(['error' => "Lo sentimos algo ocurrio al actualizar el siguiente paso"], 500);
        }
    }

    public function deleteRestaurant($id)
    {
        try {
            $deleteElement = Restaurant::find($id);
            if (!$deleteElement) {
                return response()->json(['error' => "No existe el restaurante"], 500);
            }
            FileHelper::delete($deleteElement->logo_url);
            $deleteElement->delete();
            return response()->json([
                'message' => "Se eliminó el restaurante exitosamente",
            ], Response::HTTP_OK);
        } catch (Exception $ex) {
            return response()->json(['error' => "Error al eliminar el restaurante"], 500);
        }
    }
}
