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

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

$loggedInUser = $_SESSION['logged_in_user'];
$original_id = $_GET['id'] ?? null;

if (!$original_id) {
    die("Error: No lead capture page ID provided.");
}

// ✅ Fetch numeric 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'];

// ✅ Get the original page (only if it belongs to the user)
$stmt = $pdo->prepare("SELECT * FROM lead_capture_pages WHERE id = ? AND user_id = ?");
$stmt->execute([$original_id, $user_id]);
$page = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$page) {
    die("Error: Lead capture page not found or access denied.");
}

// ✅ Generate new unique share code
$new_share_code = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 6);

// ✅ Insert cloned record with all relevant fields
$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?success=cloned");
exit;
?>
