<?php

namespace App\Http\Controllers\Api\Restaurant;

use App\Helpers\FileHelper;
use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;

class ArticleController extends Controller
{

    public function getArticleDetail($idArticle)
    {
        try {
            $queryDetail = Article::where('restaurants.restaurant_id', $idArticle)
                ->select(
                    'restaurants.restaurant_id as id',
                    'restaurants.name',
                    'restaurants.address',
                    'restaurants.logo_url',
                    'menu_steps.current_step',
                )
                ->first();
    
            return $queryDetail;
        } catch (Exception $ex) {
            return response()->json(['error' => "Error al consultar los del restaurante"], 500);
        }
    }

    public function createArticle(Request $request)
    {
        try {
            $validatedData = Validator::make($request->all(), [
                'name' => 'required|string|max:500',
                'description' => 'nullable|string|max:600',
                'price' => ['required', 'numeric', 'regex:/^\d+(\.\d{1,2})?$/'],
                'img_file' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5048',
                'label_unit' => 'nullable|string|max:600',
                'price_unit' => ['nullable', 'numeric', 'regex:/^\d+(\.\d{1,2})?$/'],
                'price_special' => ['nullable', 'numeric', 'regex:/^\d+(\.\d{1,2})?$/'],
                'category_id' => 'required|integer|exists:categories,category_id',
            ]);
            if ($validatedData->fails()) {
                return response()->json(['error' => $validatedData->errors()->toArray()], 400);
            }
            $logoPath = null;
            if ($request->hasFile('img_file')) {
                $logoPath = FileHelper::replace(
                    $request->file('img_file'),
                    '',
                    'articles'
                );
            }
            $article = new Article();
            $article->name = $request->name;
            $article->description = $request->description ?? null;
            $article->price = $request->price;
            $article->image_url = $logoPath ?? '';
            $article->label_unit = $request->label_unit;
            $article->price_unit = $request->price_unit;
            $article->price_special = $request->price_special;
            $article->category_id = $request->category_id;
            $article->save();
            return response()->json([
                'message' => "Se creo el artículo exitosamente",
                'article' => $article
            ], Response::HTTP_OK);
        } catch (Exception $ex) {
            return response()->json(['error' => "Error al crear el artículo"], 500);
        }
    }

    public function updateArticle(Request $request)
    {
        try {
            $validatedData = Validator::make($request->all(), [
                'id' => 'required|integer|exists:articles,article_id',
                'name' => 'required|string|max:500',
                'description' => 'nullable|string|max:600',
                'price' => ['required', 'numeric', 'regex:/^\d+(\.\d{1,2})?$/'],
                'img_file' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5048',
                'img_url' => 'nullable|string|max:600',
                'label_unit' => 'nullable|string|max:600',
                'price_unit' => ['nullable', 'numeric', 'regex:/^\d+(\.\d{1,2})?$/'],
                'price_special' => ['nullable', 'numeric', 'regex:/^\d+(\.\d{1,2})?$/'],
                'category_id' => 'required|integer|exists:categories,category_id',
            ]);
            if ($validatedData->fails()) {
                return response()->json(['error' => $validatedData->errors()->toArray()], 400);
            }
            $queryGetArticle = Article::where("article_id", $request->id)->first();

            if (!$queryGetArticle) {
                return response()->json(['error' => "No existe el artículo"], 500);
            }
            $imgPath = null;
            if ($request->hasFile('img_file')) {
                $imgPath = FileHelper::replace(
                    $request->file('img_file'),
                    $queryGetArticle->image_url,
                    'articles'
                );
            }            
            if ((!$request->img_url && !$request->hasFile('img_file')) && $queryGetArticle->image_url) {
                FileHelper::delete($queryGetArticle->image_url);
            }
            $queryGetArticle->update([
                "name" => $request->name,
                "description" => $request->description ?? "",
                "price" => $request->price,
                "label_unit" => $request->label_unit,
                "price_unit" => $request->price_unit,
                "price_special" => $request->price_special,
                "category_id" => $request->category_id,
                "image_url" => ($imgPath) ? $imgPath : $request->img_url,
            ]);
            return response()->json([
                'message' => "Se actualizo el artículo exitosamente",
            ], Response::HTTP_OK);
        } catch (Exception $ex) {
            return response()->json(['error' => "No se pudo actualizar el artículo"], 500);
        }
    }

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