<?php
define('SECURE_ACCESS', true);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Redirect if already logged in
redirectIfLoggedIn();

$token = isset($_GET['token']) ? trim($_GET['token']) : '';
$ref = isset($_GET['ref']) ? trim($_GET['ref']) : '';
$error = '';
$invitation = null;
$isValid = false;

$configs = [];
try {
    if ($pdo !== null) {
        $stmt_c = $pdo->query("SELECT key, value FROM system_settings");
        $configs = $stmt_c->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
    }
} catch (PDOException $e) {
    // Ignore
}
$logo_url = !empty($configs['site_logo']) ? $configs['site_logo'] : 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=100&auto=format&fit=crop';
$site_name = !empty($configs['site_name']) ? $configs['site_name'] : 'EventPortal';

$default_emp_code = '';
if ($pdo !== null) {
    $prefix = $configs['emp_code_prefix'] ?? 'REPL';
    $length = (int)($configs['emp_code_length'] ?? 15);
    $default_type = $configs['emp_code_default_type'] ?? 'generated';
    $custom_val = $configs['emp_code_custom_value'] ?? 'EMP-DEFAULT';

    if ($default_type === 'generated') {
        $unique = false;
        $attempts = 0;
        while (!$unique && $attempts < 15) {
            $temp_code = generateEmployeeCode($prefix, $length);
            $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
            $check_code->execute([$temp_code]);
            if ($check_code->fetchColumn() == 0) {
                $default_emp_code = $temp_code;
                $unique = true;
            }
            $attempts++;
        }
    } else {
        $temp_code = $custom_val;
        $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
        $check_code->execute([$temp_code]);
        if ($check_code->fetchColumn() == 0) {
            $default_emp_code = $temp_code;
        } else {
            $unique = false;
            $suffix = 1;
            while (!$unique && $suffix < 100) {
                $s_code = $temp_code . '-' . $suffix;
                $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                $check_code->execute([$s_code]);
                if ($check_code->fetchColumn() == 0) {
                    $default_emp_code = $s_code;
                    $unique = true;
                }
                $suffix++;
            }
        }
    }
}

if ($pdo === null) {
    die("Database connection is not initialized.");
}

// 1. Verify user invitation token or referral code
$registration_mode = $configs['registration_mode'] ?? 'invite_only';
$sponsor_name = '';

if ($registration_mode === 'open') {
    $isValid = true;
    if (!empty($token)) {
        try {
            $stmt = $pdo->prepare("SELECT * FROM user_invitations WHERE token = ? AND status = 'pending'");
            $stmt->execute([$token]);
            $invitation = $stmt->fetch();
        } catch (PDOException $e) {
            // Ignore
        }
    }
    if (!empty($ref)) {
        try {
            $stmt = $pdo->prepare("SELECT first_name, last_name FROM users WHERE username = ? OR employee_code = ?");
            $stmt->execute([$ref, $ref]);
            $sponsor_data = $stmt->fetch();
            if ($sponsor_data) {
                $sponsor_name = trim($sponsor_data['first_name'] . ' ' . $sponsor_data['last_name']);
            }
        } catch (PDOException $e) {
            // Ignore
        }
    }
} else {
    if (!empty($token)) {
        try {
            $stmt = $pdo->prepare("SELECT * FROM user_invitations WHERE token = ? AND status = 'pending'");
            $stmt->execute([$token]);
            $invitation = $stmt->fetch();
            
            if ($invitation) {
                $isValid = true;
            } else {
                $error = "This user registration invitation link is invalid or has already been used.";
            }
        } catch (PDOException $e) {
            $error = "Database error verifying token: " . $e->getMessage();
        }
    } elseif (!empty($ref)) {
        try {
            // Verify if the referrer (employee code or username) exists in database
            $stmt = $pdo->prepare("SELECT first_name, last_name FROM users WHERE username = ? OR employee_code = ?");
            $stmt->execute([$ref, $ref]);
            $sponsor_data = $stmt->fetch();
            if ($sponsor_data) {
                $isValid = true;
                $sponsor_name = trim($sponsor_data['first_name'] . ' ' . $sponsor_data['last_name']);
            } else {
                $error = "The referral link is invalid or the sponsor does not exist.";
            }
        } catch (PDOException $e) {
            $error = "Database error verifying referral code: " . $e->getMessage();
        }
    } else {
        $error = "An invitation token or referral link is required to register a new user account.";
    }
}

// Generate Dynamic OG Data
$og_title = htmlspecialchars($site_name) . " - Registration";
$og_description = "Register your attendee account to explore and register for conferences.";
if (!empty($ref)) {
    $og_title = "Join " . htmlspecialchars($site_name) . " using my Employee Referral Code '" . htmlspecialchars($ref) . "'!";
    if (!empty($sponsor_name)) {
        $og_description = htmlspecialchars($sponsor_name) . " has invited you to join " . htmlspecialchars($site_name) . ". Register your attendee account today!";
    }
}

$og_image_url = $logo_url;
if (!filter_var($og_image_url, FILTER_VALIDATE_URL)) {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $base_dir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
    $og_image_url = $protocol . "://" . $host . $base_dir . '/' . ltrim($og_image_url, '/');
}
if (strpos($og_image_url, 'w=100') !== false) {
    // Better fallback image for sharing link preview
    $og_image_url = 'https://images.unsplash.com/photo-1540575467063-178a50c2df87?w=1200&auto=format&fit=crop';
}

$og_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . ($_SERVER['HTTP_HOST'] ?? 'localhost') . ($_SERVER['REQUEST_URI'] ?? '');

// 2. Handle Registration Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isValid) {
    $password = $_POST['password'] ?? '';
    $email = $invitation ? $invitation['email'] : filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $phone = htmlspecialchars(trim($_POST['phone'] ?? ''), ENT_QUOTES, 'UTF-8');
    $first_name = htmlspecialchars(trim($_POST['first_name'] ?? ''), ENT_QUOTES, 'UTF-8');
    $last_name = htmlspecialchars(trim($_POST['last_name'] ?? ''), ENT_QUOTES, 'UTF-8');
    $employee_code = '';

    if (empty($password) || empty($email) || empty($phone) || empty($first_name) || empty($last_name)) {
        $error = "Please fill in all required fields marked with *.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please provide a valid email address.";
    } else {
        try {
            // Auto-generate unique username from email prefix
            $base_username = strstr($email, '@', true);
            if (!$base_username) {
                $base_username = 'user';
            }
            $username = preg_replace('/[^a-zA-Z0-9]/', '', $base_username);
            if (empty($username)) $username = 'user';
            
            $check_user = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
            $check_user->execute([$username]);
            $suffix = 1;
            while ($check_user->fetchColumn() > 0) {
                $username = $base_username . $suffix;
                $check_user->execute([$username]);
                $suffix++;
            }

            // Check if email already exists
            $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
            $check->execute([$email]);
            
            // Check if phone already exists
            $check_ph = $pdo->prepare("SELECT COUNT(*) FROM users WHERE phone = ?");
            $check_ph->execute([$phone]);
            
            if ($check->fetchColumn() > 0) {
                $error = "An account with this email address already exists. Please login instead.";
            } else if ($check_ph->fetchColumn() > 0) {
                $error = "An account with this phone number already exists. Please login instead.";
            } else {
                $referrer_username = trim($_POST['referrer_username'] ?? '');
                $referrer_id = null;
                $parent_id = null;

                if (empty($referrer_username)) {
                    $error = "Your Team Leader Employee Code is required to register.";
                } else {
                    $stmt_ref = $pdo->prepare("SELECT id, designation_id FROM users WHERE username = ? OR employee_code = ?");
                    $stmt_ref->execute([$referrer_username, $referrer_username]);
                    $referrer = $stmt_ref->fetch();
                    if (!$referrer) {
                        $error = "The Team Leader Employee Code or username you entered does not exist.";
                    } else {
                        $referrer_id = $referrer['id'];

                        // Fetch matrix config of the sponsor to calculate parent with spillover
                        $m_width = 4;
                        $m_depth = 4;
                        if ($referrer['designation_id']) {
                            $stmt_m = $pdo->prepare("SELECT matrix_width, matrix_depth FROM designations WHERE id = ?");
                            $stmt_m->execute([$referrer['designation_id']]);
                            $des = $stmt_m->fetch();
                            if ($des) {
                                $m_width = (int)$des['matrix_width'];
                                $m_depth = (int)$des['matrix_depth'];
                            }
                        }

                        // Run BFS placement algorithm to find parent_id
                        $parent_id = findMatrixPlacement($referrer_id, $m_width, $m_depth);
                    }
                }

                // Fetch default designation rank
                $stmt_def_desig = $pdo->query("SELECT id FROM designations WHERE is_default = TRUE LIMIT 1");
                $default_designation_id = $stmt_def_desig->fetchColumn();
                if (!$default_designation_id) {
                    $default_designation_id = null;
                }

                $settings = getSystemSettings();
                $final_emp_code = '';

                // A. Check Employee Code handling
                if (empty($error)) {
                    if (!empty($employee_code)) {
                        // User supplied a custom code: validate uniqueness and length limits
                        if (strlen($employee_code) < 5 || strlen($employee_code) > 30) {
                            $error = "Employee code must be between 5 and 30 characters.";
                        } else {
                            $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                            $check_code->execute([$employee_code]);
                            if ($check_code->fetchColumn() > 0) {
                                $error = "The employee code you entered is already in use by another user.";
                            } else {
                                $final_emp_code = $employee_code;
                            }
                        }
                    } else {
                        // No employee code supplied: use Admin configuration
                        $prefix = $settings['emp_code_prefix'];
                        $length = (int)$settings['emp_code_length'];
                        $default_type = $settings['emp_code_default_type'];
                        $custom_val = $settings['emp_code_custom_value'];

                        if ($default_type === 'generated') {
                            // Loop to guarantee unique code generation
                            $unique = false;
                            $attempts = 0;
                            while (!$unique && $attempts < 15) {
                                $temp_code = generateEmployeeCode($prefix, $length);
                                $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                                $check_code->execute([$temp_code]);
                                if ($check_code->fetchColumn() == 0) {
                                    $final_emp_code = $temp_code;
                                    $unique = true;
                                }
                                $attempts++;
                            }
                            if (!$unique) {
                                $error = "Failed to generate a unique employee code. Please try again or contact support.";
                            }
                        } else {
                            // Static custom value: handle potential duplication by appending numerical suffixes
                            $temp_code = $custom_val;
                            $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                            $check_code->execute([$temp_code]);
                            
                            if ($check_code->fetchColumn() == 0) {
                                $final_emp_code = $temp_code;
                            } else {
                                $unique = false;
                                $suffix = 1;
                                while (!$unique && $suffix < 100) {
                                    $s_code = $temp_code . '-' . $suffix;
                                    $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                                    $check_code->execute([$s_code]);
                                    if ($check_code->fetchColumn() == 0) {
                                        $final_emp_code = $s_code;
                                        $unique = true;
                                    }
                                    $suffix++;
                                }
                            }
                        }
                    }
                }

                // B. Save User and Update Token Status (if no errors occurred)
                if (empty($error)) {
                    $pdo->beginTransaction();

                    $hashedPass = password_hash($password, PASSWORD_DEFAULT);
                    
                    // Insert User Account
                    $ins_user = $pdo->prepare("
                        INSERT INTO users (username, email, phone, password, role, status, employee_code, designation_id, referrer_id, parent_id, first_name, last_name) 
                        VALUES (?, ?, ?, ?, 'user', 'active', ?, ?, ?, ?, ?, ?)
                    ");
                    $ins_user->execute([$username, $email, $phone, $hashedPass, $final_emp_code, $default_designation_id, $referrer_id, $parent_id, $first_name, $last_name]);
                    $new_user_id = $pdo->lastInsertId('users_id_seq');

                    // Award Signup and Referral Bonuses using centralized helper
                    require_once __DIR__ . '/../includes/bonus_helper.php';
                    awardSignupAndReferralBonuses($new_user_id, $referrer_id);

                    if ($invitation) {
                        // Update Invitation Status
                        $upd_invite = $pdo->prepare("UPDATE user_invitations SET status = 'accepted' WHERE id = ?");
                        $upd_invite->execute([$invitation['id']]);
                    }

                    $pdo->commit();

                    $require_email_verification = ($configs['require_email_verification'] ?? '1') === '1';

                    if ($require_email_verification) {
                        // Generate Email Verification Token
                        $verify_token = bin2hex(random_bytes(32));
                        $upd_token = $pdo->prepare("UPDATE users SET email_verification_token = ? WHERE id = ?");
                        $upd_token->execute([$verify_token, $new_user_id]);

                        // Send Verification Email
                        require_once __DIR__ . '/../includes/notification_helper.php';
                        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
                        $host = $_SERVER['HTTP_HOST'];
                        $base_dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
                        $verification_link = $protocol . '://' . $host . $base_dir . '/verify_email/' . $verify_token;
                        
                        sendMultichannelNotification($new_user_id, 'email_verification', [
                            'username' => $username,
                            'verification_link' => $verification_link
                        ]);

                        if (session_status() === PHP_SESSION_NONE) {
                            session_start();
                        }
                        $_SESSION['flash_success'] = "Registration complete! Please check your email to verify your account before logging in.";
                        
                        header("Location: login");
                        exit();
                    } else {
                        // Set email as verified automatically
                        $upd_verified = $pdo->prepare("UPDATE users SET is_email_verified = TRUE WHERE id = ?");
                        $upd_verified->execute([$new_user_id]);
                        
                        // Auto Log In
                        if (session_status() === PHP_SESSION_NONE) {
                            session_start();
                        }
                        $_SESSION['user_id'] = $new_user_id;
                        $_SESSION['username'] = $username;
                        $_SESSION['email'] = $email;
                        $_SESSION['role'] = 'user';
                        $_SESSION['status'] = 'active';
                        $_SESSION['flash_success'] = "Registration complete! Welcome, employee $username! Your Employee Code is $final_emp_code.";
                        
                        header("Location: dashboard");
                        exit();
                    }
                }
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = "Transaction failed: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $og_title ?? 'RENENET EDUCARE'; ?></title>
    
    <!-- Open Graph / WhatsApp / Facebook Link Preview Meta Tags -->
    <meta property="og:title" content="<?php echo $og_title; ?>">
    <meta property="og:description" content="<?php echo $og_description; ?>">
    <meta property="og:image" content="<?php echo $og_image_url; ?>">
    <meta property="og:url" content="<?php echo $og_url; ?>">
    <meta property="og:type" content="website">
    
    <!-- Twitter Card Meta Tags -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo $og_title; ?>">
    <meta name="twitter:description" content="<?php echo $og_description; ?>">
    <meta name="twitter:image" content="<?php echo $og_image_url; ?>">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    
    <style>
        html {
            font-size: 16px;
        }
        @media (max-width: 576px) {
            html { font-size: 14px; }
        }
        body {
            font-size: calc(14px + 0.2vw);
            background-color: #f8f9fa;
        }
        .register-card {
            border: none;
            border-radius: 12px;
        }
    </style>
</head>
<body class="py-5">
    <div class="container-fluid px-md-5">
        <div class="row justify-content-center">
            <div class="col-12 col-lg-8 col-xl-6">
                
                <?php if (!$isValid): ?>
                    <!-- Invalid Invitation Alert -->
                    <div class="card shadow-lg border-0 register-card p-4 text-center">
                        <div class="card-body">
                            <div class="d-inline-flex p-3 bg-danger bg-opacity-10 text-danger rounded-circle mb-3">
                                <i class="bi bi-envelope-exclamation fs-1"></i>
                            </div>
                            <h2 class="fw-bold text-dark">Access Denied</h2>
                            <p class="text-muted fs-6 mb-4"><?php echo htmlspecialchars($error); ?></p>
                            <div class="d-grid gap-2 col-sm-6 mx-auto">
                                <a href="login" class="btn btn-primary py-2 fw-bold">
                                    <i class="bi bi-arrow-left me-1"></i> Back to Login Page
                                </a>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <!-- Onboarding Registration Form -->
                    <div class="card shadow-lg border-0 register-card p-4">
                        <div class="card-body">
                            <div class="text-center mb-4">
                                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="mb-3" style="max-width: 220px; max-height: 80px; object-fit: contain;">
                                <h2 class="fw-bold"><?php echo htmlspecialchars($site_name); ?></h2>
                                <p class="text-muted">Register your attendee account to explore and register for conferences</p>
                            </div>

                            <?php if (!empty($error)): ?>
                                <div class="alert alert-danger shadow-sm border-0 mb-4" role="alert">
                                    <i class="bi bi-x-circle-fill me-2"></i>
                                    <?php echo htmlspecialchars($error); ?>
                                </div>
                            <?php endif; ?>

                            <form method="POST" action="register?token=<?php echo htmlspecialchars($token); ?>&ref=<?php echo htmlspecialchars($ref); ?>">
                                
                                <div class="row g-3 mb-4">
                                     <div class="col-12 col-md-6">
                                         <label for="first_name" class="form-label">First Name <span class="text-danger">*</span></label>
                                         <input type="text" class="form-control" id="first_name" name="first_name" required placeholder="e.g. John" value="<?php echo htmlspecialchars($_POST['first_name'] ?? ''); ?>">
                                     </div>
                                     <div class="col-12 col-md-6">
                                         <label for="last_name" class="form-label">Last Name <span class="text-danger">*</span></label>
                                         <input type="text" class="form-control" id="last_name" name="last_name" required placeholder="e.g. Doe" value="<?php echo htmlspecialchars($_POST['last_name'] ?? ''); ?>">
                                     </div>
                                    <div class="col-12">
                                        <label for="email" class="form-label">Email Address <span class="text-danger">*</span></label>
                                        <?php if ($invitation): ?>
                                            <input type="email" class="form-control bg-light" id="email" readonly value="<?php echo htmlspecialchars($invitation['email']); ?>">
                                            <span class="small text-muted font-monospace">Linked to Invitation</span>
                                        <?php else: ?>
                                            <input type="email" class="form-control" id="email" name="email" required placeholder="e.g. user@example.com" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                                            <span class="small text-muted font-monospace">Required for Account Creation</span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="col-12">
                                        <label for="phone" class="form-label">Phone Number <span class="text-danger">*</span></label>
                                        <input type="tel" class="form-control" id="phone" name="phone" required placeholder="e.g. +919876543210" value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>">
                                        <span class="small text-muted font-monospace">Required for Account Creation and Login</span>
                                    </div>
                                    
                                    <div class="col-12">
                                        <label for="password" class="form-label">Password <span class="text-danger">*</span></label>
                                        <input type="password" class="form-control" id="password" name="password" required placeholder="••••••••">
                                    </div>



                                    <div class="col-12">
                                        <label for="referrer_username" class="form-label">Your Team Leader Employee Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="referrer_username" name="referrer_username" required placeholder="e.g. REPL123456" value="<?php echo htmlspecialchars($_POST['referrer_username'] ?? $_GET['ref'] ?? $configs['default_referrer_code'] ?? 'REPLUS123456789'); ?>">
                                        <span id="sponsor_name_display" class="small fw-bold mt-1 d-inline-block"></span>
                                    </div>
                                </div>

                                <div class="d-grid mb-2">
                                    <button type="submit" class="btn btn-primary btn-lg py-2.5 fw-bold">
                                        <i class="bi bi-check2-circle me-1"></i> Register Account
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>

            </div>
        </div>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const input = document.getElementById('referrer_username');
            const display = document.getElementById('sponsor_name_display');
            
            function checkSponsor() {
                const code = input.value.trim();
                if (code.length === 0) {
                    display.textContent = '';
                    return;
                }
                
                display.textContent = 'Checking...';
                display.className = 'small fw-bold text-muted mt-1 d-inline-block';
                
                fetch('api/check_sponsor.php?code=' + encodeURIComponent(code))
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            display.textContent = 'Team Leader: ' + data.name;
                            display.className = 'small fw-bold text-success mt-1 d-inline-block';
                        } else {
                            display.textContent = 'Code not found';
                            display.className = 'small fw-bold text-danger mt-1 d-inline-block';
                        }
                    })
                    .catch(() => {
                        display.textContent = 'Error checking code';
                        display.className = 'small fw-bold text-danger mt-1 d-inline-block';
                    });
            }
            
            input.addEventListener('blur', checkSponsor);
            input.addEventListener('keyup', function(e) {
                // Also trigger if they type a lot or pause, simple debounce could be used
                // But blur is usually enough. Let's just run it if they paste or load the page
            });
            
            // Initial check if field is pre-filled
            if (input.value.trim() !== '') {
                checkSponsor();
            }
        });
    </script>
</body>
</html>
