<?php
/**
 * Publish storefront — backward-compatible alias for store-visibility resume.
 */
require_once __DIR__ . '/_init.php';
require_once __DIR__ . '/../store-public-access.php';
require_once dirname(__DIR__) . '/includes/store/SgStoreVisibility.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$conn = getDBConnection();
if (!$conn) {
    $_SESSION['seller_plan_notice'] = 'Could not connect. Try again in a moment.';
    header('Location: index.php');
    exit;
}

$uid = (int)$_SESSION['user_id'];
$sid = (int)$seller_id;
$wasLive = sg_store_visibility_get($conn, $sid);

$result = sg_store_visibility_set($conn, $sid, $uid, true, $seller_plan_state ?? null);
if (!empty($result['ok']) && !$wasLive) {
    $storeName = '';
    $storeSlug = '';
    $chk = $conn->prepare('SELECT store_name, slug FROM sellers WHERE id = ? AND user_id = ? LIMIT 1');
    if ($chk) {
        $chk->bind_param('ii', $sid, $uid);
        $chk->execute();
        $prev = function_exists('sg_mysqli_stmt_fetch_assoc') ? sg_mysqli_stmt_fetch_assoc($chk) : null;
        $chk->close();
        if ($prev) {
            $storeName = (string)($prev['store_name'] ?? '');
            $storeSlug = (string)($prev['slug'] ?? '');
        }
    }
    if ($storeSlug !== '') {
        require_once dirname(__DIR__) . '/includes/mail/SgEmailDispatch.php';
        sg_email_dispatch_store_published($conn, $sid, $storeName, $storeSlug);
    }
}
$conn->close();

$_SESSION['seller_plan_notice'] = (string)($result['message'] ?? 'Your store is live! Share your link to get orders.');
header('Location: index.php?' . (!empty($result['ok']) ? 'share=1' : ''));
exit;
