<?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') {
    $id = $_POST['id'];
    $pi_name = $_POST['pi_name'];
    $institution_name = $_POST['institution_name'];
    $department = $_POST['department'];
    $contact_number = $_POST['contact_number'];
    $email_address = $_POST['email_address'];
    $investigator_experience = $_POST['investigator_experience'];
    $gcp_certified = $_POST['gcp_certified'];

    $gcp_certificate_path = '';

    // Check if a new GCP certificate is uploaded
    if (isset($_FILES['gcp_certificate']) && $_FILES['gcp_certificate']['error'] == 0) {
        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileName = basename($_FILES['gcp_certificate']['name']);
        $targetFile = $uploadDir . time() . '_' . $fileName;

        if (move_uploaded_file($_FILES['gcp_certificate']['tmp_name'], $targetFile)) {
            $gcp_certificate_path = $targetFile;
        }
    }

    // If new file uploaded, update it; else keep existing
    if ($gcp_certificate_path !== '') {
        $stmt = $mysqli->prepare("UPDATE principal_investigators SET pi_name=?, institution_name=?, department=?, contact_number=?, email_address=?, investigator_experience=?, gcp_certified=?, gcp_certificate_path=? WHERE id=?");
        $stmt->bind_param("ssssssssi", $pi_name, $institution_name, $department, $contact_number, $email_address, $investigator_experience, $gcp_certified, $gcp_certificate_path, $id);
    } else {
        $stmt = $mysqli->prepare("UPDATE principal_investigators SET pi_name=?, institution_name=?, department=?, contact_number=?, email_address=?, investigator_experience=?, gcp_certified=? WHERE id=?");
        $stmt->bind_param("sssssssi", $pi_name, $institution_name, $department, $contact_number, $email_address, $investigator_experience, $gcp_certified, $id);
    }

    if ($stmt->execute()) {
        echo "<script>alert('Data updated successfully.'); window.location.href='principal_investigators.php';</script>";
    } else {
        echo "<script>alert('Error updating data: " . $stmt->error . "'); window.history.back();</script>";
    }

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