<?php
/**
 * Cart API Endpoint
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/Cart.php';

header('Content-Type: application/json');

$auth = new Auth();
$cart = new Cart();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

$userId = $auth->getUserId();
$sessionId = $auth->getSessionId();

// Ensure session ID is always set
if (empty($sessionId)) {
    $sessionId = session_id();
    if (empty($sessionId)) {
        // Generate a new session ID if none exists
        $sessionId = bin2hex(random_bytes(16));
        if (session_status() === PHP_SESSION_ACTIVE) {
            $_SESSION['session_id'] = $sessionId;
        }
    }
}

try {
    switch ($method) {
        case 'GET':
            // Check if we need full calculations
            $action = $_GET['action'] ?? '';
            
            // Get cart
            $cartData = $cart->getOrCreateCart($userId, $sessionId);
            $items = $cart->getCartItems($cartData['id']);
            $total = $cart->getCartTotal($cartData['id'], $userId);
            $count = $cart->getCartCount($cartData['id']);
            
            $response = [
                'success' => true,
                'cart' => [
                    'id' => $cartData['id'],
                    'items' => $items,
                    'total' => $total,
                    'count' => $count
                ]
            ];
            
            // If get_full action, include detailed calculations
            if ($action === 'get_full') {
                require_once __DIR__ . '/../includes/Product.php';
                require_once __DIR__ . '/../includes/User.php';
                require_once __DIR__ . '/../includes/B2B.php';
                
                $product = new Product();
                $user = new User();
                $b2b = new B2B();
                
                $b2bGroup = $userId ? $user->getB2BGroup($userId) : null;
                
                $subtotal = 0;
                $savings = 0;
                $itemCount = 0;
                
                // Enrich items with full product data and pricing
                foreach ($items as &$item) {
                    $productData = $product->getProductById($item['product_id']);
                    if ($productData) {
                        $currentPrice = $product->getProductPrice($productData, $b2bGroup, $userId);
                        $originalPrice = $productData['sale_price'] ?? $productData['price'];
                        
                        if ($originalPrice > $currentPrice) {
                            $savings += ($originalPrice - $currentPrice) * $item['quantity'];
                        }
                        
                        $item['current_price'] = $currentPrice;
                        $item['original_price'] = $originalPrice;
                        $item['item_total'] = $currentPrice * $item['quantity'];
                        $item['sku'] = $productData['sku'] ?? '';
                        
                        // Normalize image path
                        $itemImage = $productData['image'] ?? '01.png';
                        if (strpos($itemImage, 'http') !== 0 && strpos($itemImage, '/') !== 0) {
                            if (strpos($itemImage, 'assets/') !== 0) {
                                $itemImage = '/assets/img/shop/electronics/thumbs/' . $itemImage;
                            } else {
                                $itemImage = '/' . $itemImage;
                            }
                        }
                        $item['image'] = $itemImage;
                        
                        $subtotal += $item['item_total'];
                        $itemCount += $item['quantity'];
                    }
                }
                unset($item);
                
                $tax = $subtotal * 0.19;
                $estimatedTotal = $subtotal + $tax;
                
                $response['cart']['items'] = $items;
                $response['calculations'] = [
                    'subtotal' => $subtotal,
                    'savings' => $savings,
                    'itemCount' => $itemCount,
                    'tax' => $tax,
                    'estimatedTotal' => $estimatedTotal
                ];
            }

            echo json_encode($response);
            break;

        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            
            // Allow empty data for certain actions like 'clear'
            if (!$data && $action !== 'clear') {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Date invalide']);
                exit;
            }
            
            if ($action === 'add') {
                $productId = intval($data['product_id'] ?? 0);
                $quantity = intval($data['quantity'] ?? 1);
                
                if ($productId <= 0) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'ID produs invalid']);
                    exit;
                }
                
                if ($quantity <= 0) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Cantitate invalidă']);
                    exit;
                }
                
                try {
                    $result = $cart->addToCart($productId, $quantity, $userId, $sessionId);
                    echo json_encode($result);
                } catch (Exception $e) {
                    error_log("Add to cart error: " . $e->getMessage());
                    http_response_code(500);
                    echo json_encode(['success' => false, 'message' => 'Eroare la adăugarea produsului: ' . $e->getMessage()]);
                }
            } elseif ($action === 'update') {
                // Accept both 'item_id' and 'cart_item_id' for compatibility
                $itemId = intval($data['item_id'] ?? $data['cart_item_id'] ?? 0);
                $quantity = intval($data['quantity'] ?? 1);
                
                if ($itemId <= 0) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'ID articol invalid']);
                    exit;
                }
                
                if ($quantity <= 0) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Cantitate invalidă']);
                    exit;
                }
                
                try {
                    $result = $cart->updateCartItem($itemId, $quantity);
                    echo json_encode($result);
                } catch (Exception $e) {
                    error_log("Update cart item error: " . $e->getMessage());
                    http_response_code(500);
                    echo json_encode(['success' => false, 'message' => 'Eroare la actualizarea coșului: ' . $e->getMessage()]);
                }
            } elseif ($action === 'remove') {
                // Accept both 'item_id' and 'cart_item_id' for compatibility
                $itemId = intval($data['item_id'] ?? $data['cart_item_id'] ?? 0);
                
                if ($itemId <= 0) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'ID articol invalid']);
                    exit;
                }
                
                try {
                    $result = $cart->removeCartItem($itemId);
                    echo json_encode($result);
                } catch (Exception $e) {
                    error_log("Remove cart item error: " . $e->getMessage());
                    http_response_code(500);
                    echo json_encode(['success' => false, 'message' => 'Eroare la ștergerea produsului: ' . $e->getMessage()]);
                }
            } elseif ($action === 'merge') {
                // Merge carts on login
                $sessionCartId = $data['session_cart_id'] ?? 0;
                $userCartId = $data['user_cart_id'] ?? 0;
                $mergeType = $data['merge_type'] ?? 'merge';
                
                $result = $cart->mergeCarts($sessionCartId, $userCartId, $mergeType);
                echo json_encode($result);
            } elseif ($action === 'clear') {
                // Clear cart
                $cartData = $cart->getOrCreateCart($userId, $sessionId);
                
                if (!$cartData || !isset($cartData['id'])) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Coș invalid']);
                    exit;
                }
                
                try {
                    $result = $cart->clearCart($cartData['id']);
                    echo json_encode($result);
                } catch (Exception $e) {
                    error_log("Clear cart error: " . $e->getMessage());
                    http_response_code(500);
                    echo json_encode(['success' => false, 'message' => 'Eroare la golirea coșului: ' . $e->getMessage()]);
                }
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    error_log("Cart API Error: " . $e->getMessage() . " | Trace: " . $e->getTraceAsString());
    echo json_encode([
        'success' => false, 
        'message' => 'An error occurred. Please try again.',
        'error' => $e->getMessage() // Include error for debugging
    ]);
}
?>

