<?php

header("Access-Control-Allow-Origin: *");
// Allow the methods you need
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// Allow headers (needed for JSON / custom headers)
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight requests quickly
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Then continue with your code
header("Content-Type: application/json");
include "config.php"; // ✅ DB connection
// Get JSON input
$data = json_decode(file_get_contents("php://input"), true);

// Validate required fields
if (
    empty($data['first_name']) ||
    empty($data['last_name']) ||
    empty($data['country']) ||
    empty($data['phone']) ||
    empty($data['dob']) ||
    empty($data['email']) ||
    empty($data['password'])
) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "All fields are required"]);
    exit;
}

$first_name = $conn->real_escape_string(trim($data['first_name']));
$last_name  = $conn->real_escape_string(trim($data['last_name']));
$country    = $conn->real_escape_string(trim($data['country']));
$phone      = $conn->real_escape_string(trim($data['phone']));
$dob        = $conn->real_escape_string(trim($data['dob']));
$email      = $conn->real_escape_string(trim($data['email']));
$password   = password_hash($data['password'], PASSWORD_BCRYPT);

// Check if email exists
$check = $conn->prepare("SELECT id FROM loginusers WHERE email = ?");
$check->bind_param("s", $email);
$check->execute();
$check->store_result();

if ($check->num_rows > 0) {
    http_response_code(409);
    echo json_encode(["status" => "error", "message" => "Email already exists"]);
    $check->close();
    exit;
}
$check->close();

// Insert user
$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(["status" => "success", "message" => "User registered successfully"]);
} else {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database error"]);
}

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