<?php
require_once './src/Database.php';
$conn = Database::getInstance();

$message = '';
$redirect = false;

if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $supportEmail = $_POST['support-email'];
    $company = $_POST['company'];
    $phone = $_POST['phone'];
    $domainName = $_POST['domain'];

    $sql = "UPDATE bitrix24_users SET 
        name = ?, 
        email_id = ?, 
        support_email = ?, 
        company_name = ?, 
        phone = ?, 
        app_status = 1,
        first_user = 1  
        WHERE domain_name = ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssssss", $name, $email, $supportEmail, $company, $phone, $domainName);

    if ($stmt->execute()) {
        $message = "Record updated successfully.";
        $redirect = true;
    } else {
        $message = "Error: " . $stmt->error;
    }

    $stmt->close();
    $conn->close();
} else {
    $message = "No data submitted.";
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Updating...</title>
<script>
    // Show wait message first
    function showMessage() {
        document.getElementById('waitMsg').style.display = 'block';
        document.getElementById('resultMsg').style.display = 'none';
    }
    window.onload = showMessage;
</script>
</head>
<body>
    <div id="waitMsg" style="font-size: 20px; font-weight: bold;">
        Please wait, verifying your information...
    </div>
    <div id="resultMsg" style="font-size: 18px; font-weight: bold; display:none; margin-top:20px;">
        <?= htmlspecialchars($message) ?>
    </div>

    <?php if ($redirect): ?>
    <script>
        // After 2 seconds show result message and then after 5 seconds redirect
        setTimeout(() => {
            document.getElementById('waitMsg').style.display = 'none';
            document.getElementById('resultMsg').style.display = 'block';
        }, 2000);

        setTimeout(() => {
            window.location.href = 'dashboard.php';
        }, 7000); // 2 + 5 seconds total
    </script>
    <?php else: ?>
    <script>
        // If error or no data, hide wait and show message immediately
        setTimeout(() => {
            document.getElementById('waitMsg').style.display = 'none';
            document.getElementById('resultMsg').style.display = 'block';
        }, 1000);
    </script>
    <?php endif; ?>
</body>
</html>
