<?php

namespace App\Http\Controllers;

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

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $orders = Order::where('user_id', auth()->id())
            ->with(['customer', 'products'])
            ->get();

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'total' => 'required|numeric|min:0',
            'status' => 'required|in:Pending,Paid,Canceled',
            'payment_method' => 'required|in:WhatsApp,Bank Transfer,QRIS',
            'date' => 'required|date',
            'products' => 'required|array|min:1',
            'products.*.product_id' => 'required|exists:products,id',
            'products.*.quantity' => 'required|integer|min:1',
            'products.*.price_at_time_of_purchase' => 'required|numeric|min:0',
        ]);

        // Verify customer exists
        $customer = Customer::findOrFail($request->customer_id);

        DB::beginTransaction();

        try {
            $order = Order::create([
                'user_id' => auth()->id(),
                'customer_id' => $request->customer_id,
                'total' => $request->total,
                'status' => $request->status,
                'payment_method' => $request->payment_method,
                'date' => $request->date,
            ]);

            // Attach products to order
            foreach ($request->products as $productData) {
                $order->products()->attach($productData['product_id'], [
                    'quantity' => $productData['quantity'],
                    'price_at_time_of_purchase' => $productData['price_at_time_of_purchase'],
                ]);
            }

            $order->load(['customer', 'products']);

            DB::commit();

            return response()->json($order, 201);
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json(['error' => 'Failed to create order'], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Request $request, string $id)
    {
        $order = Order::where('user_id', auth()->id())
            ->where('id', $id)
            ->with(['customer', 'products'])
            ->firstOrFail();

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $request->validate([
            'customer_id' => 'sometimes|required|exists:customers,id',
            'total' => 'sometimes|required|numeric|min:0',
            'status' => 'sometimes|required|in:Pending,Paid,Canceled',
            'payment_method' => 'sometimes|required|in:WhatsApp,Bank Transfer,QRIS',
            'date' => 'sometimes|required|date',
            'products' => 'sometimes|array',
            'products.*.product_id' => 'required|exists:products,id',
            'products.*.quantity' => 'required|integer|min:1',
            'products.*.price_at_time_of_purchase' => 'required|numeric|min:0',
        ]);

        $order = Order::where('user_id', auth()->id())
            ->where('id', $id)
            ->firstOrFail();

        DB::beginTransaction();

        try {
            // Verify customer exists if customer_id is being updated
            if ($request->has('customer_id')) {
                Customer::findOrFail($request->customer_id);
            }

            $order->update($request->only([
                'customer_id', 'total', 'status', 'payment_method', 'date'
            ]));

            // Update products if provided
            if ($request->has('products')) {
                $order->products()->detach();

                foreach ($request->products as $productData) {
                    $order->products()->attach($productData['product_id'], [
                        'quantity' => $productData['quantity'],
                        'price_at_time_of_purchase' => $productData['price_at_time_of_purchase'],
                    ]);
                }
            }

            $order->load(['customer', 'products']);

            DB::commit();

            return response()->json($order);
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json(['error' => 'Failed to update order'], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, string $id)
    {
        $order = Order::where('user_id', auth()->id())
            ->where('id', $id)
            ->firstOrFail();

        $order->delete();

        return response()->json(['message' => 'Order deleted successfully']);
    }
}
