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

require "config.php";
require "mail_system.php"; // Include our mail system

$data = json_decode(file_get_contents("php://input"), true);

if (!$data) {
    echo json_encode(["success" => false, "message" => "Invalid data"]);
    exit;
}

$first_name = $data['first_name'] ?? '';
$last_name = $data['last_name'] ?? '';
$country = $data['country'] ?? '';
$phone = $data['phone'] ?? '';
$dob = $data['dob'] ?? '';
$email = $data['email'] ?? '';
$password = $data['password'] ?? '';

if (empty($first_name) || empty($last_name) || empty($email) || empty($password)) {
    echo json_encode(["success" => false, "message" => "All required fields must be filled"]);
    exit;
}

$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

// Check if email already exists
$stmt = $conn->prepare("SELECT id FROM loginusers WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "Email already registered"]);
    exit;
}
$stmt->close();

// Generate verification token
$verification_token = bin2hex(random_bytes(32));
$verification_expires = date('Y-m-d H:i:s', strtotime('+24 hours'));

// Insert user with verification token
$stmt = $conn->prepare("INSERT INTO loginusers (first_name, last_name, country, phone, dob, email, password, verification_token, verification_expires, is_verified) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)");
$stmt->bind_param("sssssssss", $first_name, $last_name, $country, $phone, $dob, $email, $hashedPassword, $verification_token, $verification_expires);

if ($stmt->execute()) {
    // Send verification email
    $mailer = new ZForexMailer();
    $verification_url = "https://yoursite.com/verify.php?token=" . $verification_token;
    $full_name = $first_name . " " . $last_name;
    
    $mail_result = $mailer->sendRegisterVerification($email, $full_name, $verification_url);
    
    if ($mail_result['success']) {
        echo json_encode([
            "success" => true, 
            "message" => "User registered successfully. Please check your email to verify your account.",
            "email_sent" => true
        ]);
    } else {
        echo json_encode([
            "success" => true, 
            "message" => "User registered successfully, but verification email could not be sent. Please contact support.",
            "email_sent" => false,
            "email_error" => $mail_result['message']
        ]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Registration failed"]);
}

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