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

// ✅ Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'admin_sites_error.log');

// ✅ Read JSON input
$data = json_decode(file_get_contents("php://input"), true);

// ✅ Validate required fields
if (!isset($data['admin_id'])) {
    echo json_encode(["success" => false, "message" => "Missing required fields"]);
    exit();
}

$admin_id = intval($data['admin_id']);

// ✅ Fetch admin details to check access level
$stmt = $conn->prepare("SELECT org_id, site_id FROM admin_users WHERE id = ?");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();
$admin = $result->fetch_assoc();

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

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

// ✅ Fetch sites based on admin's privileges
if ($org_id == 0) {
    // **Super Admin - Fetch All Sites**
    $stmt = $conn->prepare("SELECT site_id, org_id, site_name FROM sites");
} else {
    if ($site_id == -1) {
        // **Admin with Organization Access - Fetch Org Sites**
        $stmt = $conn->prepare("SELECT site_id, org_id, site_name FROM sites WHERE org_id = ?");
        $stmt->bind_param("i", $org_id);
    } else {
        // **Admin with Specific Site Access**
        $stmt = $conn->prepare("SELECT site_id, org_id, site_name FROM sites WHERE site_id = ?");
        $stmt->bind_param("i", $site_id);
    }
}

$stmt->execute();
$result = $stmt->get_result();
$sites = [];

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

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

$conn->close();
?>
