<?php
/**
 * API: Authentication Endpoints
 * Routes:
 * POST /api/v1/auth/register
 * POST /api/v1/auth/login
 * POST /api/v1/auth/logout
 * POST /api/v1/auth/verify-token
 */

require_once __DIR__ . '/../../app/controller/AuthController.php';

$authController = new \App\Controller\AuthController($db);

switch ($method) {
    case 'POST':
        if ($action === 'register') {
            registerUser($db, $input);
        } elseif ($action === 'login') {
            loginUser($db, $input);
        } elseif ($action === 'logout') {
            logoutUser();
        } elseif ($action === 'verify-token') {
            verifyToken($db, $input);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Action not found']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}

/**
 * Register new user
 */
function registerUser($db, $input) {
    // Validate input
    $username = $input['username'] ?? '';
    $email = $input['email'] ?? '';
    $password = $input['password'] ?? '';
    $fullName = $input['full_name'] ?? '';
    
    if (!$username || !$email || !$password) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        return;
    }
    
    if (strlen($password) < 8) {
        http_response_code(400);
        echo json_encode(['error' => 'Password must be at least 8 characters']);
        return;
    }
    
    // Check if user exists
    $stmt = $db->prepare('SELECT id FROM users WHERE username = ? OR email = ?');
    $stmt->execute([$username, $email]);
    
    if ($stmt->fetch()) {
        http_response_code(409);
        echo json_encode(['error' => 'User already exists']);
        return;
    }
    
    // Create user
    try {
        $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
        $apiKey = bin2hex(random_bytes(16));
        
        $insertStmt = $db->prepare('
            INSERT INTO users (username, email, password, full_name, account_type, status, api_key, created_at)
            VALUES (?, ?, ?, ?, "user", "active", ?, NOW())
        ');
        
        $insertStmt->execute([$username, $email, $hashedPassword, $fullName, $apiKey]);
        $userId = $db->lastInsertId();
        
        // Initialize balance
        $db->prepare('UPDATE users SET balance = 0 WHERE id = ?')->execute([$userId]);
        
        http_response_code(201);
        echo json_encode([
            'success' => true,
            'user_id' => $userId,
            'api_key' => $apiKey,
            'message' => 'User registered successfully'
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Registration failed: ' . $e->getMessage()]);
    }
}

/**
 * Login user
 */
function loginUser($db, $input) {
    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';
    
    if (!$username || !$password) {
        http_response_code(400);
        echo json_encode(['error' => 'Username and password required']);
        return;
    }
    
    // Get user
    $stmt = $db->prepare('
        SELECT id, username, email, password, full_name, balance
        FROM users
        WHERE username = ? AND status = "active"
    ');
    $stmt->execute([$username]);
    $user = $stmt->fetch(\PDO::FETCH_ASSOC);
    
    if (!$user || !password_verify($password, $user['password'])) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid credentials']);
        return;
    }
    
    // Update last login
    $db->prepare('UPDATE users SET last_login = NOW() WHERE id = ?')->execute([$user['id']]);
    
    // Create session token (JWT-style)
    $token = bin2hex(random_bytes(32));
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['token'] = $token;
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'user_id' => $user['id'],
        'username' => $user['username'],
        'email' => $user['email'],
        'token' => $token,
        'balance' => $user['balance']
    ]);
}

/**
 * Logout user
 */
function logoutUser() {
    session_destroy();
    
    http_response_code(200);
    echo json_encode(['success' => true, 'message' => 'Logged out']);
}

/**
 * Verify API token
 */
function verifyToken($db, $input) {
    $apiKey = $input['api_key'] ?? '';
    
    if (!$apiKey) {
        http_response_code(400);
        echo json_encode(['error' => 'API key required']);
        return;
    }
    
    $stmt = $db->prepare('SELECT id, username, email FROM users WHERE api_key = ? AND status = "active"');
    $stmt->execute([$apiKey]);
    $user = $stmt->fetch(\PDO::FETCH_ASSOC);
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired API key']);
        return;
    }
    
    http_response_code(200);
    echo json_encode([
        'valid' => true,
        'user' => $user
    ]);
}
?>
