<?php
// store.php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

$current_host = strtolower($_SERVER['HTTP_HOST'] ?? '');
// Normalize host: strip leading www.
$norm_host = preg_replace('/^www\./i', '', $current_host);
$store_slug = $_GET['name'] ?? '';

// 1. Try hierarchical matching
$search_terms = [];
if (!empty($store_slug)) {
    $search_terms[] = $norm_host . '/' . $store_slug; // Full path: domain.com/link
}
$search_terms[] = $norm_host; // Host-only (subdomain or direct domain)

$store_owner = null;
foreach ($search_terms as $term) {
    $stmt = $pdo->prepare("SELECT u.id, u.landing_page, u.api_key, u.redirect_url, d.id as domain_id FROM user_domains d JOIN users u ON d.user_id = u.id WHERE LOWER(d.domain_name) = ? AND d.status IN ('verified', 'active')");
    $stmt->execute([$term]);
    $store_owner = $stmt->fetch();
    if ($store_owner) break;
}

if (!$store_owner && !empty($store_slug)) {
    // 2. Fallback to path-based matching on main SITE_URL (for slug only)
    $slug_stmt = $pdo->prepare("SELECT u.id, u.landing_page, u.api_key, u.redirect_url, d.id as domain_id FROM user_domains d JOIN users u ON d.user_id = u.id WHERE LOWER(d.domain_name) = ? AND d.status IN ('verified', 'active')");
    $slug_stmt->execute([strtolower($store_slug)]);
    $store_owner = $slug_stmt->fetch();
}

if ($store_owner) {
    $store_user_id = $store_owner['id'];
    $domain_id = $store_owner['domain_id'];
    $landing_template = !empty($store_owner['landing_page']) ? $store_owner['landing_page'] : 'landing1';
    
    // Store customization settings for the templates
    $store_api_key = $store_owner['api_key'] ?? '';
    $store_redirect_url = !empty($store_owner['redirect_url']) ? $store_owner['redirect_url'] : 'https://thathendwa.us/';
    
    // Track the visit
    track_visit($pdo, $domain_id, 'view');

    // Fetch user's active videos, ordered by their custom positions or latest
    $v_stmt = $pdo->prepare("SELECT * FROM videos WHERE user_id = ? AND status = 'active' ORDER BY position ASC, created_at DESC");
    $v_stmt->execute([$store_user_id]);
    $videos = $v_stmt->fetchAll();
    
    $featured = $videos[0] ?? null;
    
    // Safety check: ensure template name is fully alphanumeric to prevent paths traversal
    if (preg_match('/^[a-zA-Z0-9_-]+$/', $landing_template)) {
        $template_file = __DIR__ . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $landing_template . '.php';
        if (file_exists($template_file)) {
            // Render the storefront template and halt
            require $template_file;
            exit;
        }
    }
    die("Error: Template '" . htmlspecialchars($landing_template) . "' not found. Make sure you have chosen a valid template in Settings.");
} else {
    // If store is not found, redirect to 404
    header("Location: " . SITE_URL . "/404");
    exit;
}
?>

