<?php
session_start();
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

$msg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add'])) {
    $name = $_POST['name'];
    $code = strtoupper($_POST['code']);
    $location = $_POST['location'];
    $contact = $_POST['contact'];
    $api_endpoint = $_POST['api_endpoint'];
    $api_key = bin2hex(random_bytes(16));
    $stmt = $conn->prepare("INSERT INTO hospitals (name, code, location, contact, api_endpoint, api_key, status) VALUES (?, ?, ?, ?, ?, ?, 'active')");
    $stmt->bind_param("ssssss", $name, $code, $location, $contact, $api_endpoint, $api_key);
    if ($stmt->execute()) $msg = "Hospital added. API Key: $api_key";
    else $msg = "Error: " . $conn->error;
}
$hospitals = $conn->query("SELECT * FROM hospitals ORDER BY name");
?>
<!DOCTYPE html>
<html><head><title>Manage Hospitals</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body><div class="container mt-4"><h2>Manage Hospitals (UHD Network)</h2><?php if($msg) echo "<div class='alert alert-info'>$msg</div>"; ?>
<form method="POST" class="mb-4"><div class="row"><div class="col-md-3"><input type="text" name="name" class="form-control" placeholder="Hospital Name" required></div>
<div class="col-md-2"><input type="text" name="code" class="form-control" placeholder="Code (e.g., LAGOSGEN)" required></div>
<div class="col-md-2"><input type="text" name="location" class="form-control" placeholder="City" required></div>
<div class="col-md-2"><input type="text" name="contact" class="form-control" placeholder="Phone"></div>
<div class="col-md-3"><input type="url" name="api_endpoint" class="form-control" placeholder="API Endpoint (URL)" required></div>
<div class="col-md-2"><button type="submit" name="add" class="btn btn-primary">Add Hospital</button></div></div></form>
<table class="table table-bordered"><thead><tr><th>Name</th><th>Code</th><th>Location</th><th>API Endpoint</th><th>API Key</th><th>Status</th></tr></thead><tbody>
<?php while($h=$hospitals->fetch_assoc()): ?>
<tr><td><?= htmlspecialchars($h['name']) ?></td><td><?= $h['code'] ?></td><td><?= $h['location'] ?></td><td><?= $h['api_endpoint'] ?></td><td><code><?= $h['api_key'] ?></code></td><td><?= $h['status'] ?></td></tr>
<?php endwhile; ?>
</tbody></table><a href="dashboard.php" class="btn btn-secondary">Back</a></div></body>
</html>