<?php
require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = getInput();

switch ($method) {
    case 'POST':
        // Login
        if (isset($input['username']) && isset($input['password'])) {
            $stmt = getDB()->prepare("SELECT id, username, name, role, password_hash FROM users WHERE username = ? AND is_active = 1");
            $stmt->execute([$input['username']]);
            $user = $stmt->fetch();

            if ($user && password_verify($input['password'], $user['password_hash'])) {
                // Generate simple token (use JWT library in production)
                $token = bin2hex(random_bytes(32));
                sendJson([
                    'success' => true,
                    'token' => $token,
                    'user' => [
                        'id' => $user['id'],
                        'name' => $user['name'],
                        'username' => $user['username'],
                        'role' => $user['role']
                    ]
                ]);
            } else {
                sendJson(['error' => 'Invalid credentials'], 401);
            }
        }
        break;

    case 'GET':
        // Get current user (verify token)
        $token = verifyToken();
        sendJson(['success' => true, 'message' => 'Token valid']);
        break;

    default:
        sendJson(['error' => 'Method not allowed'], 405);
}
