<?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";

$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;
}

// 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();

// Insert user with plain password
$stmt = $conn->prepare("INSERT INTO loginusers (first_name, last_name, country, phone, dob, email, password) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $first_name, $last_name, $country, $phone, $dob, $email, $password);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "User registered successfully"]);
} else {
    echo json_encode(["success" => false, "message" => "Registration failed"]);
}
$stmt->close();
$conn->close();
?>
