<?php

namespace App\Http\Controllers\Api\App\Home;

use Illuminate\Http\Request;
use App\Services\DietPlanService;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\App\Meal\{MealResource};
use App\Http\Requests\Api\App\DietPlan\DietPlanRequest;
use App\Http\Resources\Api\App\DietPlan\MealHomeResource;
use App\Http\Resources\Api\App\DietPlan\MealItemResource;
use App\Models\{Calory, ItemDetail, Meal, Product, MealItem, User};

class HomeController extends Controller
{

    /**
     * DietPlanService instance.
     *
     * @var DietPlanService
     */
    private $dietPlanService;

    public function __construct(DietPlanService $dietPlanService)
    {
        $this->dietPlanService = $dietPlanService;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(DietPlanRequest $request)
    {
        $user = User::findOrFail(auth('api')->id());
        $userId = $user->id;

        $product = Product::where(function ($q) use ($userId) {
            $q->where('status', 'approved')->orWhere('user_id', $userId);
        })->findOrFail($request->product_id);

        $servings = $request->number_of_servings;

        $item_calories = $this->dietPlanService->getItemCalories($product, $servings);
        $item_fats     = $this->dietPlanService->getItemFat($product, $servings);
        $item_proteins = $this->dietPlanService->getItemProtein($product, $servings);
        $item_carbs    = $this->dietPlanService->getItemCarbs($product, $servings);

        $item_detail = ItemDetail::updateOrCreate(
            [
            'product_id' => $product->id,
            'user_id'    => $userId,
            ],
            [
            'number_of_servings' => $servings,
            'calories'           => $item_calories,
            'fat'                => $item_fats,
            'protein'            => $item_proteins,
            'carb'               => $item_carbs,
            ]
        );

        $meal = Meal::where('user_id', $userId)->findOrFail($request->meal_id);

        $meal_item = $meal->mealItems()->updateOrCreate([
            'item_detail_id' => $item_detail->id,
            'meal_id'        => $meal->id,
            'user_id'        => $userId,
            'date'           => $request->date,
        ], [
            'calories'       => $item_calories,
            'fat'            => $item_fats,
            'protein'        => $item_proteins,
            'carb'           => $item_carbs,
        ]);

        $totals = $meal->mealItems()
            ->where('date', $request->date)
            ->selectRaw('SUM(calories) as calories, SUM(fat) as fat, SUM(protein) as protein, SUM(carb) as carb')
            ->first();

        $user->scheduleDetails()->updateOrCreate(
            [
            'user_id' => $userId,
            'date'    => $request->date,
            ],
            [
            'calories' => $totals->calories ?? 0,
            'fat'      => $totals->fat ?? 0,
            'protein'  => $totals->protein ?? 0,
            'carb'     => $totals->carb ?? 0,
            ]
        );

        return response()->json(['status' => 'success', 'data' => null, 'message' => trans('Created successfully')]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function home(Request $request)
    {
        $user = User::findOrFail(auth('api')->id());
        $my_calories = Calory::where('user_id', $user->id)->first();
        $schedule_details = $user->scheduleDetails()->where('date', $request->date)->first();

        $macros = [
            'calories' => $my_calories->calories ?? 0,
            'carb'     => $my_calories->carb ?? 0,
            'fat'      => $my_calories->fat ?? 0,
            'protein'  => $my_calories->protein ?? 0,
            'food_calories' => $schedule_details->calories ?? 0,
        ];

        foreach (['calories', 'carb', 'fat', 'protein'] as $macro) {
            $remaining = ($my_calories->$macro ?? 0) - ($schedule_details->$macro ?? 0);
            $percent = $macros[$macro] ? ($remaining / $macros[$macro]) * 100 : 0;
            $macros["remaining_{$macro}"] = $remaining;
            $macros["remaining_{$macro}_percent"] = round($percent, 2);
        }

        $meals = Meal::where('user_id', $user->id)->get();

            
        $data = ['macros' => $macros, 'meals' => MealHomeResource::collection($meals)];

        return response()->json(['status' => 'success', 'data' => $data, 'message' => '']);
    }
    
}
