<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Mail\OrderPlaced;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Stripe\Stripe;
use Stripe\PaymentIntent;

class CheckoutController extends Controller
{
    public function process(Request $request)
    {
        $request->validate([
            'items' => 'required|array|min:1',
            'items.*.id' => 'required|exists:products,id',
            'items.*.quantity' => 'required|integer|min:1',
            'customer_name' => 'required|string|max:255',
            'customer_email' => 'required|email|max:255',
            'customer_phone' => 'required|string|max:20',
            'shipping_address' => 'required|string',
            'payment_method' => 'required|in:stripe,cod',
        ]);

        try {
            return DB::transaction(function () use ($request) {
                $totalAmount = 0;
                $orderItems = [];

                foreach ($request->items as $item) {
                    $product = Product::findOrFail($item['id']);

                    // Simple stock check (optional, but good)
                    if ($product->stock_quantity < $item['quantity']) {
                        throw new \Exception("Product {$product->title} is out of stock.");
                    }

                    $price = $product->discount_price > 0 ? $product->discount_price : $product->price;
                    $totalAmount += $price * $item['quantity'];

                    $orderItems[] = [
                        'product_id' => $product->id,
                        'quantity' => $item['quantity'],
                        'price' => $price,
                    ];
                }

                $order = Order::create([
                    'user_id' => auth('sanctum')->id(), // Optional if logged in
                    'order_number' => 'ORD-' . strtoupper(uniqid()),
                    'total_amount' => $totalAmount,
                    'final_amount' => $totalAmount,
                    'status' => 'pending',
                    'payment_method' => $request->payment_method,
                    'payment_status' => 'pending',
                    'customer_name' => $request->customer_name,
                    'customer_email' => $request->customer_email,
                    'customer_phone' => $request->customer_phone,
                    'shipping_address' => $request->shipping_address,
                    'notes' => $request->notes,
                ]);

                foreach ($orderItems as $itemData) {
                    $order->items()->create($itemData);

                    // Decrement stock
                    Product::where('id', $itemData['product_id'])->decrement('stock_quantity', $itemData['quantity']);
                }

                if ($request->payment_method === 'stripe') {
                    $stripeSecret = get_setting('STRIPE_SECRET', config('services.stripe.secret'));
                    if (empty($stripeSecret)) {
                        throw new \Exception("Stripe is not configured correctly.");
                    }

                    Stripe::setApiKey($stripeSecret);

                    $intent = PaymentIntent::create([
                        'amount' => (int)($totalAmount * 100), // cents
                        'currency' => 'usd',
                        'metadata' => [
                            'order_id' => $order->id,
                            'order_number' => $order->order_number,
                        ],
                    ]);

                    return response()->json([
                        'status' => 'success',
                        'message' => 'Order created, proceed to payment.',
                        'order_id' => $order->id,
                        'client_secret' => $intent->client_secret,
                    ]);
                }

                // COD Flow
                Mail::to($order->customer_email)->send(new OrderPlaced($order));

                return response()->json([
                    'status' => 'success',
                    'message' => 'Order placed successfully (COD).',
                    'order_id' => $order->id,
                ]);
            });
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
            ], 400);
        }
    }
}
