<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/media.php';

function product_slugify(string $name): string
{
    $s = strtolower(trim($name));
    $s = preg_replace('/[^a-z0-9]+/', '-', $s) ?? '';
    return trim($s, '-') ?: 'product';
}

function product_unique_slug(int $tenantId, string $base, ?int $ignoreId = null): string
{
    $slug = product_slugify($base);
    $n = 0;
    while (true) {
        $try = $n === 0 ? $slug : $slug . '-' . $n;
        $sql = 'SELECT id FROM products WHERE tenant_id = ? AND slug = ?';
        $params = [$tenantId, $try];
        if ($ignoreId) {
            $sql .= ' AND id != ?';
            $params[] = $ignoreId;
        }
        $stmt = db()->prepare($sql . ' LIMIT 1');
        $stmt->execute($params);
        if (!$stmt->fetch()) {
            return $try;
        }
        $n++;
    }
}

function cart_boot(): void
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) {
        $_SESSION['cart'] = []; // product_id => qty
    }
}

function cart_items(int $tenantId): array
{
    cart_boot();
    if (!$_SESSION['cart']) {
        return [];
    }
    $ids = array_map('intval', array_keys($_SESSION['cart']));
    if (!$ids) {
        return [];
    }
    $in = implode(',', array_fill(0, count($ids), '?'));
    $params = array_merge([$tenantId], $ids);
    $stmt = db()->prepare(
        "SELECT * FROM products WHERE tenant_id = ? AND id IN ($in) AND is_active = 1"
    );
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
    $out = [];
    foreach ($rows as $p) {
        $qty = (int) ($_SESSION['cart'][(int) $p['id']] ?? 0);
        if ($qty < 1) {
            continue;
        }
        $p['qty'] = $qty;
        $p['line_total'] = round((float) $p['price'] * $qty, 2);
        $p['image_url'] = media_public_url($p['image_path'] ?? null);
        $out[] = $p;
    }
    return $out;
}

function cart_totals(array $items): array
{
    $sub = 0.0;
    $count = 0;
    foreach ($items as $i) {
        $sub += (float) $i['line_total'];
        $count += (int) $i['qty'];
    }
    return ['subtotal' => round($sub, 2), 'total' => round($sub, 2), 'count' => $count];
}

function cart_add(int $productId, int $qty = 1): void
{
    cart_boot();
    $qty = max(1, $qty);
    $_SESSION['cart'][$productId] = ($_SESSION['cart'][$productId] ?? 0) + $qty;
}

function cart_set(int $productId, int $qty): void
{
    cart_boot();
    if ($qty <= 0) {
        unset($_SESSION['cart'][$productId]);
    } else {
        $_SESSION['cart'][$productId] = $qty;
    }
}

function cart_clear(): void
{
    cart_boot();
    $_SESSION['cart'] = [];
}
