<?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'; // Make sure this file has your DB connection as $mysqli

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and collect form data
    $study_type = $_POST['study_type'];
    $num_arms = $_POST['num_arms'];
    $randomization_method = $_POST['randomization_method'];
    $blinding_type = $_POST['blinding_type'];
    $study_duration = $_POST['study_duration'];
    $sample_size = $_POST['sample_size'];
    $num_sites = $_POST['num_sites'];
    $target_population = $_POST['target_population'];
    $inclusion_criteria = $_POST['inclusion_criteria'];
    $exclusion_criteria = $_POST['exclusion_criteria'];

    // Insert query using prepared statement for security
    $stmt = $mysqli->prepare("
        INSERT INTO study_design (
            study_type, num_arms, randomization_method, blinding_type,
            study_duration, sample_size, num_sites,
            target_population, inclusion_criteria, exclusion_criteria, clinic_id
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    if (!$stmt) {
        die("Prepare failed: " . $mysqli->error);
    }

    $stmt->bind_param(
        "sissiiisssi",
        $study_type,
        $num_arms,
        $randomization_method,
        $blinding_type,
        $study_duration,
        $sample_size,
        $num_sites,
        $target_population,
        $inclusion_criteria,
        $exclusion_criteria,
        $admin_id
    );

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

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