<?php
require_once 'db.php';
session_start();

if (!isset($_SESSION['logged_in_user'])) {
    header("Location: user-login.php");
    exit;
}

$loggedInUser = $_SESSION['logged_in_user'];
$share_code = $_POST['share_code'] ?? null;

if (!$share_code) {
    die("Error: No share code entered.");
}

// ✅ Fetch the correct user ID
$userQuery = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$userQuery->execute([$loggedInUser]);
$userData = $userQuery->fetch(PDO::FETCH_ASSOC);

if (!$userData) {
    die("Error: User not found.");
}

$user_id = $userData['id'];

// ✅ Find the lead capture page by Share Code
$stmt = $pdo->prepare("SELECT * FROM lead_capture_pages WHERE share_code = ?");
$stmt->execute([$share_code]);
$page = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$page) {
    die("Error: Invalid Share Code.");
}

// ✅ Generate a NEW unique Share Code for the cloned page
$new_share_code = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 6);

// ✅ Clone the Lead Capture Page for the New User
$cloneStmt = $pdo->prepare("
    INSERT INTO lead_capture_pages (
        user_id, layout, background, mockup_filename, color_theme,
        headline, subheadline, footer_text, form_name_field, thumbnail,
        font_headline, font_subheading, share_code,
        cta_text, exit_popup_enabled, exit_popup_lead_magnet_id,
        default_capture, created_at
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NOW()
    )
");

$cloneStmt->execute([
    $user_id,
    $page['layout'],
    $page['background'],
    $page['mockup_filename'] ?? null,
    $page['color_theme'],
    $page['headline'],
    $page['subheadline'],
    $page['footer_text'] ?? '',
    $page['form_name_field'] ?? '',
    $page['thumbnail'],
    $page['font_headline'] ?? '',
    $page['font_subheading'] ?? '',
    $new_share_code,
    $page['cta_text'] ?? '',
    $page['exit_popup_enabled'] ?? 0,
    $page['exit_popup_lead_magnet_id'] ?? null
]);

header("Location: lead-capture.php?cloned=1");
exit;
?>
