<?php
// Set headers first to ensure they're sent
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// Set absolute path for logs directory
$log_dir = __DIR__ . '/../../logs';
$log_file = $log_dir . '/registration_debug.log';

// Function to send JSON response and exit
function sendJsonResponse($success, $message = '', $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    $response = ['success' => $success];
    if ($message) $response['message'] = $message;
    if ($data !== null) $response['data'] = $data;
    echo json_encode($response);
    exit();
}

// Function to log messages with timestamp
function log_message($message, $data = null) {
    global $log_file;
    $log_entry = '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
    if ($data !== null) {
        $log_entry .= 'Data: ' . print_r($data, true) . "\n";
    }
    // Try to log to file, but don't fail if we can't
    @file_put_contents($log_file, $log_entry, FILE_APPEND);
}

// Ensure logs directory exists and is writable
if (!is_dir($log_dir)) {
    if (!@mkdir($log_dir, 0755, true)) {
        sendJsonResponse(false, 'Failed to create logs directory', null, 500);
    }
}

// Set error reporting
ini_set('display_errors', 0); // Don't output errors to response
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', $log_file);

// Log server and environment information
log_message("=== PHP Server Environment ===");
log_message("PHP Version: " . phpversion());
log_message("Server Software: " . ($_SERVER['SERVER_SOFTWARE'] ?? 'N/A'));
log_message("Document Root: " . ($_SERVER['DOCUMENT_ROOT'] ?? 'N/A'));
log_message("Current Directory: " . __DIR__);
log_message("Log Directory: " . $log_dir);
log_message("Log File: " . $log_file);

// Get request method
$request_method = $_SERVER['REQUEST_METHOD'];

// Log request details
log_message("=== New Request ===");
log_message("Time: " . date('Y-m-d H:i:s'));
log_message("Method: " . $request_method);
log_message("Request URI: " . ($_SERVER['REQUEST_URI'] ?? 'N/A'));
log_message("Content Type: " . ($_SERVER['CONTENT_TYPE'] ?? 'N/A'));

// Get raw input
$raw_input = file_get_contents('php://input');
log_message("Raw input: " . $raw_input);

// Handle preflight OPTIONS request
if ($request_method === 'OPTIONS') {
    log_message("Handling OPTIONS request");
    sendJsonResponse(true, 'Options request handled');
}

// Only allow POST requests
if ($request_method !== 'POST') {
    $error_msg = 'Method not allowed';
    log_message("Error: " . $error_msg);
    sendJsonResponse(false, $error_msg, null, 405);
}

// Parse JSON input
$data = json_decode($raw_input, true);

// Validate JSON
if (json_last_error() !== JSON_ERROR_NONE) {
    $error_msg = 'Invalid JSON: ' . json_last_error_msg();
    log_message("JSON parse error: " . $error_msg);
    log_message("Raw input that caused error: " . $raw_input);
    sendJsonResponse(false, $error_msg, null, 400);
}

// Log parsed data
log_message("Parsed data: ", $data);

// Validate required fields
$required_fields = ['name', 'username', 'email', 'password', 'confirmPassword'];
$missing_fields = [];

foreach ($required_fields as $field) {
    if (empty($data[$field])) {
        $missing_fields[] = $field;
    }
}

if (!empty($missing_fields)) {
    $error_msg = 'Missing required fields: ' . implode(', ', $missing_fields);
    log_message("Validation error: " . $error_msg);
    sendJsonResponse(false, $error_msg, ['missing_fields' => $missing_fields], 400);
}

// Validate email format
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
    $error_msg = 'Invalid email format';
    log_message("Validation error: " . $error_msg);
    sendJsonResponse(false, $error_msg, null, 400);
}

// Validate password match
if ($data['password'] !== $data['confirmPassword']) {
    $error_msg = 'Passwords do not match';
    log_message("Validation error: " . $error_msg);
    sendJsonResponse(false, $error_msg, null, 400);
}

// Validate password strength
if (strlen($data['password']) < 8) {
    $error_msg = 'Password must be at least 8 characters long';
    log_message("Validation error: " . $error_msg);
    sendJsonResponse(false, $error_msg, null, 400);
}

// If we get here, all validations passed
log_message('Input validation passed', [
    'name' => $data['name'],
    'username' => $data['username'],
    'email' => $data['email']
]);

// Here you would typically:
// 1. Check if username/email already exists
// 2. Hash the password
// 3. Create the user in the database
// 4. Send verification email (if needed)
// 5. Return success response

// For now, just return a success response
$response = [
    'success' => true,
    'message' => 'Registration successful',
    'user' => [
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email']
    ]
];

log_message("Registration successful", $response);
sendJsonResponse(true, 'Registration successful', [
    'user' => [
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email']
    ]
]);
