<?php
/**
 * API: Get Commands by Zone ID
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

// Include configuration
require_once __DIR__ . '/../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Get zone ID from request
$zoneId = isset($_GET['zone_id']) ? intval($_GET['zone_id']) : 0;

if (!$zoneId) {
    echo json_encode([]);
    exit;
}

// Get database connection
$pdo = getDBConnection();
if (!$pdo) {
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

try {
    // Prepare and execute query
    $stmt = $pdo->prepare("SELECT id, command_name FROM commands WHERE zone_id = ? ORDER BY command_name ASC");
    $stmt->execute([$zoneId]);
    $commands = $stmt->fetchAll();
    
    // Return JSON response
    echo json_encode($commands);
    
} catch (PDOException $e) {
    error_log("Error fetching commands: " . $e->getMessage());
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}