<?php
require 'config.php';
header("Content-Type: application/json");

$conn = getDbConnection();

// ✅ Read admin token from request
$data = json_decode(file_get_contents("php://input"), true);
$token = $data['token'] ?? '';

if (empty($token)) {
    echo json_encode(["success" => false, "message" => "Missing token"]);
    exit();
}

// ✅ Get admin details
$stmt = $conn->prepare("SELECT org_id, site_id FROM admin_users WHERE token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();
$admin = $result->fetch_assoc();

if (!$admin) {
    echo json_encode(["success" => false, "message" => "Invalid token"]);
    exit();
}

$org_id = $admin['org_id'];
$site_id = $admin['site_id'];

if ($org_id == 0) {
    // Super Admin - Fetch all sites
    $query = "SELECT site_id, site_name FROM sites";
} elseif ($site_id == 0) {
    // Superior Admin - Fetch all sites within the organization
    $query = "SELECT site_id, site_name FROM sites WHERE org_id = ?";
} else {
    // Normal Admin - Fetch only the assigned site
    $query = "SELECT site_id, site_name FROM sites WHERE site_id = ?";
}

$stmt = $conn->prepare($query);
if ($org_id != 0 && $site_id == 0) {
    $stmt->bind_param("i", $org_id);
} elseif ($site_id > 0) {
    $stmt->bind_param("i", $site_id);
}
$stmt->execute();
$result = $stmt->get_result();

$sites = [];
while ($row = $result->fetch_assoc()) {
    $sites[] = $row;
}

// ✅ Return sites
echo json_encode(["success" => true, "sites" => $sites]);

$stmt->close();
$conn->close();
?>
