<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_name'  => 'required|string|max:255',
            'customer_phone' => 'required|string|max:20',
            'notes'          => 'nullable|string|max:1000',
            'product_id'     => 'required|exists:products,id',
            'quantity'       => 'required|integer|min:1|max:100',
        ]);

        $product = Product::findOrFail($validated['product_id']);

        if (! $product->is_active) {
            return back()->with('error', 'Désolé, ce produit n\'est plus disponible.');
        }

        $subtotal = $product->price * $validated['quantity'];

        $order = Order::create([
            'customer_name'    => $validated['customer_name'],
            'customer_email'   => null,
            'customer_phone'   => $validated['customer_phone'],
            'customer_address' => 'Non précisé',
            'notes'            => $validated['notes'] ?? null,
            'total_amount'     => $subtotal,
            'status'           => 'pending',
        ]);

        $order->items()->create([
            'product_id'   => $product->id,
            'product_name' => $product->name,
            'quantity'     => $validated['quantity'],
            'unit_price'   => $product->price,
            'subtotal'     => $subtotal,
        ]);

        return back()->with('success', "Votre commande #{$order->order_number} a été passée avec succès ! Nous vous contacterons bientôt.");
    }
}
