<?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'];


// DB connection
include 'dbconn.php'; // Make sure this file contains a valid $mysqli connection

// Sanitize and retrieve form inputs
$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'] ?? '';

// Handle file upload
$gcp_certificate_path = '';

if (isset($_FILES['gcp_certificate']) && $_FILES['gcp_certificate']['error'] === UPLOAD_ERR_OK) {
    $fileTmpPath = $_FILES['gcp_certificate']['tmp_name'];
    $fileName = $_FILES['gcp_certificate']['name'];
    $fileSize = $_FILES['gcp_certificate']['size'];
    $fileType = mime_content_type($fileTmpPath);
    $fileNameCmps = explode(".", $fileName);
    $fileExtension = strtolower(end($fileNameCmps));

    // Allowed extensions
    $allowedfileExtensions = ['pdf', 'jpg', 'jpeg', 'png'];

    if (!in_array($fileExtension, $allowedfileExtensions)) {
        die('<script>alert("Upload failed. Allowed file types: pdf, jpg, jpeg, png."); window.history.back();</script>');
    }

    // Validate PDF size (<= 5MB)
    if ($fileExtension === 'pdf' && $fileSize > (5 * 1024 * 1024)) {
        die('<script>alert("PDF file must be less than or equal to 5MB."); window.history.back();</script>');
    }

    // Validate image size (must be 1000x1000 px)
   if (in_array($fileExtension, ['jpg', 'jpeg', 'png'])) {
    $imageInfo = getimagesize($fileTmpPath);
    if (!$imageInfo) {
        die('<script>alert("Invalid image file."); window.history.back();</script>');
    }

    $width = $imageInfo[0];
    $height = $imageInfo[1];

    if ($width > 1000 || $height > 1000) {
        die('<script>alert("Image dimensions must not exceed 1000x1000 pixels."); window.history.back();</script>');
    }
}


    // All good, move file
    $uploadFileDir = 'uploads/gcp_certificates/';
    if (!is_dir($uploadFileDir)) {
        mkdir($uploadFileDir, 0777, true);
    }

    $newFileName = uniqid('gcp_', true) . '.' . $fileExtension;
    $dest_path = $uploadFileDir . $newFileName;

    if (move_uploaded_file($fileTmpPath, $dest_path)) {
        $gcp_certificate_path = $dest_path;
    } else {
        die('<script>alert("Error moving the uploaded file."); window.history.back();</script>');
    }
}


// Insert into database
$stmt = $mysqli->prepare("INSERT INTO principal_investigators 
    (pi_name, institution_name, department, contact_number, email_address, investigator_experience, gcp_certified, gcp_certificate_path, clinic_id) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)");

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

$stmt->bind_param(
    "ssssssssi",
    $pi_name,
    $institution_name,
    $department,
    $contact_number,
    $email_address,
    $investigator_experience,
    $gcp_certified,
    $gcp_certificate_path,
    $admin_id
);

if ($stmt->execute()) {
    echo "<script>
        alert('Data inserted successfully!');
        window.location.href = 'principal_investigators.php'; // change to your actual destination
    </script>";
} else {
    echo "<script>
        alert('Error inserting data: " . addslashes($stmt->error) . "');
        window.history.back(); // or use a fallback page
    </script>";
}

$stmt->close();
$mysqli->close();
?>
