<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\UsersIngredient;
use App\Pantry;
use App\Models\User;

class UsersIngredientsController extends Controller
{
    public function store(Request $request)
    {

        try {
            // Validate the request data
            $validated = $request->validate([
                'ingredients' => 'required|json',
                'user_id' => 'required',
            ]);

            // Create a new recipe instance
            $usersIngredient = new UsersIngredient();
            $usersIngredient->user_id = $validated['user_id'];
            $usersIngredient->ingredients = $validated['ingredients'];

            // Save the recipe to the database
            $usersIngredient->save();
            
            $user = User::find($validated['user_id']);
            if ($user) {
            $user->total_scans += 1; // Add new scans
            $user->save();
        }

            // Return a success response with the created recipe
            return response()->json([
                'message' => 'users Ingredient created successfully',
                'recipe' => $usersIngredient
            ], 201);

        } catch (ValidationException $e) {
            // Return a JSON response with the validation errors
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $e->errors(),
            ], 422);
        }  }

    // Get all recipes
    public function index()
    {
        $usersIngredient = UsersIngredient::all();

        if ($usersIngredient->isEmpty()) {
            return response()->json([], 204);
        }

        return response()->json($usersIngredient, 200);
    }
    
    public function getGlobalIngredientStatistics(Request $request)
{
    // Optional: Handle time range filtering
    $timeRange = $request->query('time_range');

    // Prepare the initial query for UsersIngredient
    $userIngredientsQuery = UsersIngredient::query();

    // Apply time range filter if provided
    if ($timeRange) {
        if ($timeRange === '24h') {
            $userIngredientsQuery->where('created_at', '>=', now()->subHours(24));
        } elseif ($timeRange === '7 days') {
            $userIngredientsQuery->where('created_at', '>=', now()->subDays(7));
        } elseif ($timeRange === '28 days') {
            $userIngredientsQuery->where('created_at', '>=', now()->subDays(28));
        } elseif ($timeRange === '12 months') {
            $userIngredientsQuery->where('created_at', '>=', now()->subMonths(12));
        }
    }

    // Retrieve the filtered users' ingredients
    $allUserIngredients = $userIngredientsQuery->get();

    // Aggregate ingredient counts
    $ingredientCount = [];

    foreach ($allUserIngredients as $userIngredient) {
        $ingredients = json_decode($userIngredient->ingredients, true) ?? [];
        foreach ($ingredients as $ingredient) {
            $ingredientLower = strtolower($ingredient);
            if (isset($ingredientCount[$ingredientLower])) {
                $ingredientCount[$ingredientLower] += 1;
            } else {
                $ingredientCount[$ingredientLower] = 1;
            }
        }
    }

    // Sort ingredients by count in descending order
    arsort($ingredientCount);

    // Limit to top 5 ingredients (adjust as needed)
    $topIngredients = array_slice($ingredientCount, 0, 15, true);

    // Return the results as JSON
    return response()->json($topIngredients);
}
/**
     * GET /api/pantry
     */
    public function listPantry()
    {
        return response()->json(
            Pantry::where('user_id', Auth::id())->get()
        );
    }

    /**
     * POST /api/pantry
     */
    public function addToPantry(Request $request)
    {
        $validated = $request->validate([
            'ingredient_title' => 'required|string',
            'image_url'        => 'nullable|string',
            'ingredient_url'   => 'nullable|string',
            'expired_date'     => 'nullable|date',
            'measurement'      => 'nullable|string|max:20',
            'count'            => 'nullable|integer|min:1',
        ]);

        $pantryItem = Pantry::create(array_merge(
            $validated,
            ['user_id' => Auth::id()]
        ));

        return response()->json($pantryItem, 201);
    }

    /**
     * PUT /api/pantry/{id}
     */
    public function updatePantryItem(Request $request, $id)
    {
        $pantryItem = Pantry::where('id', $id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $validated = $request->validate([
            'ingredient_title' => 'sometimes|string',
            'image_url'        => 'sometimes|string|nullable',
            'ingredient_url'   => 'sometimes|string|nullable',
            'expired_date'     => 'sometimes|date|nullable',
            'measurement'      => 'sometimes|string|max:20|nullable',
            'count'            => 'sometimes|integer|min:1|nullable',
        ]);

        $pantryItem->update($validated);

        return response()->json($pantryItem);
    }

    /**
     * DELETE /api/pantry/{id}
     */
    public function removeFromPantry($id)
    {
        $pantryItem = Pantry::where('id', $id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $pantryItem->delete();

        return response()->json([
            'message' => 'Pantry item removed successfully'
        ]);
    }
    
    public function getPantryByExpiration(Request $request)
{
    $request->validate([
        'type' => 'required|in:expired,valid,expiring_soon',
        'days' => 'nullable|integer|min:1',
    ]);

    $query = Pantry::where('user_id', Auth::id());

    switch ($request->type) {
        case 'expired':
            $query->whereNotNull('expired_date')
                  ->where('expired_date', '<', now());
            break;

        case 'valid':
            $query->where(function ($q) {
                $q->whereNull('expired_date')
                  ->orWhere('expired_date', '>=', now());
            });
            break;

        case 'expiring_soon':
            $days = $request->get('days', 7);
            $query->whereBetween('expired_date', [
                now(),
                now()->addDays($days)
            ]);
            break;
    }

    return response()->json(
        $query->orderBy('expired_date', 'asc')->get()
    );
}
}
