<?php
session_start();
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Invalid request method');
}

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

// This endpoint is now deprecated - use send_otp.php instead
// Keeping this for backward compatibility

// Validate input
if (!isset($data['name']) || !isset($data['email']) || !isset($data['password']) || !isset($data['confirmPassword'])) {
    sendResponse(false, 'All fields are required');
}

$name = trim($data['name']);
$email = trim($data['email']);
$password = $data['password'];
$confirmPassword = $data['confirmPassword'];

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(false, 'Invalid email format');
}

// Validate password length
if (strlen($password) < 6) {
    sendResponse(false, 'Password must be at least 6 characters long');
}

// Check if passwords match
if ($password !== $confirmPassword) {
    sendResponse(false, 'Passwords do not match');
}

// Check if email already exists
$stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    sendResponse(false, 'Email already registered');
}

// Hash password
$hashedPassword = hashPassword($password);

// Insert new user - Note: Now only for backward compatibility
// New signup flow uses OTP verification
$stmt = $conn->prepare("INSERT INTO users (name, email, password, is_email_verified, email_verified_at) VALUES (?, ?, ?, 1, NOW())");
$stmt->bind_param("sss", $name, $email, $hashedPassword);

if ($stmt->execute()) {
    $userId = $conn->insert_id;
    
    // Set session
    $_SESSION['user_id'] = $userId;
    $_SESSION['user_name'] = $name;
    $_SESSION['user_email'] = $email;
    
    sendResponse(true, 'Account created successfully', [
        'id' => $userId,
        'name' => $name,
        'email' => $email
    ]);
} else {
    sendResponse(false, 'Error creating account: ' . $conn->error);
}

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