<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Product;
use App\Models\Deal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class CartController extends Controller
{
    // Helper method to check if a product is in an active deal
    private function getActiveDealForProduct($productId)
    {
        $now = Carbon::now();
        
        $deal = Deal::where('is_active', true)
            ->where('start_date', '<=', $now)
            ->where('end_date', '>=', $now)
            ->whereHas('products', function ($query) use ($productId) {
                $query->where('product_id', $productId);
            })
            ->first();
        
        return $deal;
    }
    
    // Calculate deal price for a product
    private function calculateDealPrice($product, $deal)
    {
        $originalPrice = $product->price;
        
        if (!$deal) {
            // No deal - use regular price
            return [
                'price' => $originalPrice,
                'original_price' => $originalPrice,
                'deal_id' => null,
                'deal_type' => null,
                'discount_value' => null,
                'is_deal' => false,
            ];
        }
        
        // Check if deal is active
        $now = Carbon::now();
        if ($deal->start_date > $now || $deal->end_date < $now || !$deal->is_active) {
            // Deal is not active
            return [
                'price' => $originalPrice,
                'original_price' => $originalPrice,
                'deal_id' => null,
                'deal_type' => null,
                'discount_value' => null,
                'is_deal' => false,
            ];
        }
        
        // Calculate deal price
        switch ($deal->type) {
            case 'percentage':
                $discount = ($deal->discount_value / 100) * $originalPrice;
                $finalPrice = $originalPrice - $discount;
                break;
                
            case 'fixed':
                $finalPrice = max(0, $originalPrice - $deal->discount_value);
                $discount = $deal->discount_value;
                break;
                
            case 'bundle':
                // For bundle deals, you might want different logic
                $finalPrice = $originalPrice; // Or implement bundle pricing
                $discount = 0;
                break;
                
            default:
                $finalPrice = $originalPrice;
                $discount = 0;
        }
        
        return [
            'price' => $finalPrice,
            'original_price' => $originalPrice,
            'deal_id' => $deal->id,
            'deal_type' => $deal->type,
            'discount_value' => $deal->discount_value,
            'is_deal' => true,
            'discount_amount' => $originalPrice - $finalPrice,
        ];
    }
    
    // Add item to cart
    public function add(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
            'deal_id' => 'nullable|exists:deals,id', // NEW: Optional deal ID
        ]);
        
        $product = Product::findOrFail($request->product_id);
        
        // Check stock
        if ($product->stock < $request->quantity) {
            return response()->json([
                'success' => false,
                'message' => 'Insufficient stock available. Only ' . $product->stock . ' items left.'
            ], 400);
        }
        
        // Check for active deal
        $deal = null;
        if ($request->has('deal_id') && $request->deal_id) {
            // If deal_id is provided, use that deal
            $deal = Deal::where('id', $request->deal_id)
                ->where('is_active', true)
                ->where('start_date', '<=', Carbon::now())
                ->where('end_date', '>=', Carbon::now())
                ->first();
        } else {
            // Otherwise check if product is in any active deal
            $deal = $this->getActiveDealForProduct($product->id);
        }
        
        // Calculate price (with deal if applicable)
        $priceInfo = $this->calculateDealPrice($product, $deal);
        
        if (Auth::check()) {
            // User is logged in - store in database
            $cartItem = Cart::where('user_id', Auth::id())
                ->where('product_id', $request->product_id)
                ->where('deal_id', $priceInfo['deal_id']) // Important: Different deals = different cart items
                ->first();
            
            if ($cartItem) {
                // Update existing item
                $newQuantity = $cartItem->quantity + $request->quantity;
                
                // Check stock again with new quantity
                if ($product->stock < $newQuantity) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Cannot add more. You already have ' . $cartItem->quantity . ' in cart. Only ' . $product->stock . ' items total available.'
                    ], 400);
                }
                
                $cartItem->quantity = $newQuantity;
                $cartItem->save();
            } else {
                // Create new cart item with deal info
                $cartItem = Cart::create([
                    'user_id' => Auth::id(),
                    'product_id' => $request->product_id,
                    'quantity' => $request->quantity,
                    'original_price' => $priceInfo['original_price'],
                    'deal_id' => $priceInfo['deal_id'],
                    'deal_type' => $priceInfo['deal_type'],
                    'deal_discount_value' => $priceInfo['discount_value'],
                ]);
            }
            
            // Get updated cart count
            $cartCount = Cart::where('user_id', Auth::id())->sum('quantity');
            
            return response()->json([
                'success' => true,
                'message' => $priceInfo['is_deal'] ? 'Product added to cart with deal price!' : 'Product added to cart successfully.',
                'cart_count' => $cartCount,
                'deal_applied' => $priceInfo['is_deal'],
                'deal_price' => $priceInfo['price'],
                'original_price' => $priceInfo['original_price'],
                'savings' => $priceInfo['is_deal'] ? $priceInfo['original_price'] - $priceInfo['price'] : 0,
            ]);
            
        } else {
            // Guest user - store in session
            $cart = session()->get('cart', []);
            
            // Create a unique key that includes deal_id to differentiate between regular and deal items
            $cartKey = $request->product_id . '_' . ($priceInfo['deal_id'] ?? 'regular');
            
            if (isset($cart[$cartKey])) {
                $newQuantity = $cart[$cartKey]['quantity'] + $request->quantity;
                
                // Check stock for guest too
                if ($product->stock < $newQuantity) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Cannot add more. You already have ' . $cart[$cartKey]['quantity'] . ' in cart. Only ' . $product->stock . ' items available.'
                    ], 400);
                }
                
                $cart[$cartKey]['quantity'] = $newQuantity;
            } else {
                $cart[$cartKey] = [
                    'product_id' => $product->id,
                    'quantity' => $request->quantity,
                    'name' => $product->name,
                    'price' => $priceInfo['price'], // Store the calculated price
                    'original_price' => $priceInfo['original_price'], // Store original price (always set)
                    'deal_id' => $priceInfo['deal_id'],
                    'deal_type' => $priceInfo['deal_type'],
                    'deal_discount_value' => $priceInfo['discount_value'],
                    'image' => $product->image,
                    'cart_key' => $cartKey, // Store the key for reference
                ];
            }
            
            session()->put('cart', $cart);
            
            // Calculate guest cart count
            $cartCount = 0;
            foreach ($cart as $item) {
                $cartCount += $item['quantity'];
            }
            
            return response()->json([
                'success' => true,
                'message' => $priceInfo['is_deal'] ? 'Product added to cart with deal price!' : 'Product added to cart successfully.',
                'cart_count' => $cartCount,
                'deal_applied' => $priceInfo['is_deal'],
                'deal_price' => $priceInfo['price'],
                'original_price' => $priceInfo['original_price'],
                'savings' => $priceInfo['is_deal'] ? $priceInfo['original_price'] - $priceInfo['price'] : 0,
            ]);
        }
    }
    
    // Get cart count for header
    public function count()
    {
        if (Auth::check()) {
            // Get count from database for logged in user
            $cartCount = Cart::where('user_id', Auth::id())->sum('quantity');
        } else {
            // Get count from session for guest
            $cart = session()->get('cart', []);
            $cartCount = 0;
            foreach ($cart as $item) {
                $cartCount += $item['quantity'];
            }
        }
        
        return response()->json([
            'cart_count' => $cartCount
        ]);
    }
    
    // View cart page
    public function view()
    {
        // Temporary fix for existing session cart data
        if (!Auth::check() && session()->has('cart')) {
            $cart = session()->get('cart', []);
            $updated = false;
            
            foreach ($cart as $key => &$item) {
                if (!isset($item['original_price'])) {
                    $product = Product::find($item['product_id']);
                    if ($product) {
                        $item['original_price'] = $product->price;
                        $updated = true;
                    }
                }
            }
            
            if ($updated) {
                session()->put('cart', $cart);
            }
        }
        
        if (Auth::check()) {
            // Get cart items from database
            $cartItems = Cart::with(['product', 'deal'])
                ->where('user_id', Auth::id())
                ->get();
        } else {
            // Get cart items from session
            $sessionCart = session()->get('cart', []);
            $cartItems = collect();
            
            foreach ($sessionCart as $key => $item) {
                $product = Product::find($item['product_id']);
                if ($product) {
                    // Create a mock cart item object with all necessary properties
                    $cartItem = (object)[
                        'product' => $product,
                        'quantity' => $item['quantity'],
                        'id' => null, // No database ID for session items
                        'original_price' => $item['original_price'] ?? $product->price, // Default to product price if not set
                        'deal_id' => $item['deal_id'] ?? null,
                        'deal_type' => $item['deal_type'] ?? null,
                        'deal_discount_value' => $item['deal_discount_value'] ?? null,
                        'cart_key' => $item['cart_key'] ?? $key,
                    ];
                    
                    // Add calculated properties
                    $cartItem->actual_price = $item['price'] ?? $product->price;
                    $cartItem->total_price = ($item['price'] ?? $product->price) * $item['quantity'];
                    $cartItem->has_deal = !empty($item['deal_id']);
                    
                    $cartItems->push($cartItem);
                }
            }
        }
        
        // Calculate totals
        $subtotal = 0;
        $totalDiscount = 0;
        $originalSubtotal = 0;
        
        foreach ($cartItems as $item) {
            $itemPrice = $item->actual_price ?? $item->product->price;
            $originalPrice = $item->original_price ?? $item->product->price;
            $subtotal += $itemPrice * $item->quantity;
            $originalSubtotal += $originalPrice * $item->quantity;
            
            // Calculate discount if deal exists
            if ($originalPrice > $itemPrice) {
                $totalDiscount += ($originalPrice - $itemPrice) * $item->quantity;
            }
        }
        
        return view('cart', compact('cartItems', 'subtotal', 'totalDiscount', 'originalSubtotal'));
    }
    
    // Update cart item quantity
    public function update(Request $request, $id)
    {
        $request->validate([
            'quantity' => 'required|integer|min:1'
        ]);
        
        if (Auth::check()) {
            // Update in database - $id is the cart item ID
            $cartItem = Cart::find($id);
            
            // Check if cart item exists
            if (!$cartItem) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cart item not found.'
                ], 404);
            }
            
            // Check if cart item belongs to current user
            if ($cartItem->user_id != Auth::id()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized action.'
                ], 403);
            }
            
            $product = $cartItem->product;
            
            if (!$product) {
                return response()->json([
                    'success' => false,
                    'message' => 'Product not found.'
                ], 404);
            }
            
            // Check stock
            if ($product->stock < $request->quantity) {
                return response()->json([
                    'success' => false,
                    'message' => 'Only ' . $product->stock . ' items available.'
                ], 400);
            }
            
            $cartItem->quantity = $request->quantity;
            $cartItem->save();
            
        } else {
            // For guests, $id is the cart_key (productId_dealId)
            $cart = session()->get('cart', []);
            
            if (!isset($cart[$id])) {
                // Try to find by product ID (for backward compatibility)
                $foundKey = null;
                foreach ($cart as $key => $item) {
                    if (str_starts_with($key, $id . '_') || $item['product_id'] == $id) {
                        $foundKey = $key;
                        break;
                    }
                }
                
                if (!$foundKey) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Item not found in cart.'
                    ], 404);
                }
                
                $id = $foundKey;
            }
            
            $product = Product::find($cart[$id]['product_id']);
            
            if (!$product) {
                return response()->json([
                    'success' => false,
                    'message' => 'Product not found.'
                ], 404);
            }
            
            // Check stock
            if ($product->stock < $request->quantity) {
                return response()->json([
                    'success' => false,
                    'message' => 'Only ' . $product->stock . ' items available.'
                ], 400);
            }
            
            $cart[$id]['quantity'] = $request->quantity;
            session()->put('cart', $cart);
        }
        
        return response()->json([
            'success' => true,
            'message' => 'Cart updated successfully.'
        ]);
    }
    
    // Remove item from cart
    public function remove($id)
    {
        if (Auth::check()) {
            // Remove from database - $id is the cart item ID
            $cartItem = Cart::find($id);
            
            if ($cartItem && $cartItem->user_id == Auth::id()) {
                $cartItem->delete();
            }
            
        } else {
            // Remove from session - $id is the cart_key
            $cart = session()->get('cart', []);
            
            if (isset($cart[$id])) {
                unset($cart[$id]);
                session()->put('cart', $cart);
            } else {
                // Try to find by product ID (for backward compatibility)
                foreach ($cart as $key => $item) {
                    if (str_starts_with($key, $id . '_') || $item['product_id'] == $id) {
                        unset($cart[$key]);
                        session()->put('cart', $cart);
                        break;
                    }
                }
            }
        }
        
        return response()->json([
            'success' => true,
            'message' => 'Item removed from cart.'
        ]);
    }
    
    // Clear entire cart
    public function clear()
    {
        if (Auth::check()) {
            // Clear from database
            Cart::where('user_id', Auth::id())->delete();
        } else {
            // Clear from session
            session()->forget('cart');
        }
        
        return response()->json([
            'success' => true,
            'message' => 'Cart cleared successfully.'
        ]);
    }
    
    // Merge guest cart with user cart after login
    public function mergeGuestCart()
    {
        if (Auth::check() && session()->has('cart')) {
            $guestCart = session()->get('cart', []);
            
            foreach ($guestCart as $cartKey => $item) {
                // Check if this product already exists in user's cart with same deal
                $cartItem = Cart::where('user_id', Auth::id())
                    ->where('product_id', $item['product_id'])
                    ->where('deal_id', $item['deal_id'] ?? null)
                    ->first();
                
                if ($cartItem) {
                    // Update existing item
                    $cartItem->quantity += $item['quantity'];
                    $cartItem->save();
                } else {
                    // Create new item with deal info
                    Cart::create([
                        'user_id' => Auth::id(),
                        'product_id' => $item['product_id'],
                        'quantity' => $item['quantity'],
                        'original_price' => $item['original_price'] ?? Product::find($item['product_id'])->price,
                        'deal_id' => $item['deal_id'] ?? null,
                        'deal_type' => $item['deal_type'] ?? null,
                        'deal_discount_value' => $item['deal_discount_value'] ?? null,
                    ]);
                }
            }
            
            // Clear guest cart session
            session()->forget('cart');
        }
        
        return response()->json([
            'success' => true,
            'message' => 'Cart merged successfully.'
        ]);
    }
    
    // NEW: Check if a product has an active deal (for AJAX calls)
    public function checkDeal(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
        ]);
        
        $deal = $this->getActiveDealForProduct($request->product_id);
        
        if ($deal) {
            $product = Product::find($request->product_id);
            $priceInfo = $this->calculateDealPrice($product, $deal);
            
            return response()->json([
                'success' => true,
                'has_deal' => true,
                'deal' => [
                    'id' => $deal->id,
                    'title' => $deal->title,
                    'type' => $deal->type,
                    'discount_value' => $deal->discount_value,
                ],
                'prices' => $priceInfo,
            ]);
        }
        
        return response()->json([
            'success' => true,
            'has_deal' => false,
        ]);
    }
}