<?php

function get_abandoned_cart_session_id()
{
    if (empty($_SESSION['abandoned_cart_session_id'])) {
        $_SESSION['abandoned_cart_session_id'] = session_id() ?: bin2hex(random_bytes(16));
    }

    return $_SESSION['abandoned_cart_session_id'];
}

function create_recovery_token()
{
    return bin2hex(random_bytes(32));
}

function upsert_abandoned_cart($customerId, $email, $cartTotal, $cartItems)
{
    global $pdo;

    if (!$cartItems || $cartTotal <= 0) {
        return false;
    }

    $sessionId = get_abandoned_cart_session_id();

    $stmt = $pdo->prepare("
        SELECT *
        FROM abandoned_carts
        WHERE session_id = ?
          AND status = 'pending'
        LIMIT 1
    ");
    $stmt->execute([$sessionId]);
    $existingCart = $stmt->fetch();

    if ($existingCart) {
        $abandonedCartId = (int) $existingCart['id'];

        $stmt = $pdo->prepare("
            UPDATE abandoned_carts
            SET customer_id = ?,
                email = ?,
                cart_total = ?
            WHERE id = ?
        ");
        $stmt->execute([
            $customerId ?: null,
            $email !== '' ? $email : null,
            $cartTotal,
            $abandonedCartId
        ]);

        $stmt = $pdo->prepare("DELETE FROM abandoned_cart_items WHERE abandoned_cart_id = ?");
        $stmt->execute([$abandonedCartId]);
    } else {
        $recoveryToken = create_recovery_token();

        $stmt = $pdo->prepare("
            INSERT INTO abandoned_carts (
                customer_id,
                session_id,
                email,
                cart_total,
                recovery_token,
                status
            ) VALUES (?, ?, ?, ?, ?, 'pending')
        ");
        $stmt->execute([
            $customerId ?: null,
            $sessionId,
            $email !== '' ? $email : null,
            $cartTotal,
            $recoveryToken
        ]);

        $abandonedCartId = (int) $pdo->lastInsertId();
    }

    $stmtItem = $pdo->prepare("
        INSERT INTO abandoned_cart_items (
    abandoned_cart_id,
    product_id,
    variation_id,
    product_name,
    variation_name,
    quantity,
    unit_price
) VALUES (?, ?, ?, ?, ?, ?, ?)
    ");

    foreach ($cartItems as $item) {
        $stmtItem->execute([
    $abandonedCartId,
    $item['product_id'] ?? null,
    $item['variation_id'] ?? null,
    $item['product_name'] ?? 'Product',
    $item['variation_name'] ?? null,
    max(1, (int) ($item['quantity'] ?? 1)),
    (float) ($item['unit_price'] ?? 0)
]);
    }

    return $abandonedCartId;
}

function mark_abandoned_cart_recovered($sessionId = null, $email = null)
{
    global $pdo;

    $sessionId = $sessionId ?: get_abandoned_cart_session_id();

    if ($email) {
        $stmt = $pdo->prepare("
            UPDATE abandoned_carts
            SET status = 'recovered'
            WHERE status = 'pending'
              AND (session_id = ? OR email = ?)
        ");
        $stmt->execute([$sessionId, $email]);
    } else {
        $stmt = $pdo->prepare("
            UPDATE abandoned_carts
            SET status = 'recovered'
            WHERE status = 'pending'
              AND session_id = ?
        ");
        $stmt->execute([$sessionId]);
    }
}
