<?php
$host = 'localhost';
$user = 'uuqzchta_Kelechi';
$pass = 'Grarft2021';
$db = 'uuqzchta_uhd_database';

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// ============================================
// AUTOMATIC NOTIFICATION FEATURE
// ============================================

// Send notification to a single patient
function sendPatientNotification($patient_id, $title, $message, $type = 'info') {
    global $conn;
    $conn->query("CREATE TABLE IF NOT EXISTS patient_notifications (
        id INT AUTO_INCREMENT PRIMARY KEY,
        patient_id VARCHAR(50) NOT NULL,
        title VARCHAR(255) NOT NULL,
        message TEXT NOT NULL,
        type ENUM('info','success','warning','danger') DEFAULT 'info',
        is_read TINYINT(1) DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    $stmt = $conn->prepare("INSERT INTO patient_notifications (patient_id, title, message, type) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $patient_id, $title, $message, $type);
    return $stmt->execute();
}

// Send notification to a single doctor
function sendDoctorNotification($doctor_id, $title, $message, $type = 'info') {
    global $conn;
    $conn->query("CREATE TABLE IF NOT EXISTS doctor_notifications (
        id INT AUTO_INCREMENT PRIMARY KEY,
        doctor_id INT NOT NULL,
        title VARCHAR(255),
        message TEXT,
        type VARCHAR(50) DEFAULT 'info',
        is_read TINYINT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    $stmt = $conn->prepare("INSERT INTO doctor_notifications (doctor_id, title, message, type) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("isss", $doctor_id, $title, $message, $type);
    return $stmt->execute();
}

// Send broadcast to all patients
function sendBroadcastToPatients($title, $message, $type = 'info') {
    global $conn;
    $patients = $conn->query("SELECT patient_id FROM patients WHERE portal_active = 1");
    $count = 0;
    while ($p = $patients->fetch_assoc()) {
        $stmt = $conn->prepare("INSERT INTO patient_notifications (patient_id, title, message, type) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $p['patient_id'], $title, $message, $type);
        if ($stmt->execute()) $count++;
    }
    return $count;
}
?>