<?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'; // Ensure this contains $mysqli = new mysqli(...)

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Sanitize inputs
    $site_name       = trim($_POST['site_name']);
    $site_address    = trim($_POST['site_address']);
    $site_type       = trim($_POST['site_type']);
    $site_readiness  = trim($_POST['site_readiness']);
    $irb_approval    = trim($_POST['irb_approval']);
    $irb_contact     = trim($_POST['irb_contact']);

    // Handle checkbox array
    $infrastructure_arr = isset($_POST['infrastructure']) ? $_POST['infrastructure'] : [];
    $infrastructure = implode(', ', $infrastructure_arr); // convert array to comma-separated string

    // Prepare SQL insert
    $stmt = $mysqli->prepare("INSERT INTO site_facilities 
        (site_name, site_address, site_type, site_readiness, irb_approval, irb_contact, infrastructure, clinic_id)
        VALUES (?, ?, ?, ?, ?, ?, ? , ?)");

    if ($stmt) {
        $stmt->bind_param("sssssssi", $site_name, $site_address, $site_type, $site_readiness, $irb_approval, $irb_contact, $infrastructure, $admin_id);

        if ($stmt->execute()) {
            echo "<script>alert('Site details saved successfully!'); window.location.href='site_facility.php';</script>";
        } else {
            echo "<script>alert('Error saving data: " . $stmt->error . "'); history.back();</script>";
        }

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