<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Resources\OrderplacedResource;
use App\Http\Resources\WishlistResource;
use App\Models\OrderDetails;
use Illuminate\Http\Request;
use App\Models\Wishlist;
use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class WishlistController extends Controller
{
       
    public function order_place(Request $request)
    {
        $quantity = array_map('intval', $request->input('quantity'));
        $amount = array_map('floatval', $request->input('amount'));
    
        $validated = $request->validate([
            'product_details_id.*'   => 'required|string',
            'product_details_name.*' => 'required|string',
            'quantity.*'             => 'sometimes|required|integer|min:1',
            'amount.*'               => 'sometimes|required|numeric|min:0.01',
            'user_id'                => 'required|integer',
            'user_name'              => 'required|string',
            'delivery_address'       => 'required|string',
            'instruction'            => 'nullable|string',
            'category_id'            => 'nullable|string',
            'category_name'          => 'nullable|string',
        ]);
    
        try {
            $idsArray        = $validated['product_details_id'];
            $namesArray      = $validated['product_details_name'];
            $quantitiesArray = $quantity;
            $amountsArray    = $amount;
    
            $totalAmount = 0;
            foreach ($quantitiesArray as $key => $quantity) {
                $totalAmount += $quantity * $amountsArray[$key];
            }
    
            $idsString        = implode('~', $idsArray);
            $namesString      = implode('~', $namesArray);
            $quantitiesString = implode('~', $quantitiesArray);
    
            $order = OrderDetails::create([
                'order_date'           => now(),
                'user_id'              => $validated['user_id'],
                'user_name'            => $validated['user_name'],
                'category_id'          => optional($validated['category_id']),
                'category_name'        => optional($validated['category_name']),
                'product_details_id'   => $idsString,
                'product_details_name' => $namesString,
                'quantity'             => $quantitiesString,
                'amount'               => $totalAmount,
                'delivery_address'     => $validated['delivery_address'],
                'instruction'          => optional($validated['instruction']),
            ]);
    
            return response()->json([
                'status'  => 'success',
                'message' => 'Order placed successfully',
                'data'    => new OrderplacedResource($order),
                'code'    => 200,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Failed to place order',
                'code'    => 500,
            ]);
        }
    }
    public function wishlist_create(Request $request)
    {
        try {
            if (!auth()->guard('sanctum')->check()) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Please login!',
                    'data'    => [],
                    'code'    => 401,
                ]);
            }
            $user    = auth()->guard('sanctum')->user();
            $product = Product::where('id', $request->product_id)->first();
            if (!$product) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Product not found',
                    'data'    => WishlistResource::collection($product),
                    'code'    => 404,
                ]);
            }
            $wishlistItem = new Wishlist([
                'user_id'      => $user->id,
                'product_id'   => $request->product_id,
                'product_name' => $product->title
            ]);
            $wishlistItem->save();
            return response()->json([
                'status'  => 'success',
                'message' => 'Product added to wishlist',
                'data'    => [
                    'wishlist_id'  => $wishlistItem->id,
                    'product_id'   => $wishlistItem->product_id,
                    'product_name' => $wishlistItem->product_name,
                ],
                'code' => 201,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to add product to wishlist', ['error' => $e->getMessage()]);
            return response()->json([
                'status'  => 'error',
                'message' => 'Failed to add product to wishlist',
                'data'    => [],
                'code'    => 500,
            ]);
        }
    }

    public function wishlist_delete($product_id)
    {
        $wishlist = Wishlist::where('product_id', $product_id)->first();
        if ($wishlist) {
            $wishlist->delete();
            return response()->json([
                'status'  => 'success',
                'message' => 'Product removed from wishlist',
                'data'    => WishlistResource::collection($wishlist),
                'code'    => 200,
            ]);
        }
        return response()->json([
            'status'  => 'error',
            'message' => 'Error not found',
            'data'    => WishlistResource::collection($wishlist),
            'code'    => 404,
        ]);
    }

    public function wishlist_display()
    {
        $user          = Auth::user();
        $wishlistItems = Wishlist::all();
        return response()->json([
            'status'  => 'success',
            'data'    => WishlistResource::collection($wishlistItems),
            'message' => 'Wishlist items retrieved successfully',
            'code'    => 200
        ], 200);
    }
}