<?php
require_once 'layouts/session.php';
require_once 'layouts/dbconn.php';

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'HEAD_NURSE') {
    header('Location: unauthorized.php');
    exit();
}

$conn = db_connect();
$visit_id = isset($_GET['visit_id']) ? intval($_GET['visit_id']) : 0;
$patient_id = isset($_GET['patient_id']) ? intval($_GET['patient_id']) : 0;

// Get patient info
$patient_sql = "SELECT p.patient_id, p.patient_number, 
                CONCAT(u.first_name, ' ', u.last_name) as full_name,
                TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age, 
                u.gender, pv.visit_status
                FROM patients p
                INNER JOIN users u ON p.user_id = u.user_id
                LEFT JOIN patient_visits pv ON pv.visit_id = ?
                WHERE p.patient_id = ?";
$stmt = $conn->prepare($patient_sql);
$stmt->bind_param('ii', $visit_id, $patient_id);
$stmt->execute();
$patient = $stmt->get_result()->fetch_assoc();

if (!$patient) {
    header('Location: ward_patients.php');
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_note'])) {
    $note_type = $_POST['note_type'];
    $note_content = trim($_POST['note_content']);
    $is_critical = isset($_POST['is_critical']) ? 1 : 0;
    
    // Since nursing_notes table doesn't exist in schema, we'll use consultations table
    // or create entries in a general notes format
    $insert_sql = "INSERT INTO consultations (
                    patient_id, visit_id, doctor_id, consultation_type, 
                    chief_complaint, clinical_notes, status, 
                    consultation_date, start_time, end_time, created_at
                   ) VALUES (?, ?, ?, 'NURSING_NOTE', ?, ?, 'COMPLETED', 
                            CURDATE(), CURTIME(), CURTIME(), NOW())";
    
    $stmt = $conn->prepare($insert_sql);
    $doctor_id = $_SESSION['user_id'];
    $title = "Nursing Note - " . $note_type;
    $content = "[" . ($is_critical ? "CRITICAL" : "ROUTINE") . "] " . $note_content;
    
    $stmt->bind_param('iiiss', $patient_id, $visit_id, $doctor_id, $title, $content);
    
    if ($stmt->execute()) {
        // Log activity
        $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, user_agent)
                        VALUES (?, 'ADD_NURSING_NOTE', 'NURSING', ?, 'CONSULTATION', ?, ?)";
        $activity_stmt = $conn->prepare($activity_sql);
        $note_id = $stmt->insert_id;
        $ip = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $activity_stmt->bind_param('iiss', $doctor_id, $note_id, $ip, $user_agent);
        $activity_stmt->execute();
        
        $_SESSION['success_message'] = "Nursing note recorded successfully";
        header('Location: nursing_notes.php?visit_id=' . $visit_id . '&patient_id=' . $patient_id);
        exit();
    } else {
        $error_message = "Error recording note: " . $conn->error;
    }
}

// Get nursing notes (from consultations with type NURSING_NOTE)
$notes_sql = "SELECT c.*, u.first_name, u.last_name,
              CONCAT(u.first_name, ' ', u.last_name) as nurse_name
              FROM consultations c
              LEFT JOIN users u ON c.doctor_id = u.user_id
              WHERE c.patient_id = ? AND c.visit_id = ?
              AND (c.consultation_type = 'NURSING_NOTE' OR c.chief_complaint LIKE 'Nursing Note%')
              ORDER BY c.created_at DESC";
$stmt = $conn->prepare($notes_sql);
$stmt->bind_param('ii', $patient_id, $visit_id);
$stmt->execute();
$nursing_notes = $stmt->get_result();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Nursing Notes')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #26a69a 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .patient-info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .note-form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .note-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1rem;
            border-left: 4px solid #2d7a2d;
            transition: transform 0.2s;
        }
        
        .note-card:hover {
            transform: translateX(4px);
        }
        
        .note-card.critical {
            border-left-color: #ef4444;
            background: #fef2f2;
        }
        
        .note-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 0.75rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .note-content {
            white-space: pre-wrap;
            color: #1e293b;
            line-height: 1.6;
        }
        
        .badge-critical {
            background: #fee2e2;
            color: #991b1b;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-weight: 600;
        }
        
        .badge-routine {
            background: #dbeafe;
            color: #1e40af;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-weight: 600;
        }
        
        .note-meta {
            font-size: 0.875rem;
            color: #64748b;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Nursing Notes</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="ward_patients.php">Ward Patients</a></li>
                                        <li class="breadcrumb-item active">Nursing Notes</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="ri-check-line me-2"></i><?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($error_message)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Patient Info -->
                    <div class="row">
                        <div class="col-12">
                            <div class="patient-info-card">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h5 class="mb-2"><?php echo htmlspecialchars($patient['full_name']); ?></h5>
                                        <div class="d-flex gap-3">
                                            <span><strong>Patient No:</strong> <?php echo htmlspecialchars($patient['patient_number']); ?></span>
                                            <span><strong>Age:</strong> <?php echo $patient['age']; ?> years</span>
                                            <span><strong>Gender:</strong> <?php echo ucfirst($patient['gender']); ?></span>
                                            <span><strong>Status:</strong> 
                                                <span class="badge bg-info"><?php echo $patient['visit_status']; ?></span>
                                            </span>
                                        </div>
                                    </div>
                                    <a href="ward_patients.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back to Ward
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Note Entry Form -->
                        <div class="col-xl-5">
                            <div class="note-form-card">
                                <h5 class="mb-4"><i class="ri-file-text-line me-2"></i>Add Nursing Note</h5>
                                <form method="POST" id="noteForm">
                                    <div class="mb-3">
                                        <label class="form-label">Note Type *</label>
                                        <select class="form-select" name="note_type" required>
                                            <option value="">Select Type</option>
                                            <option value="ASSESSMENT">Assessment</option>
                                            <option value="INTERVENTION">Intervention</option>
                                            <option value="OBSERVATION">Observation</option>
                                            <option value="MEDICATION">Medication Administration</option>
                                            <option value="VITAL_SIGNS">Vital Signs Check</option>
                                            <option value="WOUND_CARE">Wound Care</option>
                                            <option value="PATIENT_EDUCATION">Patient Education</option>
                                            <option value="HANDOVER">Shift Handover</option>
                                            <option value="INCIDENT">Incident Report</option>
                                            <option value="PROGRESS">Progress Note</option>
                                            <option value="OTHER">Other</option>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Note Content *</label>
                                        <textarea class="form-control" name="note_content" rows="8" 
                                                  required placeholder="Enter detailed nursing note using SBAR format:
S - Situation: What is happening with the patient?
B - Background: What is the clinical background/context?
A - Assessment: What do you think the problem is?
R - Recommendation: What should be done?"></textarea>
                                        <small class="text-muted">Use SBAR format for clarity and consistency</small>
                                    </div>
                                    
                                    <div class="form-check mb-3">
                                        <input class="form-check-input" type="checkbox" name="is_critical" id="is_critical">
                                        <label class="form-check-label" for="is_critical">
                                            <strong>Mark as Critical/Urgent</strong>
                                            <small class="d-block text-muted">Requires immediate attention from medical staff</small>
                                        </label>
                                    </div>
                                    
                                    <div class="alert alert-info">
                                        <i class="ri-information-line me-2"></i>
                                        <strong>Remember:</strong> Document objectively, include time, patient response, and any interventions performed.
                                    </div>
                                    
                                    <div class="d-flex gap-2">
                                        <a href="ward_patients.php" class="btn btn-light flex-fill">Cancel</a>
                                        <button type="submit" name="save_note" class="btn btn-success flex-fill">
                                            <i class="ri-save-line me-1"></i> Save Note
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <!-- Notes History -->
                        <div class="col-xl-7">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5><i class="ri-history-line me-2"></i>Previous Nursing Notes</h5>
                                <button class="btn btn-sm btn-outline-primary" onclick="window.print()">
                                    <i class="ri-printer-line me-1"></i> Print Notes
                                </button>
                            </div>
                            
                            <div class="notes-history">
                                <?php if ($nursing_notes->num_rows > 0): ?>
                                    <?php while($note = $nursing_notes->fetch_assoc()): 
                                        $is_critical = strpos($note['clinical_notes'], '[CRITICAL]') !== false;
                                        $note_content = str_replace(['[CRITICAL]', '[ROUTINE]'], '', $note['clinical_notes']);
                                    ?>
                                        <div class="note-card <?php echo $is_critical ? 'critical' : ''; ?>">
                                            <div class="note-header">
                                                <div>
                                                    <strong><?php echo htmlspecialchars($note['chief_complaint']); ?></strong>
                                                    <?php if ($is_critical): ?>
                                                        <span class="badge-critical ms-2">
                                                            <i class="ri-alert-line me-1"></i>CRITICAL
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="badge-routine ms-2">ROUTINE</span>
                                                    <?php endif; ?>
                                                    <div class="note-meta mt-2">
                                                        <i class="ri-time-line me-1"></i>
                                                        <?php echo date('M d, Y H:i', strtotime($note['created_at'])); ?>
                                                        <span class="mx-2">|</span>
                                                        <i class="ri-user-line me-1"></i>
                                                        <?php echo htmlspecialchars($note['nurse_name']); ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="note-content"><?php echo nl2br(htmlspecialchars($note_content)); ?></div>
                                        </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="alert alert-info">
                                        <i class="ri-information-line me-2"></i>
                                        No nursing notes recorded yet for this patient visit.
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
        // Form validation
        $('#noteForm').on('submit', function(e) {
            const noteContent = $('textarea[name="note_content"]').val().trim();
            
            if (noteContent.length < 20) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Note Too Short',
                    text: 'Please provide a more detailed note (minimum 20 characters)'
                });
                return false;
            }
            
            if ($('#is_critical').is(':checked')) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Critical Note',
                    text: 'You are marking this as a critical note. Are you sure?',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Save',
                    cancelButtonText: 'Review'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $('#noteForm')[0].submit();
                    }
                });
                return false;
            }
        });
    </script>
</body>
</html>