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

$conn = getDbConnection();

// ✅ Read JSON input
$data = json_decode(file_get_contents("php://input"), true);
$username = $data['username'] ?? '';
$password = $data['password'] ?? '';

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

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

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

// ✅ Verify password
if (!password_verify($password, $admin['password'])) {
    echo json_encode(["success" => false, "message" => "Incorrect password"]);
    exit();
}

$admin_id = $admin['id'];
$org_id = $admin['org_id'] ?? 0;
$site_id = $admin['site_id'] ?? 0;

// ✅ Determine Admin Level
if ($org_id == 0) {
    $admin_level = "Super Admin";
    $site_query = "SELECT site_id FROM sites";
} elseif ($site_id == 0) {
    $admin_level = "Superior Admin";
    $site_query = "SELECT site_id FROM sites WHERE org_id = ?";
} else {
    $admin_level = "Site Admin";
    $site_query = "SELECT site_id FROM sites WHERE site_id = ?";
}

// ✅ Fetch sites based on privilege
$stmt = $conn->prepare($site_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();
$site_result = $stmt->get_result();

$sites = [];
while ($row = $site_result->fetch_assoc()) {
    $sites[] = $row['site_id'];
}

// ✅ Generate token
$token = bin2hex(random_bytes(32));

// ✅ Save token in database
$updateStmt = $conn->prepare("UPDATE admin_users SET token = ? WHERE id = ?");
$updateStmt->bind_param("si", $token, $admin_id);
$updateStmt->execute();

// ✅ Return response
echo json_encode([
    "success" => true,
    "message" => "Admin login successful",
    "token" => $token,
    "admin_id" => $admin_id,
    "org_id" => $org_id,
    "site_id" => $site_id,
    "admin_level" => $admin_level,
    "site_access" => $sites
]);

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