<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

function addToCart(int $user_id, int $product_id, ?int $variation_id, string $quantity): bool {
    try {
        $product = getProduct($product_id);
        if (!$product) {
            throw new Exception("Product not found.");
        }

        $stock_to_check = null;
        $identifier_column = 'product_id';
        $identifier_value = $product_id;

        if ($variation_id !== null) {
            $variation = getVariationById($variation_id);
            if (!$variation || $variation['product_id'] != $product_id) {
                throw new Exception("Variation not found or does not belong to product.");
            }
            $stock_to_check = $variation['stock'];
            $identifier_column = 'variation_id';
            $identifier_value = $variation_id;
        } else {
            if ($product['type'] === 'variable') {
                throw new Exception("Cannot add variable product to cart without selecting a variation.");
            }
            $stock_to_check = $product['stock'];
        }

        $stmt = pdo()->prepare("SELECT id, quantity FROM carts WHERE user_id = ? AND product_id = ? AND variation_id " . ($variation_id ? "= ?" : "IS NULL"));
        $params = $variation_id ? [$user_id, $product_id, $variation_id] : [$user_id, $product_id];
        $stmt->execute($params);
        $existing_item = $stmt->fetch();

        if ($existing_item) {
            $new_quantity = bcadd((string)$existing_item['quantity'], $quantity, 1);
            if ($stock_to_check !== null && bccomp((string)$stock_to_check, $new_quantity, 1) < 0) {
                throw new Exception("Stock limit reached while updating cart quantity.");
            }
            $update_stmt = pdo()->prepare("UPDATE carts SET quantity = ? WHERE id = ?");
            return $update_stmt->execute([$new_quantity, $existing_item['id']]);
        } else {
            if ($stock_to_check !== null && bccomp((string)$stock_to_check, $quantity, 1) < 0) {
                throw new Exception("Stock limit reached while adding to cart.");
            }
            $insert_stmt = pdo()->prepare("INSERT INTO carts (user_id, product_id, variation_id, quantity) VALUES (?, ?, ?, ?)");
            return $insert_stmt->execute([$user_id, $product_id, $variation_id, $quantity]);
        }
    } catch (Exception $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB/Logic Error adding/updating cart (User: {$user_id}, Prod: {$product_id}, Var: {$variation_id}): " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

function getCartContents(int $user_id): array {
    try {
        $user = getUserById($user_id);
        $partner_user_id = $user['referred_by_user_id'] ?? null;
        $pdo = pdo();

        $sql = "
            SELECT 
                c.id AS cart_item_id, 
                c.quantity, 
                p.id AS product_id, 
                p.name AS product_name, 
                p.unit,
                p.weight AS product_weight,
                p.weight_unit AS product_weight_unit,
                p.type AS product_type,
                p.discount_price AS product_discount_price,
                p.discount_type AS product_discount_type,
                p.discount_start_date AS product_discount_start_date,
                p.discount_end_date AS product_discount_end_date,
                COALESCE(pv.id, 0) AS variation_id,
                COALESCE(pv.price, p.price) AS base_price,
                COALESCE(pv.stock, p.stock) AS stock,
                COALESCE(pv.image_path, p.image_path) AS image_path_relative,
                pv.weight AS variation_weight,
                pv.weight_unit AS variation_weight_unit
            FROM carts c
            JOIN products p ON c.product_id = p.id
            LEFT JOIN product_variations pv ON c.variation_id = pv.id
            WHERE c.user_id = :user_id AND p.is_active = TRUE
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':user_id' => $user_id]);
        $items = $stmt->fetchAll();

        if (empty($items)) {
            return [];
        }

        $variation_ids = array_filter(array_column($items, 'variation_id'));
        $variation_options = [];
        if (!empty($variation_ids)) {
            $placeholders = implode(',', array_fill(0, count($variation_ids), '?'));
            $sql_opts = "SELECT vo.variation_id, av.value 
                         FROM variation_options vo
                         JOIN attribute_values av ON vo.attribute_value_id = av.id
                         WHERE vo.variation_id IN ({$placeholders})
                         ORDER BY av.attribute_id";
            $stmt_opts = $pdo->prepare($sql_opts);
            $stmt_opts->execute($variation_ids);
            while ($opt = $stmt_opts->fetch()) {
                $variation_options[$opt['variation_id']][] = $opt['value'];
            }
        }

        $partner_profits = [];
        if ($partner_user_id !== null) {
            if (!empty($variation_ids)) {
                $sql_p_var = "SELECT variation_id, extra_price, is_active FROM partner_variation_profits WHERE partner_user_id = ? AND variation_id IN (" . implode(',', array_fill(0, count($variation_ids), '?')) . ")";
                $stmt_p_var = $pdo->prepare($sql_p_var);
                $stmt_p_var->execute(array_merge([$partner_user_id], $variation_ids));
                while ($p_var = $stmt_p_var->fetch()) {
                    $partner_profits[$p_var['variation_id']] = $p_var;
                }
            }
            
            $product_ids = array_column($items, 'product_id');
            $placeholders_prod = implode(',', array_fill(0, count($product_ids), '?'));
            $sql_p_prod = "SELECT product_id, extra_price, is_active FROM partner_products WHERE partner_user_id = ? AND product_id IN ({$placeholders_prod})";
            $stmt_p_prod = $pdo->prepare($sql_p_prod);
            $stmt_p_prod->execute(array_merge([$partner_user_id], $product_ids));
            while ($p_prod = $stmt_p_prod->fetch()) {
                if (!isset($partner_profits['p_' . $p_prod['product_id']])) {
                    $partner_profits['p_' . $p_prod['product_id']] = $p_prod;
                }
            }
        }

        $final_items = [];
        foreach ($items as &$item) {
            $item['name'] = $item['product_name'];
            if ($item['variation_id'] > 0 && isset($variation_options[$item['variation_id']])) {
                $item['name'] .= ' (' . implode(' - ', $variation_options[$item['variation_id']]) . ')';
            }

            $item['platform_photo_id'] = $item['image_path_relative'] 
                ? (rtrim(PRODUCT_IMAGE_PUBLIC_URL_BASE, '/') . '/' . ltrim($item['image_path_relative'], '/')) 
                : null;

            $item['weight'] = $item['variation_id'] > 0 ? $item['variation_weight'] : $item['product_weight'];
            $item['weight_unit'] = $item['variation_id'] > 0 ? $item['variation_weight_unit'] : $item['product_weight_unit'];

            $product_level_pricing_data = [
                'price' => $item['base_price'],
                'discount_price' => $item['product_discount_price'],
                'discount_type' => $item['product_discount_type'],
                'discount_start_date' => $item['product_discount_start_date'],
                'discount_end_date' => $item['product_discount_end_date']
            ];
            
            $item['pricing'] = calculateCurrentPrice($product_level_pricing_data);
            
            $partner_profit = '0.00';
            $partner_is_active = false;
            
            if ($partner_user_id !== null) {
                $profit_setting = null;
                if ($item['variation_id'] > 0) {
                    $profit_setting = $partner_profits[$item['variation_id']] ?? null;
                } else {
                    $profit_setting = $partner_profits['p_' . $item['product_id']] ?? null;
                }
                
                if ($profit_setting && $profit_setting['is_active']) {
                    $partner_profit = $profit_setting['extra_price'];
                    $partner_is_active = true;
                } else {
                    continue;
                }
            }
            
            $final_price = bcadd($item['pricing']['price'], $partner_profit, BC_SCALE);
            
            $item['pricing']['final_price'] = $final_price;
            $item['pricing']['partner_profit'] = $partner_profit;
            $item['pricing']['price'] = $final_price; 
            
            $final_items[] = $item;
        }
        unset($item);

        return $final_items;
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting cart contents for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

function updateCartItemQuantity(int $cart_item_id, string $new_quantity): bool {
    try {
        if (bccomp($new_quantity, '0', 1) > 0) {
            $stmt = pdo()->prepare("UPDATE carts SET quantity = ? WHERE id = ?");
            return $stmt->execute([$new_quantity, $cart_item_id]);
        } else {
            return deleteCartItem($cart_item_id);
        }
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error updating cart quantity for item {$cart_item_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

function deleteCartItem(int $cart_item_id): bool {
    try {
        $stmt = pdo()->prepare("DELETE FROM carts WHERE id = ?");
        return $stmt->execute([$cart_item_id]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error deleting cart item {$cart_item_id}: " . "\n", FILE_APPEND);
        return false;
    }
}

function clearCart(int $user_id): bool {
    try {
       $stmt = pdo()->prepare("DELETE FROM carts WHERE user_id = ?");
        return $stmt->execute([$user_id]);
    } catch (PDOException $e) {
         file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error clearing cart for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

?>