<?php
session_start();
include("connect.php");

// Ensure user is logged in
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role'])) {
    echo "<script>alert('Unauthorized access! Please login.'); window.location.href='tm-login.php';</script>";
    exit;
}

$tmid = $_SESSION['user_id'];
$role = $_SESSION['role'];

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve and sanitize input
    $doctorName = trim($_POST['doctorname'] ?? '');
    $clinicAddress = trim($_POST['clinic_address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $noOfPatients = trim($_POST['no_of_patients_screened'] ?? '');

    // Basic validation
    if (empty($doctorName) || empty($noOfPatients) || !is_numeric($noOfPatients)) {
        echo "<script>alert('Please provide valid Doctor Name and Number of Patients Screened.'); history.back();</script>";
        exit;
    }

    // Prepare SQL based on role
    if ($role === "Admin") {
        $stmt = $conn->prepare("INSERT INTO doctors (doctor_name, tm_id, clinic_address, city, state, no_of_patients_screened) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssi", $doctorName, $tmid, $clinicAddress, $city, $state, $noOfPatients);
    } else {
        $stmt = $conn->prepare("INSERT INTO doctors (doctor_name, tm_id,clinic_address, city, state, no_of_patients_screened) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssi", $doctorName, $tmid, $clinicAddress, $city, $state, $noOfPatients);
    }

    // Execute and check result
    if ($stmt->execute()) {
        echo "1";
        exit;
    } else {
        echo "<script>alert('Error saving data. Please try again.'); history.back();</script>";
    }

    $stmt->close();
}

$conn->close();
?>
