<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/auth.php';

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

$action = $_POST['action'] ?? '';
$response = ['success' => false];

$userId = isset($_SESSION['user']['id']) ? (int)$_SESSION['user']['id'] : null;
$sessionId = session_id();

function getCartItems($db, $userId, $sessionId) {
    if ($userId) {
        $stmt = $db->prepare("SELECT c.*, p.name, p.price, p.main_image as image, p.vendor_id FROM cart_items c JOIN products p ON c.product_id = p.id WHERE c.user_id = ?");
        $stmt->execute([$userId]);
    } else {
        $stmt = $db->prepare("SELECT c.*, p.name, p.price, p.main_image as image, p.vendor_id FROM cart_items c JOIN products p ON c.product_id = p.id WHERE c.session_id = ? AND c.user_id IS NULL");
        $stmt->execute([$sessionId]);
    }
    return $stmt->fetchAll();
}

function getCartTotals($items) {
    $totalAmount = 0;
    $totalItems = 0;
    foreach ($items as $item) {
        $totalAmount += $item['price'] * $item['quantity'];
        $totalItems += $item['quantity'];
    }
    return ['amount' => $totalAmount, 'items' => $totalItems];
}

try {
    if ($action === 'add') {
        $productId = (int)($_POST['product_id'] ?? 0);
        $size = sanitize($_POST['size'] ?? 'M');
        $color = sanitize($_POST['color'] ?? 'Default');

        if ($productId > 0) {
            $db = getDBConnection();
            $stmt = $db->prepare("SELECT id FROM products WHERE id = ? AND status = 'active'");
            $stmt->execute([$productId]);
            
            if ($stmt->fetch()) {
                if ($userId) {
                    $checkStmt = $db->prepare("SELECT id, quantity FROM cart_items WHERE user_id = ? AND product_id = ? AND size = ? AND color = ?");
                    $checkStmt->execute([$userId, $productId, $size, $color]);
                } else {
                    $checkStmt = $db->prepare("SELECT id, quantity FROM cart_items WHERE session_id = ? AND user_id IS NULL AND product_id = ? AND size = ? AND color = ?");
                    $checkStmt->execute([$sessionId, $productId, $size, $color]);
                }
                
                $existing = $checkStmt->fetch();
                
                if ($existing) {
                    $updateStmt = $db->prepare("UPDATE cart_items SET quantity = quantity + 1 WHERE id = ?");
                    $updateStmt->execute([$existing['id']]);
                } else {
                    $insertStmt = $db->prepare("INSERT INTO cart_items (user_id, session_id, product_id, size, color, quantity) VALUES (?, ?, ?, ?, ?, 1)");
                    // MySQL UNIQUE constraints treat NULL as distinct. 
                    // However, our logic ensures we either have user_id OR session_id.
                    if ($userId) {
                        $insertStmt->execute([$userId, null, $productId, $size, $color]);
                    } else {
                        $insertStmt->execute([null, $sessionId, $productId, $size, $color]);
                    }
                }
                
                $items = getCartItems($db, $userId, $sessionId);
                $totals = getCartTotals($items);
                
                $response = [
                    'success' => true,
                    'total_items' => $totals['items']
                ];
            } else {
                $response['message'] = 'ไม่พบสินค้านี้ในระบบ';
            }
        }
    } elseif ($action === 'update') {
        $id = (int)($_POST['key'] ?? 0); // In DB context, key is the cart_items.id
        $qty = (int)($_POST['quantity'] ?? 1);

        if ($id > 0) {
            $db = getDBConnection();
            
            // Verify ownership
            if ($userId) {
                $checkStmt = $db->prepare("SELECT id FROM cart_items WHERE id = ? AND user_id = ?");
                $checkStmt->execute([$id, $userId]);
            } else {
                $checkStmt = $db->prepare("SELECT id FROM cart_items WHERE id = ? AND session_id = ? AND user_id IS NULL");
                $checkStmt->execute([$id, $sessionId]);
            }
            
            if ($checkStmt->fetch()) {
                if ($qty <= 0) {
                    $delStmt = $db->prepare("DELETE FROM cart_items WHERE id = ?");
                    $delStmt->execute([$id]);
                } else {
                    $updStmt = $db->prepare("UPDATE cart_items SET quantity = ? WHERE id = ?");
                    $updStmt->execute([$qty, $id]);
                }
                
                $items = getCartItems($db, $userId, $sessionId);
                $totals = getCartTotals($items);
                
                // Reformat for frontend
                $cartFormatted = array_map(function($i) {
                    return [
                        'key' => $i['id'], // use id as key for UI
                        'product_id' => $i['product_id'],
                        'vendor_id' => $i['vendor_id'],
                        'name' => $i['name'],
                        'price' => $i['price'],
                        'image' => $i['image'],
                        'size' => $i['size'],
                        'color' => $i['color'],
                        'quantity' => $i['quantity']
                    ];
                }, $items);

                $response = [
                    'success' => true,
                    'cart' => $cartFormatted,
                    'total_amount' => $totals['amount'],
                    'total_items' => $totals['items']
                ];
            }
        }
    } elseif ($action === 'remove') {
        $id = (int)($_POST['key'] ?? 0);

        if ($id > 0) {
            $db = getDBConnection();
            // Verify ownership
            if ($userId) {
                $checkStmt = $db->prepare("SELECT id FROM cart_items WHERE id = ? AND user_id = ?");
                $checkStmt->execute([$id, $userId]);
            } else {
                $checkStmt = $db->prepare("SELECT id FROM cart_items WHERE id = ? AND session_id = ? AND user_id IS NULL");
                $checkStmt->execute([$id, $sessionId]);
            }
            
            if ($checkStmt->fetch()) {
                $delStmt = $db->prepare("DELETE FROM cart_items WHERE id = ?");
                $delStmt->execute([$id]);
                
                $items = getCartItems($db, $userId, $sessionId);
                $totals = getCartTotals($items);
                
                // Reformat for frontend
                $cartFormatted = array_map(function($i) {
                    return [
                        'key' => $i['id'],
                        'product_id' => $i['product_id'],
                        'vendor_id' => $i['vendor_id'],
                        'name' => $i['name'],
                        'price' => $i['price'],
                        'image' => $i['image'],
                        'size' => $i['size'],
                        'color' => $i['color'],
                        'quantity' => $i['quantity']
                    ];
                }, $items);

                $response = [
                    'success' => true,
                    'cart' => $cartFormatted,
                    'total_amount' => $totals['amount'],
                    'total_items' => $totals['items']
                ];
            }
        }
    }
} catch (PDOException $e) {
    $response = [
        'success' => false,
        'message' => 'Database Error: ' . $e->getMessage()
    ];
} catch (Exception $e) {
    $response = [
        'success' => false,
        'message' => $e->getMessage()
    ];
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($response);
exit;
