<?php
/**
 * Get Locations by Library ID (AJAX)
 * Path: plugins/multi_opac_path/pages/get_locations.php
 * 
 * CATATAN: File ini diakses langsung via AJAX, endpoint khusus
 */

// ============================================================
// BYPASS INDEX_AUTH UNTUK AJAX (karena diakses langsung)
// ============================================================
if (!defined('INDEX_AUTH')) {
    define('INDEX_AUTH', true);
}

// Load SLiMS (tanpa INDEX_AUTH)
$basePath = dirname(__DIR__, 3);
require_once $basePath . '/sysconfig.inc.php';

// Load autoload
if (file_exists($basePath . '/lib/autoload.php')) {
    require_once $basePath . '/lib/autoload.php';
}

// Load helper
if (file_exists($basePath . '/lib/helper.inc.php')) {
    require_once $basePath . '/lib/helper.inc.php';
}

// Load helpers plugin
require_once __DIR__ . '/../src/helpers.php';

// ============================================================
// HANDLER
// ============================================================
$librarySlug = isset($_GET['library_id']) ? $_GET['library_id'] : '';

if (empty($librarySlug)) {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Library ID required']);
    exit;
}

// Ambil library_id dari slug
$library = getLibraryBySlug($librarySlug);
if (!$library) {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Library not found']);
    exit;
}

$libraryId = $library['library_id'];

// Ambil lokasi berdasarkan library_id
global $dbs;
if (!$dbs) {
    // Jika $dbs belum ada, ambil koneksi dari SLiMS
    $dbs = \SLiMS\DB::getInstance();
}

$query = $dbs->query("
    SELECT location_id, location_name 
    FROM mst_location 
    WHERE library_id = " . intval($libraryId) . "
    ORDER BY location_name ASC
");

$locations = [];
if ($query && $query->num_rows > 0) {
    while ($row = $query->fetch_assoc()) {
        $locations[] = $row;
    }
}

header('Content-Type: application/json');
echo json_encode(['status' => 'success', 'data' => $locations]);
exit;