<?php
require_once 'session_helper.php';
require_once 'db_config.php';

function initializeCart() {
    safe_session_start();
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
    }
    
    if (isset($_SESSION['user_id']) && !isset($_SESSION['cart_loaded'])) {
        loadCartFromDatabase();
        $_SESSION['cart_loaded'] = true;
    }
}

function loadCartFromDatabase() {
    if (!isset($_SESSION['user_id'])) return;
    
    try {
        $db = getDBConnection();
        $stmt = $db->prepare("SELECT service_id, quantity, selected_option FROM Cart WHERE user_id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $cart = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $session = $_SESSION['cart'] ?? [];
        $merged = [];
        
        foreach ($cart as $item) {
            $options = null;
            if ($item['selected_option']) {
                $ids = explode(',', $item['selected_option']);
                $placeholders = implode(',', array_fill(0, count($ids), '?'));
                $stmt2 = $db->prepare("SELECT id, option_type, option_name, price_modifier FROM service_options WHERE id IN ($placeholders)");
                $stmt2->execute($ids);
                $opts = $stmt2->fetchAll(PDO::FETCH_ASSOC);
                $options = [];
                foreach ($opts as $o) {
                    $options[$o['option_type']] = ['id' => $o['id'], 'name' => $o['option_name'], 'price_modifier' => $o['price_modifier']];
                }
            }
            $merged[] = ['service_id' => $item['service_id'], 'quantity' => $item['quantity'], 'selected_options' => $options];
        }
        
        foreach ($session as $s) {
            $found = 0;
            for ($i = 0; $i < count($merged); $i++) {
                if ($merged[$i]['service_id'] == $s['service_id']) {
                    $merged[$i]['quantity'] += $s['quantity'];
                    $found = 1;
                    break;
                }
            }
            if (!$found) $merged[] = $s;
        }
        
        $_SESSION['cart'] = $merged;
        saveCartToDatabase();
    } catch (Exception $e) {
        error_log("cart load error");
    }
}

function saveCartToDatabase() {
    if (!$_SESSION['user_id'] || !$_SESSION['cart']) return;
    try {
        $db = getDBConnection();
        $db->prepare("DELETE FROM Cart WHERE user_id = ?")->execute([$_SESSION['user_id']]);
        $stmt = $db->prepare("INSERT INTO Cart (user_id, service_id, quantity, selected_option, pickup_option, pickup_address) VALUES (?, ?, ?, ?, ?, ?)");
        
        foreach ($_SESSION['cart'] as $item) {
            $opts = '';
            if (isset($item['selected_options']) && $item['selected_options']) {
                $ids = [];
                foreach ($item['selected_options'] as $key => $opt) {
                    if ($key === 'addons' && is_array($opt)) {
                        foreach ($opt as $addon) {
                            if (isset($addon['id'])) {
                                $ids[] = $addon['id'];
                            }
                        }
                    } elseif (is_array($opt) && isset($opt['id'])) {
                        $ids[] = $opt['id'];
                    }
                }
                $opts = join(',', $ids);
            }

            $pickup_option = $item['pickup_option'] ?? null;
            $pickup_address = $item['pickup_address'] ?? null;

            $stmt->execute([$_SESSION['user_id'], $item['service_id'], $item['quantity'], $opts, $pickup_option, $pickup_address]);
        }
    } catch (Exception $e) {
        error_log("saveCartToDatabase error: " . $e->getMessage());
    }
}


function addToCart($sid, $q = 1, $o = null, $special_instructions = null, $pickup_option = null, $pickup_address = null) {
    safe_session_start();
    initializeCart();
    $found = 0;

    for ($i = 0; $i < count($_SESSION['cart']); $i++) {
        if ($_SESSION['cart'][$i]['service_id'] == $sid) {
            $_SESSION['cart'][$i]['quantity'] += $q;
            if ($o) $_SESSION['cart'][$i]['selected_options'] = $o;
            if ($special_instructions) $_SESSION['cart'][$i]['special_instructions'] = $special_instructions;
            if ($pickup_option) $_SESSION['cart'][$i]['pickup_option'] = $pickup_option;
            if ($pickup_address) $_SESSION['cart'][$i]['pickup_address'] = $pickup_address;
            $found = 1;
            break;
        }
    }

    if (!$found) {
        $item = [
            'service_id' => $sid,
            'quantity' => $q,
            'selected_options' => $o,
            'pickup_address' => $pickup_address
        ];
        if ($special_instructions) $item['special_instructions'] = $special_instructions;
        if ($pickup_option) $item['pickup_option'] = $pickup_option;
        if ($pickup_address) $item['pickup_address'] = $pickup_address;

        $_SESSION['cart'][] = $item;
    }

    if (isset($_SESSION['user_id'])) saveCartToDatabase();
    return count($_SESSION['cart']);
}


function removeFromCart($sid) {
    safe_session_start();
    initializeCart();
    for ($i = 0; $i < count($_SESSION['cart']); $i++) {
        if ($_SESSION['cart'][$i]['service_id'] == $sid) {
            unset($_SESSION['cart'][$i]);
            $_SESSION['cart'] = array_values($_SESSION['cart']);
            break;
        }
    }
    if ($_SESSION['user_id']) saveCartToDatabase();
}

function updateCartItemQuantity($sid, $q) {
    safe_session_start();
    initializeCart();
    for ($i = 0; $i < count($_SESSION['cart']); $i++) {
        if ($_SESSION['cart'][$i]['service_id'] == $sid) {
            if ($q <= 0) {
                removeFromCart($sid);
                return;
            }
            $_SESSION['cart'][$i]['quantity'] = $q;
            break;
        }
    }
    if ($_SESSION['user_id']) saveCartToDatabase();
}

function getCartItems() {
    safe_session_start();
    initializeCart();
    return $_SESSION['cart'];
}

function getCartCount() {
    safe_session_start();
    initializeCart();
    return $_SESSION['cart'] ? count($_SESSION['cart']) : 0;
}

function clearCart() {
    safe_session_start();
    $_SESSION['cart'] = [];
    if ($_SESSION['user_id']) {
        $db = getDBConnection();
        $db->prepare("DELETE FROM Cart WHERE user_id = ?")->execute([$_SESSION['user_id']]);
    }
}

function onUserLogin($uid) {
    $_SESSION['user_id'] = $uid;
    unset($_SESSION['cart_loaded']);
    loadCartFromDatabase();
    $_SESSION['cart_loaded'] = 1;
}

function onUserLogout() {
    if ($_SESSION['user_id']) saveCartToDatabase();
    unset($_SESSION['user_id']);
    unset($_SESSION['cart_loaded']);
}
?>