<?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');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../../logs/register_v2_errors.log');

// Create logs directory if it doesn't exist
$logDir = __DIR__ . '/../../logs';
if (!file_exists($logDir)) {
    mkdir($logDir, 0755, true);
}

// Log function
function logMessage($message, $data = null) {
    $logMessage = '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
    if ($data !== null) {
        $logMessage .= 'Data: ' . print_r($data, true) . "\n";
    }
    error_log($logMessage, 3, __DIR__ . '/../../logs/register_v2_errors.log');
}

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

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Method not allowed', null, 405);
}

try {
    // Get JSON input
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON input: ' . json_last_error_msg());
    }
    
    // Validate required fields
    $required = ['name', 'username', 'email', 'password', 'confirmPassword'];
    foreach ($required as $field) {
        if (empty($data[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }
    
    // Validate email
    if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Invalid email format');
    }
    
    // Validate password match
    if ($data['password'] !== $data['confirmPassword']) {
        throw new Exception('Passwords do not match');
    }
    
    // Validate password strength
    if (strlen($data['password']) < 8) {
        throw new Exception('Password must be at least 8 characters long');
    }
    
    // Hash password
    $passwordHash = password_hash($data['password'], PASSWORD_BCRYPT, ['cost' => 12]);
    if ($passwordHash === false) {
        throw new Exception('Failed to hash password');
    }
    
    // Generate verification token
    $token = bin2hex(random_bytes(32));
    $tokenHash = hash('sha256', $token);
    $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));
    
    // Centralized database connection
    require_once __DIR__ . '/includes/Database.php';
    $pdo = Database::getInstance()->getConnection();
    
    // Begin transaction
    $pdo->beginTransaction();
    
    try {
        // Check if user exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$data['username'], $data['email']]);
        
        if ($stmt->rowCount() > 0) {
            throw new Exception('Username or email already exists');
        }
        
        // Insert user
        $sql = "
            INSERT INTO users (
                name, username, email, password, 
                email_verified, email_verification_token, 
                status, kycStatus, balance, total_earned, is_admin
            ) VALUES (?, ?, ?, ?, 0, ?, 'active', 'pending', 0, 0, 0)
        ";
        
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([
            $data['name'],
            $data['username'],
            $data['email'],
            $passwordHash,
            $tokenHash
        ]);
        
        if (!$result) {
            $error = $stmt->errorInfo();
            throw new Exception('Failed to insert user: ' . ($error[2] ?? 'Unknown error'));
        }
        
        $userId = $pdo->lastInsertId();
        
        // Insert verification token
        $sql = "
            INSERT INTO email_verification_tokens 
            (user_id, token, expires_at) 
            VALUES (?, ?, ?)
        ";
        
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([
            $userId,
            $tokenHash,
            $expiresAt
        ]);
        
        if (!$result) {
            $error = $stmt->errorInfo();
            throw new Exception('Failed to insert verification token: ' . ($error[2] ?? 'Unknown error'));
        }
        
        // Commit transaction
        $pdo->commit();
        
        // Send success response
        sendResponse(true, 'Registration successful! Please check your email to verify your account.', [
            'user_id' => $userId,
            'email' => $data['email']
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
    
} catch (Exception $e) {
    logMessage('Registration error: ' . $e->getMessage(), [
        'trace' => $e->getTraceAsString(),
        'input' => $_POST ?? null,
        'json_input' => $json ?? null
    ]);
    
    // Don't expose internal errors to the client
    $errorMessage = 'Registration failed. Please try again later.';
    if ($e->getCode() === 23000) {
        // Duplicate entry error
        if (strpos($e->getMessage(), 'username') !== false) {
            $errorMessage = 'Username already exists';
        } elseif (strpos($e->getMessage(), 'email') !== false) {
            $errorMessage = 'Email already registered';
        }
    }
    
    sendResponse(false, $errorMessage, null, 500);
}
