<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type");

require "config.php";
require "mail_system.php";

// Get token from URL parameter
$token = $_GET['token'] ?? $_POST['token'] ?? '';

if (empty($token)) {
    echo json_encode(["success" => false, "message" => "Verification token is required"]);
    exit;
}

// Find user with this token
$stmt = $conn->prepare("SELECT id, first_name, last_name, email, is_verified, verification_expires FROM loginusers WHERE verification_token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "Invalid verification token"]);
    exit;
}

$user = $result->fetch_assoc();

// Check if already verified
if ($user['is_verified'] == 1) {
    echo json_encode(["success" => false, "message" => "Email already verified"]);
    exit;
}

// Check if token expired
if (strtotime($user['verification_expires']) < time()) {
    echo json_encode(["success" => false, "message" => "Verification token has expired"]);
    exit;
}

// Update user as verified
$update_stmt = $conn->prepare("UPDATE loginusers SET is_verified = 1, verification_token = NULL, verification_expires = NULL, verified_at = NOW() WHERE id = ?");
$update_stmt->bind_param("i", $user['id']);

if ($update_stmt->execute()) {
    // Send login credentials email
    $mailer = new ZForexMailer();
    $full_name = $user['first_name'] . " " . $user['last_name'];
    $login_url = "https://yoursite.com/login";
    
    // Note: In production, you might want to generate a temporary password or ask user to set one
    $temp_password = "Please set your password"; // Or generate a temporary one
    
    $mail_result = $mailer->sendLoginCredentials($user['email'], $full_name, $temp_password, $login_url);
    
    echo json_encode([
        "success" => true, 
        "message" => "Email verified successfully! Login credentials have been sent to your email.",
        "user_id" => $user['id'],
        "email_sent" => $mail_result['success']
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to verify email"]);
}

$stmt->close();
$update_stmt->close();
$conn->close();
?>