<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class LaundryItemController extends Controller
{
    // __invoke method to handle the route for indexApi
     public function __invoke(Request $request)
    {
        $laundryItems = DB::table('laundry_items')->get();  // Retrieve all laundry items

        return response()->json($laundryItems);  // Return as JSON response
    }


    // Show the list of laundry items in a view
public function index()
{
    // Get all laundry items from the 'laundry_items' table
    $laundryItems = DB::table('laundry_items')->get();

    // Initialize an empty array for orders that have been used
    $ordersWithUsedItems = [];

    // Loop through each laundry item and check its usage in orders
    foreach ($laundryItems as $laundryItem) {
        // Get the liquid name from the laundry item (note the lowercase 'liquid_name')
        $liquidName = $laundryItem->liquid_name;

        // Fetch orders that used either anti_germs_liquid or cloth_softener based on liquid_name
        $orders = DB::table('orders')
            ->where(function ($query) use ($liquidName) {
                if ($liquidName == 'anti_germs_liquid') {
                    $query->where('anti_germs_liquid', 1);
                } elseif ($liquidName == 'cloth_softener') {
                    $query->where('cloth_softener', 1);
                }
            })
            ->get(['id as order_idS', 'order_id', 'user_id', 'vendor_id', 'anti_germs_liquid', 'cloth_softener']);

        // Merge the fetched orders with the existing ones and remove duplicates by 'order_id'
        foreach ($orders as $order) {
            // If the order ID doesn't exist in the array, add it
            if (!isset($ordersWithUsedItems[$order->order_id])) {
                $ordersWithUsedItems[$order->order_id] = [
                    'order_idS' => $order->order_idS,  // the actual 'id' of the order from the orders table
                    'order_id' => $order->order_id,    // the custom 'order_id' field
                    'user_id' => $order->user_id,
                    'vendor_id' => $order->vendor_id,
                    'anti_germs_liquid' => $order->anti_germs_liquid,
                    'cloth_softener' => $order->cloth_softener,
                ];
            } else {
                // If the order ID exists, update the liquid usage
                $ordersWithUsedItems[$order->order_id]['anti_germs_liquid'] = $ordersWithUsedItems[$order->order_id]['anti_germs_liquid'] || $order->anti_germs_liquid;
                $ordersWithUsedItems[$order->order_id]['cloth_softener'] = $ordersWithUsedItems[$order->order_id]['cloth_softener'] || $order->cloth_softener;
            }
        }
    }

    // Return the view with both laundry items and their usage status
    return view('laundry_items.index', compact('laundryItems', 'ordersWithUsedItems'));
}





    // API endpoint to fetch laundry items and format them as camelCase
   public function indexApi()
    {
        $laundryItems = DB::table('laundry_items')->get();  // Get all laundry items from DB

        // Transform keys to camelCase and capitalize the first letter
        $formattedItems = $laundryItems->map(function ($item) {
            $itemArray = (array) $item;  // Convert the object to an array
            $formattedItem = [];

            // Loop through each key and format it
            foreach ($itemArray as $key => $value) {
                // Convert the key to camelCase with the first letter capitalized
                $newKey = ucfirst(Str::camel($key));  // Use Str::camel() to convert to camelCase
                $formattedItem[$newKey] = $value;
            }

            // Format the LiquidName (Replace underscores and capitalize each word)
            if (isset($formattedItem['LiquidName'])) {
                // Replace underscores with spaces and capitalize each word
                $formattedItem['LiquidName'] = ucwords(str_replace('_', ' ', $formattedItem['LiquidName']));
            }

            return (object) $formattedItem;  // Convert the formatted array back to an object
        });

        return response()->json($formattedItems);  // Return the formatted data as JSON
    }


    // Store a new laundry item
    public function store(Request $request)
    {
        $request->validate([
            'liquid_name' => 'required|string|max:255',
            'price' => 'required|numeric',
            'number_of_clothes' => 'required|integer',
        ]);

        DB::table('laundry_items')->insert([
            'liquid_name' => $request->input('liquid_name'),
            'price' => $request->input('price'),
            'number_of_clothes' => $request->input('number_of_clothes'),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->route('laundry-items.index')->with('success', 'Laundry item created successfully!');
    }

    // Show the form for editing a laundry item
    public function edit($id)
    {
        $laundryItem = DB::table('laundry_items')->where('id', $id)->first();  // Get the laundry item by ID
        return view('laundry_items.edit', compact('laundryItem'));  // Pass to edit view
    }

    // Update an existing laundry item
    public function update(Request $request, $id)
    {
        $request->validate([
            'liquid_name' => 'required|string|max:255',
            'price' => 'required|numeric',
            'number_of_clothes' => 'required|integer',
        ]);

        DB::table('laundry_items')
            ->where('id', $id)
            ->update([
                'liquid_name' => $request->input('liquid_name'),
                'price' => $request->input('price'),
                'number_of_clothes' => $request->input('number_of_clothes'),
                'updated_at' => now(),
            ]);

        return redirect()->route('laundry-items.index')->with('success', 'Laundry item updated successfully!');
    }

    // Delete a laundry item
    public function destroy($id)
    {
        DB::table('laundry_items')->where('id', $id)->delete();  // Delete the laundry item by ID
        return redirect()->route('laundry-items.index')->with('success', 'Laundry item deleted successfully!');
    }
}
