<?php
/**
 * API: Register
 * Register new doctor account
 * Method: POST
 */

require_once '../config/config.php';
require_once '../includes/functions.php';
require_once '../includes/validation.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Check if registration is enabled
$pdo = getDB();
$stmt = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'registration_enabled'");
$regEnabled = $stmt->fetch();
if ($regEnabled && $regEnabled['setting_value'] != '1') {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Registration is currently disabled']);
    exit;
}

// Get input data
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

// Validate input
$errors = [];

$fullName = trim($input['full_name'] ?? '');
$username = trim($input['username'] ?? '');
$email = trim($input['email'] ?? '');
$password = $input['password'] ?? '';
$confirmPassword = $input['confirm_password'] ?? '';

if (empty($fullName)) $errors[] = "Full name is required";
if (empty($username)) $errors[] = "Username is required";
if (empty($email)) $errors[] = "Email is required";
if (empty($password)) $errors[] = "Password is required";

if (!isValidEmail($email)) $errors[] = "Invalid email format";

$passwordValidation = validatePasswordStrength($password);
if (!$passwordValidation['valid']) {
    $errors = array_merge($errors, $passwordValidation['errors']);
}

if ($password != $confirmPassword) $errors[] = "Passwords do not match";

// Check uniqueness
if (empty($errors)) {
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$username]);
    if ($stmt->fetch()) $errors[] = "Username already taken";
    
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->fetch()) $errors[] = "Email already registered";
}

if (!empty($errors)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => $errors]);
    exit;
}

// Create user account
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$apiKey = 'hom_' . bin2hex(random_bytes(32));

$stmt = $pdo->prepare("INSERT INTO users (username, email, full_name, password_hash, api_key, role, is_active, created_at) 
                      VALUES (?, ?, ?, ?, ?, 'doctor', 0, NOW())");
$stmt->execute([$username, $email, $fullName, $passwordHash, $apiKey]);

$userId = $pdo->lastInsertId();

// Send notification to admin (optional)
// mail($adminEmail, "New Doctor Registration", "A new doctor has registered: $fullName ($email)");

echo json_encode([
    'success' => true,
    'message' => 'Registration successful. Please wait for admin approval.',
    'data' => [
        'user_id' => $userId,
        'username' => $username,
        'email' => $email,
        'full_name' => $fullName,
        'api_key' => $apiKey
    ]
]);
?>