<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session (Must be before any output)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// REMOVE the JSON header because this page outputs HTML
?>


<?php

// ✅ CONNECT TO MySQL DATABASE
require_once __DIR__ . '/../db.php';


// ✅ Get existing program columns dynamically
$programColumns = [];
$columnStmt = $pdo->query("SHOW COLUMNS FROM users LIKE 'program_%'");
while ($column = $columnStmt->fetch()) {
    $programColumns[] = $column['Field'];
}

// Get step number
$step = isset($_GET['step']) ? (int) $_GET['step'] : 1;
$stmt = $pdo->query("SELECT * FROM programs ORDER BY id ASC");
$programs = $stmt->fetchAll();

// Capture the referrer from URL (if exists)
// ✅ Ensure a user ID is generated
if (!isset($_SESSION['new_user_id'])) {
    $_SESSION['new_user_id'] = "usr" . rand(10000, 99999);
}
$new_user_id = $_SESSION['new_user_id'];
$referrer_id = $_GET['ref'] ?? null;  // ✅ Make sure referrer_id is always set


// Ensure the user exists in the database
// ✅ Check if user already exists in database
$stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
$stmt->execute([$new_user_id]);
$userExists = $stmt->fetch();

// ✅ Check if user already exists before inserting
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE user_id = ?");
$stmt->execute([$new_user_id]);
$userCount = $stmt->fetchColumn();

if ($userCount == 0) { // ✅ Insert ONLY if user does not exist
    $columns = array_merge(["user_id", "referrer_id", "edit_token"], $programColumns, ["email"]);
    $placeholders = implode(", ", array_fill(0, count($columns), "?"));

    $stmt = $pdo->prepare("INSERT INTO users (" . implode(", ", $columns) . ") VALUES ($placeholders)");
    $values = array_merge([$new_user_id, $referrer_id, bin2hex(random_bytes(6))], array_fill(0, count($programColumns), ""), [""]);
    $stmt->execute($values);
}


// ✅ Capture the referrer ID (if any)
$referrer_id = $_GET['ref'] ?? null;



// ✅ Check if user already exists in database
$stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
$stmt->execute([$new_user_id]);
$user = $stmt->fetch();


if (!$user) {
    // ✅ CREATE NEW USER RECORD IN DATABASE
    $edit_token = bin2hex(random_bytes(6));
    $stmt = $pdo->prepare("INSERT INTO users (user_id, edit_token, program_1, program_2, program_3, email) VALUES (?, ?, '', '', '', '')");
    $stmt->execute([$new_user_id, $edit_token]);
    
    $user = [
        "id" => $new_user_id,
        "edit_token" => $edit_token,
        "program_1" => "",
        "program_2" => "",
        "program_3" => "",
        "email" => ""
    ];
}

// ✅ HANDLE SAVING USER INPUT (AJAX POST REQUEST)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);
    $stepIndex = $input['step'] - 1;
    $userInput = trim($input['user_id'] ?? '');

if (isset($programs[$stepIndex]) && in_array("program_" . ($stepIndex + 1), $programColumns)) {
    $programKey = "program_" . ($stepIndex + 1);

    // ✅ UPDATE USER'S REFERRAL ID IN DATABASE
    $stmt = $pdo->prepare("UPDATE users SET $programKey = ? WHERE user_id = ?");
    $stmt->execute([$userInput, $new_user_id]);

    echo json_encode(["success" => true, "message" => "User ID saved!"]);
    exit;
}
}

// **SHOW COMPLETION SCREEN IF STEPS ARE DONE**
if ($step > count($programs)) {
    // Generate referral link
    $baseURL = "https://" . $_SERVER['HTTP_HOST'] . str_replace('/scripts', '', dirname($_SERVER['PHP_SELF']));
    $fullReferralLink = $baseURL . "/index.php?ref=" . $new_user_id;

// ✅ Retrieve user password from MySQL
$stmt = $pdo->prepare("SELECT edit_token FROM users WHERE user_id = ?");
$stmt->execute([$new_user_id]);
$user = $stmt->fetch();
$userPassword = $user['edit_token'] ?? "Unknown";


    // Display final screen
    echo "<div class='container'>";
    echo "<h2>Complete Your Registration</h2>";

echo "<form id='finalSignupForm'>";

// First Name
echo "<label for='first_name'>First Name:</label>";
echo "<input type='text' id='first_name' name='first_name' required>";

// Last Name
echo "<label for='last_name'>Last Name:</label>";
echo "<input type='text' id='last_name' name='last_name' required>";

// Email
echo "<label for='email'>Email:</label>";
echo "<input type='email' id='email' name='email' required>";

echo "<button type='submit'>Finish Registration</button>";

echo "</form>";
    
echo "<p style='color: red; font-weight: bold; font-size: 18px;'>
⚠️ WARNING: Complete your registration as soon as possible to save your account!
</p>";


echo "<p>Please log in and enter your details before time runs out.</p>";
echo "<a href='user-dashboard.php' target='_blank'><button>Edit My Details</button></a>";



    echo "<p><strong>Your Referral Link:</strong></p>";
    echo "<input type='text' id='referralLink' value='" . htmlspecialchars($fullReferralLink) . "' readonly>";
    echo "<button onclick='copyReferralLink()'>Copy Referral Link</button>";
    echo '<p class="copy-success" id="copySuccess" style="display: none;">Copied to clipboard!</p>';

    echo "<hr>";

    echo "<h3>Important: Save Your Login Details</h3>";
    echo "<p><strong>User ID:</strong> " . htmlspecialchars($new_user_id) . "</p>";
    echo "<p><strong>Password:</strong> " . htmlspecialchars($userPassword) . "</p>";
    echo "<p>Use your User ID and Password to log in and edit your details later.</p>";

    echo "<a href='user-dashboard.php' target='_blank'><button>Edit My Details</button></a>";
    echo "</div>";

    echo "<script>
    function copyReferralLink() {
        var copyText = document.getElementById('referralLink').value;

        navigator.clipboard.writeText(copyText).then(() => {
            var copyMessage = document.getElementById('copySuccess');
            copyMessage.style.display = 'block';
            copyMessage.innerText = 'Copied to clipboard!';
            
            setTimeout(() => { copyMessage.style.display = 'none'; }, 2000);
        }).catch(err => {
            console.error('Failed to copy:', err);
            alert('Copy to clipboard failed. Please copy manually.');
        });
    }
    </script>";

    exit;
}

// ✅ GET PROGRAM DETAILS FOR THE CURRENT STEP
$program = $programs[$step - 1];


// ✅ Ensure step is within available programs
if (!in_array("program_" . $step, $programColumns)) {
    die(json_encode(["error" => "Step exceeds available programs."]));
}

$programKey = "program_" . $step;
$userRefID = $user[$programKey] ?? "";

// ✅ 1. Start with direct sponsor's referral ID (if they have one)
$referrer_id = $_GET['ref'] ?? null;
$referrerUsername = "";

if ($referrer_id) {
    $stmt = $pdo->prepare("SELECT user_id, referrer_id, $programKey FROM users WHERE user_id = ?");
    $stmt->execute([$referrer_id]);
    $referrerData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $referrerUsername = $referrerData[$programKey] ?? "";
}

// ✅ 2. If the direct sponsor has no referral ID, check their sponsor (multi-tier fallback)
$uplineID = $referrerData['referrer_id'] ?? null;

while (empty($referrerUsername) && !empty($uplineID)) {
    $stmt = $pdo->prepare("SELECT user_id, referrer_id, $programKey FROM users WHERE user_id = ?");
    $stmt->execute([$uplineID]);
    $uplineData = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($uplineData) {
        $referrerUsername = $uplineData[$programKey] ?? "";
        $uplineID = $uplineData['referrer_id'] ?? null; // Move up the chain
    } else {
        break; // Stop if no more uplines exist
    }
}

// ✅ 3. If still empty, use the default admin referral ID from the admin panel
if (empty($referrerUsername) && isset($program['id'])) {
    $stmt = $pdo->prepare("SELECT default_admin_referrer FROM programs WHERE id = ?");
    $stmt->execute([$program['id']]);
    $programDefault = $stmt->fetchColumn();
    
    $referrerUsername = !empty($programDefault) ? $programDefault : 'your_admin_id'; // 🔹 Final fallback
}

// **GENERATE STEP CONTENT**
?>
<h1><?php echo htmlspecialchars($program['title'] ?? ""); ?></h1>
<h3><?php echo htmlspecialchars($program['subtitle'] ?? ""); ?></h3>
<iframe width="100%" height="315" src="<?php echo htmlspecialchars($program['video_url'] ?? ""); ?>" frameborder="0" allowfullscreen></iframe>
<br>
<?php
// ✅ Apply dynamic user ID replacement
$signupUrl = $program['url_template'] ?? $program['signup_url']; // Use new template if available
$signupUrl = str_replace('{{USER_ID}}', htmlspecialchars($referrerUsername ?? ""), $signupUrl);
?>

<?php
// ✅ Use new URL template instead of hardcoded signup_url
$signupUrl = $program['url_template'] ?? $program['signup_url']; // Use the new URL template if available
$signupUrl = str_replace('{{USER_ID}}', htmlspecialchars($referrerUsername ?? ""), $signupUrl);
?>

<a href="<?php echo htmlspecialchars($signupUrl); ?>" target="_blank">
    <button><?php echo htmlspecialchars($program['cta_text'] ?? "Sign Up Now"); ?></button>
</a>

<br><br>
<input type="text" id="referral-<?php echo $step; ?>" placeholder="<?php echo htmlspecialchars($program['placeholder_text'] ?? "Enter your ID"); ?>" value="<?php echo $userRefID; ?>">
<br>
<?php if ($step > 1): ?>
    <button onclick="loadStep(<?php echo $step - 1; ?>)">Back</button>
<?php endif; ?>
<button onclick="saveUserID(<?php echo $step; ?>)">Save & Continue</button>

<script>
function saveUserID(step) {
    var userID = document.getElementById('referral-' + step).value;
    fetch("scripts/fetchPrograms.php?ref=<?php echo $_SESSION['new_user_id']; ?>", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ step: step, user_id: userID })
    }).then(response => response.json())
      .then(data => {
          console.log("User ID saved:", data);
          loadStep(step + 1);
      })
      .catch(error => console.error("Error:", error));
}
</script>

<script>
document.getElementById("finalSignupForm").addEventListener("submit", function(event) {
    event.preventDefault(); // ⛔ Prevent Page Reload

    let formData = new FormData(this);
    formData.append("user_id", "<?php echo $_SESSION['new_user_id']; ?>");

    fetch("scripts/completeSignup.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log("Signup Response:", data); // Debugging Output
        if (data.success) {
            alert("✅ Registration completed! Redirecting...");
            window.location.href = "user-dashboard.php"; // ✅ Redirect to the user dashboard
        } else {
            alert("❌ Error: " + data.message);
        }
    })
    .catch(error => {
        console.error("❌ AJAX Error:", error);
        alert("⚠️ Something went wrong.");
    });
});
 // Stop form from redirecting

    let formData = new FormData(this);
    formData.append("user_id", "<?php echo $_SESSION['new_user_id']; ?>");

    fetch("scripts/completeSignup.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log("Signup Response:", data);
        if (data.success) {
            alert("Registration successful! Redirecting...");
            window.location.href = "user-dashboard.php"; // ✅ Redirect after saving
        } else {
            alert("Error: " + data.message);
        }
    })
    .catch(error => {
        console.error("AJAX Error:", error);
        alert("Something went wrong.");
    });
});

    let formData = new FormData();
    formData.append("user_id", "<?php echo $_SESSION['new_user_id']; ?>");
    formData.append("first_name", document.getElementById("first_name").value.trim());
    formData.append("last_name", document.getElementById("last_name").value.trim());
    formData.append("email", document.getElementById("email").value.trim());

    fetch("scripts/completeSignup.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log("Signup Response:", data); // ✅ Debugging output

        if (data.success) {
            alert("Registration completed successfully! Redirecting...");
            window.location.href = data.redirect; // ✅ Redirects to the correct page
        } else {
            alert("Error: " + data.message);
        }
    })
    .catch(error => {
        console.error("AJAX Error:", error);
        alert("A network error occurred.");
    });
});


    let formData = new URLSearchParams();
    formData.append("user_id", "<?php echo $new_user_id; ?>");
    formData.append("first_name", document.getElementById("first_name").value.trim());
    formData.append("last_name", document.getElementById("last_name").value.trim());
    formData.append("email", document.getElementById("email").value.trim());

    fetch("scripts/completeSignup.php", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: formData.toString()
    })
    .then(response => response.json())
    .then(data => {
        console.log("Signup Response:", data); // ✅ Log response for debugging
        if (data.success) {
            alert("Registration completed successfully! Redirecting...");
            window.location.href = data.redirect;
        } else {
            alert("Error: " + data.message);
        }
    })
    .catch(error => {
        console.error("AJAX Error:", error);
        alert("A network error occurred.");
    });
});
.then(response => response.json())
.then(data => {
    console.log("Signup Response:", data); // ✅ Log response to console

    if (data.success) {
        alert("Registration completed successfully! Redirecting...");
        window.location.href = data.redirect;
    } else {
        alert("Error: " + data.message);
    }
})
.catch(error => {
    console.error("AJAX Error:", error);
    alert("A network error occurred.");
});

    .then(response => response.json())
    .then(data => {
if (data.success) {
    alert("Registration completed successfully! Redirecting...");
    window.location.href = data.redirect;
} else {
    alert("Error: " + data.message);
}
 else {
            alert("Error: " + data.message);
        }
    })
    .catch(error => {
        console.error("Error:", error);
        alert("An error occurred. Please try again.");
    });
});
</script>



<?php
file_put_contents("debug_log.txt", print_r($_POST, true) . PHP_EOL, FILE_APPEND);
?>

