<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Transaksi;
use App\Models\TransaksiItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CheckoutController extends Controller
{
    public function index()
    {
        $cartItems = Cart::where('user_id', Auth::id())
            ->with('menu')
            ->get();
        
        if($cartItems->isEmpty()) {
            return redirect()->route('menu.index')->with('error', 'Keranjang belanja kosong!');
        }

        $totals = Cart::calculateTotals($cartItems);

        return view('checkout', compact('cartItems', 'totals'));
    }

    public function process(Request $request)
    {
        $request->validate([
            'payment_method' => 'required|in:cash,transfer,qris',
            'notes' => 'nullable|string|max:500'
        ]);

        try {
            DB::beginTransaction();

            $cartItems = Cart::where('user_id', Auth::id())
                ->with('menu')
                ->get();

            if($cartItems->isEmpty()) {
                return redirect()->route('menu.index')->with('error', 'Keranjang belanja kosong!');
            }

            $totals = Cart::calculateTotals($cartItems);

            // Buat transaksi baru
            $transaksi = Transaksi::create([
                'user_id' => Auth::id(),
                'transaction_code' => 'TRX-' . time(),
                'tax_amount' => $totals['tax'],
                'service_charge' => $totals['service'],
                'final_amount' => $totals['final'],
                'payment_method' => $request->payment_method,
                'notes' => $request->notes
            ]);

            // Simpan item transaksi
            foreach($cartItems as $item) {
                TransaksiItem::create([
                    'transaksi_id' => $transaksi->id,
                    'menu_id' => $item->menu_id,
                    'menu_name' => $item->menu->name,
                    'quantity' => $item->quantity,
                    'price' => $item->price,
                    'subtotal' => $item->subtotal,
                    'notes' => $item->notes
                ]);
            }

            // Kosongkan cart
            Cart::where('user_id', Auth::id())->delete();

            DB::commit();

            return redirect()->route('transaksi.show', $transaksi->id)
                ->with('success', 'Pesanan berhasil diproses!');

        } catch(\Exception $e) {
            DB::rollback();
            return redirect()->back()
                ->with('error', 'Terjadi kesalahan saat memproses pesanan. Silakan coba lagi.');
        }
    }
}