<?php
/**
 * Simplified Register - No Email Verification
 */

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

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('Access-Control-Allow-Credentials: true');

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

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

function sendResponse($success, $message, $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

try {
    global $pdo;
    
    if (!isset($pdo)) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    $rawInput = file_get_contents('php://input');
    $data = json_decode($rawInput, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        sendResponse(false, 'Invalid JSON data', null, 400);
    }
    
    $name = trim($data['name'] ?? '');
    $username = trim($data['username'] ?? '');
    $email = trim($data['email'] ?? '');
    $password = $data['password'] ?? '';
    $confirmPassword = $data['confirmPassword'] ?? '';
    
    // Validation
    if (empty($name) || empty($username) || empty($email) || empty($password) || empty($confirmPassword)) {
        sendResponse(false, 'All fields are required', null, 400);
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        sendResponse(false, 'Invalid email format', null, 400);
    }
    
    if ($password !== $confirmPassword) {
        sendResponse(false, 'Passwords do not match', null, 400);
    }
    
    if (strlen($password) < 6) {
        sendResponse(false, 'Password must be at least 6 characters', null, 400);
    }
    
    // Check duplicates
    $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        sendResponse(false, 'Email already exists', null, 400);
    }
    
    $stmt = $pdo->prepare('SELECT id FROM users WHERE username = ?');
    $stmt->execute([$username]);
    if ($stmt->fetch()) {
        sendResponse(false, 'Username already exists', null, 409);
    }
    
    // Create user
    $pdo->beginTransaction();
    
    try {
        $passwordHash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
        
        $sql = "INSERT INTO users (
            name, username, email, password, 
            email_verified, status, kycStatus, 
            balance, total_earned, is_admin
        ) VALUES (?, ?, ?, ?, 1, 'active', 'pending', 0, 0, 0)";
        
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([$name, $username, $email, $passwordHash]);
        
        if (!$result) {
            $errorInfo = $stmt->errorInfo();
            throw new Exception('Database error: ' . ($errorInfo[2] ?? 'Unknown'));
        }
        
        $userId = $pdo->lastInsertId();
        $pdo->commit();
        
        sendResponse(true, 'Registration successful! You can now log in.', [
            'user_id' => $userId,
            'username' => $username,
            'email' => $email
        ], 201);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log('Registration error: ' . $e->getMessage());
        sendResponse(false, 'Registration failed: ' . $e->getMessage(), null, 500);
    }
    
} catch (Exception $e) {
    error_log('Fatal error: ' . $e->getMessage());
    sendResponse(false, 'Server error', null, 500);
}
