<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Category;
use App\Models\Transaction;
use App\Models\TransactionItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class KasirController extends Controller
{
    public function __construct()
    {
        // Pastikan user sudah login
        if (!Auth::check()) {
            abort(403, 'Unauthorized. Please login first.');
        }
    }

    public function dashboard(Request $request)
    {
        $categories = Category::all();
        
        // Filter products by category if selected
        $query = Product::with('category')->where('stock', '>', 0);
        
        if ($request->has('category') && $request->category != '') {
            $query->where('category_id', $request->category);
        }
        
        $products = $query->orderBy('name')->get();
        
        return view('kasir.dashboard', compact('categories', 'products'));
    }
    
    public function addToCart(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
        ]);
        
        $product = Product::find($request->product_id);
        
        if (!$product || $product->stock <= 0) {
            return back()->with('error', 'Produk tidak tersedia atau stok habis!');
        }
        
        $cart = session()->get('cart', []);
        
        // Check if product already in cart
        $found = false;
        foreach ($cart as &$item) {
            if ($item['product_id'] == $product->id) {
                if ($item['quantity'] < $product->stock) {
                    $item['quantity']++;
                    $found = true;
                } else {
                    return back()->with('error', 'Stok tidak mencukupi!');
                }
                break;
            }
        }
        
        // If not found, add new item
        if (!$found) {
            $cart[] = [
                'product_id' => $product->id,
                'name' => $product->name,
                'price' => $product->price,
                'quantity' => 1,
                'stock' => $product->stock
            ];
        }
        
        session()->put('cart', $cart);
        
        return back()->with('success', $product->name . ' ditambahkan ke keranjang!');
    }
    
    public function updateCart(Request $request)
    {
        $request->validate([
            'index' => 'required|integer',
            'action' => 'required|in:increase,decrease',
        ]);
        
        $cart = session()->get('cart', []);
        $index = $request->index;
        
        if (!isset($cart[$index])) {
            return back()->with('error', 'Item tidak ditemukan di keranjang!');
        }
        
        $item = &$cart[$index];
        $product = Product::find($item['product_id']);
        
        if ($request->action === 'increase') {
            if ($item['quantity'] < $product->stock) {
                $item['quantity']++;
            } else {
                return back()->with('error', 'Stok tidak mencukupi!');
            }
        } else {
            $item['quantity']--;
            if ($item['quantity'] <= 0) {
                unset($cart[$index]);
                $cart = array_values($cart); // Re-index array
            }
        }
        
        session()->put('cart', $cart);
        
        return back();
    }
    
    public function removeFromCart(Request $request)
    {
        $request->validate([
            'index' => 'required|integer',
        ]);
        
        $cart = session()->get('cart', []);
        $index = $request->index;
        
        if (isset($cart[$index])) {
            $itemName = $cart[$index]['name'];
            unset($cart[$index]);
            $cart = array_values($cart); // Re-index array
            session()->put('cart', $cart);
            
            return back()->with('success', $itemName . ' dihapus dari keranjang!');
        }
        
        return back()->with('error', 'Item tidak ditemukan di keranjang!');
    }
    
    public function clearCart()
    {
        session()->forget('cart');
        return back()->with('success', 'Keranjang dikosongkan!');
    }
    
    public function processTransaction(Request $request)
    {
        $cart = session()->get('cart', []);
        
        if (empty($cart)) {
            return back()->with('error', 'Keranjang kosong!');
        }
        
        // Calculate total from cart
        $totalAmount = 0;
        foreach ($cart as $item) {
            $totalAmount += $item['price'] * $item['quantity'];
        }
        
        $request->validate([
            'payment_amount' => 'required|numeric|min:' . $totalAmount,
        ]);
        
        DB::beginTransaction();
        
        try {
            // Validate stock for each item
            foreach ($cart as $item) {
                $product = Product::find($item['product_id']);
                if (!$product || $product->stock < $item['quantity']) {
                    DB::rollBack();
                    return back()->with('error', "Stok produk {$item['name']} tidak mencukupi!");
                }
            }
            
            // Create transaction
            $transaction = Transaction::create([
                'user_id' => Auth::id(),
                'total_amount' => $totalAmount,
                'payment_amount' => $request->payment_amount,
                'change_amount' => $request->payment_amount - $totalAmount,
                'transaction_date' => now(),
            ]);
            
            // Save transaction items and update stock
            foreach ($cart as $item) {
                $product = Product::find($item['product_id']);
                
                TransactionItem::create([
                    'transaction_id' => $transaction->id,
                    'product_id' => $item['product_id'],
                    'quantity' => $item['quantity'],
                    'price' => $product->price,
                    'subtotal' => $product->price * $item['quantity'],
                ]);
                
                // Update product stock
                $product->decrement('stock', $item['quantity']);
            }
            
            // Clear cart
            session()->forget('cart');
            
            DB::commit();
            
            // Redirect to order detail page instead of dashboard
            return redirect()->route('kasir.order-detail', $transaction->id)
                ->with('success', 'Transaksi berhasil diproses!');
            
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Terjadi kesalahan saat memproses transaksi: ' . $e->getMessage());
        }
    }
    
    // New method for showing order detail
    public function orderDetail($id)
    {
        $transaction = Transaction::with(['transactionItems.product', 'user'])
            ->findOrFail($id);
        
        // Only allow viewing own transactions or admin can view all
        if (Auth::id() !== $transaction->user_id && Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized to view this transaction.');
        }
        
        return view('kasir.order-detail', compact('transaction'));
    }
}