<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once "db_connect.php";

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$token = $_GET["token"] ?? "";

if (empty($token)) {
    $_SESSION['success_message'] = "Invalid verification link.";
    header("Location: ../html/index.php");
    exit;
}

$stmt = $conn->prepare("SELECT id, role FROM users WHERE verification_token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $user = $result->fetch_assoc();

    $update = $conn->prepare("
        UPDATE users
        SET email_verified = 1,
            verification_token = NULL
        WHERE id = ?
    ");
    $update->bind_param("i", $user["id"]);

    if ($update->execute()) {
        if ($user["role"] === "admin") {
            $_SESSION['success_message'] = "Email verified successfully. Your shop account is now waiting for admin approval.";
        } else {
            $_SESSION['success_message'] = "Email verified successfully. Your customer account is now active. You can now log in.";
        }
    } else {
        $_SESSION['success_message'] = "Verification failed. Please try again.";
    }
} else {
    $_SESSION['success_message'] = "Invalid or expired verification link.";
}

header("Location: ../html/index.php");
exit;
?>