<?php
// get_menu.php

header("Content-Type: application/json; charset=UTF-8");

require 'security.php';
require 'logger.php';
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on get_menu.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Mendapatkan token dari header Authorization
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in get_menu.php");
    exit;
}

try {
    // 1) Cek apakah token valid dan tidak expired
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();

    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in get_menu.php");
        exit;
    }

    // 2) Ambil daftar menu dari database
    $stmt = $pdo->prepare("SELECT id, name, route_name, icon_url FROM menu_items");
    $stmt->execute();
    $menu = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$menu) {
        http_response_code(404);
        echo json_encode(['error' => 'No menu items found']);
        log_activity("No menu items found in get_menu.php");
        exit;
    }

    // 3) Kirim response daftar menu
    http_response_code(200);
    echo json_encode($menu);
    log_activity("Menu data retrieved successfully.");

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("get_menu.php error: " . $e->getMessage());
    exit;
}
?>
