<?php

namespace App\Http\Controllers;

use App\Models\Commande;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function checkout()
    {
        $cart = session()->get('cart', []);
        
        if (empty($cart)) {
            return redirect()->route('cart.index')->with('error', 'Votre panier est vide.');
        }
        
        $total = 0;
        foreach ($cart as $item) {
            $total += $item['prix'] * $item['quantite'];
        }
        
        return view('orders.checkout', compact('cart', 'total'));
    }

    public function store(Request $request)
    {
        $cart = session()->get('cart', []);
        
        if (empty($cart)) {
            return redirect()->route('cart.index')->with('error', 'Votre panier est vide.');
        }

        // Validation for guests
        if (!Auth::check()) {
            $request->validate([
                'name_client' => 'required|string|max:255',
                'prenom_client' => 'required|string|max:255',
                'telephone_client' => 'required|string|digits:10',
                'adresse_client' => 'required|string|max:500',
            ]);
        }
        
        $total = 0;
        foreach ($cart as $product_id => $item) {
            $product = Product::find($product_id);
            if (!$product || $item['quantite'] > $product->en_stock) {
                return redirect()->route('cart.index')->with('error', "Le stock pour le produit '{$item['nom']}' a changé. Veuillez ajuster votre panier.");
            }
            $total += $item['prix'] * $item['quantite'];
        }
        
        DB::beginTransaction();
        
        try {
            // Create order
            $orderData = [
                'total' => $total,
                'created_at' => now(),
                'statut' => 'en_attente'
            ];

            if (Auth::check()) {
                $orderData['user_id'] = Auth::id();
            } else {
                $orderData['name_client'] = $request->name_client;
                $orderData['prenom_client'] = $request->prenom_client;
                $orderData['telephone_client'] = $request->telephone_client;
                $orderData['adresse_client'] = $request->adresse_client;
            }

            $commande = Commande::create($orderData);
            
            // Create order items
            foreach ($cart as $product_id => $item) {
                OrderItem::create([
                    'commande_id' => $commande->id,
                    'product_id' => $product_id,
                    'quantite' => $item['quantite'],
                    'prix_unitaire' => $item['prix']
                ]);
            }
            
            DB::commit();
            
            // Clear cart
            session()->forget('cart');
            
            return redirect()->route('orders.confirmation', $commande->id);
            
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->route('cart.index')->with('error', 'Une erreur est survenue lors de la commande.');
        }
    }

    public function confirmation($id)
    {
        $commande = Commande::with('products')->findOrFail($id);
        
        // Ensure user can only see their own orders if logged in
        if ($commande->user_id && $commande->user_id !== Auth::id()) {
            abort(403);
        }
        
        return view('orders.confirmation', compact('commande'));
    }

    public function index()
    {
        $commandes = Commande::where('user_id', Auth::id())
                             ->orderBy('created_at', 'desc')
                             ->get();
        
        return view('orders.index', compact('commandes'));
    }
}
