<?php

namespace App\Http\Controllers;

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

class OrdersController extends Controller
{
    public function index(Request $request)
    {
        $orders = Order::query()
            ->with(['user', 'items.product', 'shippingCost'])
            ->when($request->search, function ($query, $search) {
                $query->where(function ($q) use ($search) {
                    $q->where('order_code', 'like', "%{$search}%")
                      ->orWhereHas('user', function ($q) use ($search) {
                          $q->where('name', 'like', "%{$search}%")
                            ->orWhere('email', 'like', "%{$search}%");
                      })
                      ->orWhere('shipping_address', 'like', "%{$search}%");
                });
            })
            ->when($request->status, function ($query, $status) {
                $query->where('status', $status);
            })
            ->latest()
            ->paginate(10)
            ->withQueryString();

        $products = Product::all();

        return view('admin.order', compact('orders', 'products'));
    }

    public function updateStatus(Request $request, Order $order)
    {
        try {
            $validated = $request->validate([
                'status' => ['required', 'string'],
            ]);

            $order->updateStatus($validated['status']);

            return redirect()->back()->with('success', "Order {$order->order_code} status updated to {$validated['status']}");
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function updateItem(Request $request, Order $order)
    {
        try {
            DB::beginTransaction();

            $validated = $request->validate([
                'items' => ['required', 'array'],
                'items.*.id' => ['required', 'exists:order_items,id'],
                'items.*.product_id' => ['required', 'exists:products,id'],
                'items.*.quantity' => ['required', 'integer', 'min:1'],
            ]);

            foreach ($validated['items'] as $itemData) {
                $orderItem = $order->items()->findOrFail($itemData['id']);
                $product = Product::findOrFail($itemData['product_id']);

                $orderItem->update([
                    'product_id' => $itemData['product_id'],
                    'quantity' => $itemData['quantity'],
                    'price' => $product->price,
                ]);
            }

            $order->calculateTotal();

            DB::commit();

            return redirect()->back()->with('success', 'Order items updated successfully');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
