<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("db.php");

$message = "";

if(isset($_GET['token'])){
    $token = mysqli_real_escape_string($conn, $_GET['token']);

    // Check if token exists and user is not active
    $check = mysqli_query($conn, "SELECT id, is_active FROM users WHERE activation_token='$token'");
    if(mysqli_num_rows($check) == 1){
        $row = mysqli_fetch_assoc($check);
        if($row['is_active'] == 1){
            $message = "<div class='alert alert-info'>Your account is already activated.</div>";
        } else {
            // Generate membership ID
            $membership_id = "PR" . str_pad($row['id'], 6, "0", STR_PAD_LEFT);

            // Activate account
            mysqli_query($conn, "UPDATE users SET is_active=1, membership_id='$membership_id' WHERE id=".$row['id']);

            // Redirect to dashboard
            header("Location: dashboard.php?uid=".$row['id']);
            exit;
        }
    } else {
        $message = "<div class='alert alert-danger'>Invalid activation token.</div>";
    }
} else {
    $message = "<div class='alert alert-danger'>No activation token provided.</div>";
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Account Activation</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">
    <?php if(!empty($message)) echo $message; ?>
</div>
</body>
</html>
