<?php
session_start();

if (!isset($_SESSION['clinic_logged_in']) || $_SESSION['clinic_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}

// Optional: access admin ID like this
$admin_id = $_SESSION['clinic_id'];
include 'dbconn.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    $site_name = $mysqli->real_escape_string(trim($_POST['site_name']));
    $site_address = $mysqli->real_escape_string(trim($_POST['site_address']));
    $site_type = $mysqli->real_escape_string(trim($_POST['site_type']));
    $site_readiness = $mysqli->real_escape_string(trim($_POST['site_readiness']));
    $irb_approval = $mysqli->real_escape_string(trim($_POST['irb_approval']));
    $irb_contact = $mysqli->real_escape_string(trim($_POST['irb_contact']));
    $infrastructure = isset($_POST['infrastructure']) ? implode(',', $_POST['infrastructure']) : '';

    $stmt = $mysqli->prepare("
        UPDATE site_facilities 
        SET 
            site_name = ?, 
            site_address = ?, 
            site_type = ?, 
            site_readiness = ?, 
            irb_approval = ?, 
            irb_contact = ?, 
            infrastructure = ?
        WHERE id = ?
    ");
    $stmt->bind_param("sssssssi", $site_name, $site_address, $site_type, $site_readiness, $irb_approval, $irb_contact, $infrastructure, $id);

    if ($stmt->execute()) {
        // Success: Show alert and redirect
        echo "<script>
            alert('Site details updated successfully.');
            window.location.href = 'site_facility.php?id=$id'; // change to your target page
        </script>";
    } else {
        // Error: Show alert
        echo "<script>
            alert('Error updating record: " . $stmt->error . "');
            window.history.back();
        </script>";
    }

    $stmt->close();
} else {
    echo "<script>alert('Invalid request.'); window.history.back();</script>";
}
?>
