<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{

    public function search(Request $request)
    {
        $searchValue = $request->input('searchValue');
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 10);

        $orders = Order::with('products') // Load related products
            ->where(function ($query) use ($searchValue) {
                $query->where('order_number', 'LIKE', "%{$searchValue}%")
                    ->orWhere('first_name', 'LIKE', "%{$searchValue}%")
                    ->orWhere('last_name', 'LIKE', "%{$searchValue}%")
                    ->orWhere('email', 'LIKE', "%{$searchValue}%")
                    ->orWhere('phone', 'LIKE', "%{$searchValue}%")
                    ->orWhere('city', 'LIKE', "%{$searchValue}%")
                    ->orWhere('company_name', 'LIKE', "%{$searchValue}%")
                    ->orWhere('status', 'LIKE', "%{$searchValue}%");
            })
            ->orderBy('created_at', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        return response()->json([
            'message' => 'Orders retrieved successfully.',
            'data' => $orders->items(),
            'total' => $orders->total(),
            'current_page' => $orders->currentPage(),
            'last_page' => $orders->lastPage(),
        ], Response::HTTP_OK);
    }


    public function createOrder(Request $request)
    {
        $ip = $request->ip();
        $oneHourAgo = Carbon::now()->subHour();

        $recentOrder = Order::where('ip_address', $ip)
            ->where('created_at', '>=', $oneHourAgo)
            ->exists();

        if ($recentOrder) {
            return response()->json(['message' => 'You can only place one order per hour.'], 429);
        }

        DB::beginTransaction();

        $lastOrderId = DB::table('orders')->max('id') ?? 0; // Récupère le dernier ID


        try {
            $order = Order::create([
                'order_number' => 'ORD' . str_pad($lastOrderId + 1, 6, '0', STR_PAD_LEFT),
                'first_name' => $request->formData['firstName'],
                'last_name' => $request->formData['lastName'],
                'email' => $request->formData['email'],
                'phone' => $request->formData['phone'],
                'city' => $request->formData['city'],
                'company_name' => $request->formData['company'] ?? null,
                'comments' => $request->formData['comments'] ?? null,
                'status' => 'pending',
                'ip_address' => $ip,
            ]);

            foreach ($request->cart as $product) {
                $productDetails = Product::find($product['id']);
                if ($productDetails) {
                    $order->products()->attach($product['id'], [
                        'quantity' => $product['quantity'] ?? 1,
                        'price' => $productDetails->price ?? 0,
                    ]);
                }
            }

            DB::commit();
            return response()->json(['message' => 'Order created successfully!', 'order' => $order], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Error processing order', 'error' => $e->getMessage()], 500);
        }
    }



    public function updateOrder(Request $request, $orderId)
    {
        $order = Order::find($orderId);

        if (!$order) {
            return response()->json(['message' => 'Order not found'], 404);
        }

        DB::beginTransaction();

        try {
            $order->update([
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'email' => $request->email,
                'phone' => $request->phone,
                'city' => $request->city,
                'status' => $request->status,
                'company_name' => $request->company_name ?? null,
                'comments' => $request->comments ?? null,
            ]);

            // Mise à jour des produits associés à la commande
            foreach ($request->products as $product) {
                $productDetails = Product::find($product['id']);

                if (!$productDetails) {
                    continue;
                }

                $price = $productDetails->price ?? 0;
                $quantity = $product['quantity'] ?? 1;

                if (isset($product['remove']) && $product['remove']) {
                    $order->products()->detach($product['id']);
                } else {
                    $order->products()->syncWithoutDetaching([
                        $product['id'] => [
                            'quantity' => $quantity,
                            'price' => $price,
                        ],
                    ]);
                }
            }

            DB::commit();

            return response()->json([
                'message' => 'Order updated successfully!',
                'order' => $order->load('products'),
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Error updating order', 'error' => $e->getMessage()], 500);
        }
    }




    public function destroy($id, Request $request)
    {

        $order = Order::find($id);

        if (!$order) {
            return response()->json(['message' => 'order not found or you don\'t have permission to delete this order.'], Response::HTTP_NOT_FOUND);
        }

        $order->deleted_at = now();
        $order->save();

        return response()->json(['message' => 'order deleted successfully.', 'data' => $order], Response::HTTP_OK);
    }
}
