<?php
require 'db.php';

header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
$headers = getallheaders();

if (!isset($headers['Authorization'])) {
    echo json_encode(['message' => 'No token provided']);
    exit();
}

$token = str_replace('Bearer ', '', $headers['Authorization']);
$user = authenticate($token);

if (!$user) {
    echo json_encode(['message' => 'Unauthorized']);
    exit();
}

switch($method) {
    case 'GET':
        getData();
        break;
    default:
        echo json_encode(['message' => 'Method not allowed']);
        break;
}

function authenticate($token) {
    global $conn;
    
    $stmt = $conn->prepare("SELECT * FROM users WHERE token = :token");
    $stmt->bindParam(':token', $token);
    $stmt->execute();
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function getData() {
    echo json_encode(['message' => 'This is protected data']);
}
?>
