<?php
// api/patient/notifications.php
require_once __DIR__ . '/../middleware.php';
require_once __DIR__ . '/../../layouts/dbconn.php';

global $API_USER;
if (!isset($API_USER)) {
    jsonError('Unauthorized', 401);
}

// Get Patient ID
$user_id = $API_USER['sub'];
$stmt = $conn->prepare("SELECT patient_id FROM patients WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    jsonError('Patient profile not found', 404);
}

$patient = $res->fetch_assoc();
$patient_id = $patient['patient_id'];

// Ensure Table Exists
$conn->query("CREATE TABLE IF NOT EXISTS patient_notifications (
    notification_id INT AUTO_INCREMENT PRIMARY KEY,
    patient_id INT NOT NULL,
    title VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    is_read BOOLEAN DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // List Notifications
    $sql = "SELECT notification_id, title, message, is_read, created_at FROM patient_notifications WHERE patient_id = ? ORDER BY created_at DESC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $notifications = [];
    while ($row = $result->fetch_assoc()) {
        $notifications[] = $row;
    }

    jsonResponse($notifications);

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Mark Read
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';

    if ($action === 'mark_all_read') {
        $stmt = $conn->prepare("UPDATE patient_notifications SET is_read = 1 WHERE patient_id = ?");
        $stmt->bind_param("i", $patient_id);
        $stmt->execute();
        jsonResponse(['message' => 'All notifications marked as read']);
    } elseif ($action === 'mark_read' && !empty($input['notification_id'])) {
        $notif_id = $input['notification_id'];
        $stmt = $conn->prepare("UPDATE patient_notifications SET is_read = 1 WHERE patient_id = ? AND notification_id = ?");
        $stmt->bind_param("ii", $patient_id, $notif_id);
        $stmt->execute();
        jsonResponse(['message' => 'Notification marked as read']);
    } else {
        jsonError('Invalid action or missing ID', 400);
    }

} else {
    jsonError('Method not allowed', 405);
}
?>