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

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

$conn = db_connect();
$nurse_id = $_SESSION['user_id'];

// Get nurse information
$nurse_sql = "SELECT n.*, CONCAT(u.first_name, ' ', u.last_name) as nurse_name
              FROM nurses n
              INNER JOIN users u ON n.user_id = u.user_id
              WHERE n.user_id = ?";
$stmt = $conn->prepare($nurse_sql);
$stmt->bind_param('i', $nurse_id);
$stmt->execute();
$nurse_info = $stmt->get_result()->fetch_assoc();

// Get statistics
$stats_sql = "SELECT 
              COUNT(DISTINCT pv.visit_id) as total_assigned,
              COUNT(DISTINCT CASE WHEN pv.visit_status = 'IN_PROGRESS' THEN pv.visit_id END) as active_patients,
              COUNT(DISTINCT CASE WHEN pv.visit_status = 'ADMITTED' THEN pv.visit_id END) as admitted_patients
              FROM patient_visits pv
              WHERE pv.primary_nurse_id = ? OR pv.assigned_nurse_id = ?
              AND pv.visit_status IN ('ADMITTED', 'IN_PROGRESS')
              AND DATE(pv.registration_date) = CURDATE()";
$stmt = $conn->prepare($stats_sql);
$stmt->bind_param('ii', $nurse_id, $nurse_id);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Assigned Patients')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables/datatables.min.css" rel="stylesheet">
    <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;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-left: 4px solid #2d7a2d;
            margin-bottom: 1.5rem;
            transition: transform 0.2s;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #2d7a2d;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
            font-weight: 600;
        }
        
        .patient-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 #26a69a;
            transition: all 0.2s;
        }
        
        .patient-card:hover {
            transform: translateX(4px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .patient-card.priority-high {
            border-left-color: #ef4444;
            background: #fef2f2;
        }
        
        .badge-admitted {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .badge-in-progress {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-critical {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .badge-stable {
            background: #d1fae5;
            color: #065f46;
        }
        
        .task-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .task-item {
            padding: 0.5rem;
            margin-bottom: 0.25rem;
            background: #f8fafc;
            border-radius: 4px;
            font-size: 0.875rem;
        }
        
        .task-item.overdue {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .quick-action-btn {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
            margin-right: 0.5rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <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">My Assigned Patients</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">My Patients</li>
                                        <li class="breadcrumb-item active">Assigned Patients</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-user-heart-line me-2"></i>My Patient Assignments</h4>
                                <p class="mb-0">Welcome, <?php echo htmlspecialchars($nurse_info['nurse_name']); ?> - Manage your assigned patients</p>
                            </div>
                            <button class="btn btn-light" onclick="window.print()">
                                <i class="ri-printer-line me-1"></i> Print List
                            </button>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="row">
                        <div class="col-xl-4 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['total_assigned']); ?></div>
                                <div class="stat-label">Total Assigned</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #f59e0b;"><?php echo number_format($stats['active_patients']); ?></div>
                                <div class="stat-label">Active Care</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #3b82f6;"><?php echo number_format($stats['admitted_patients']); ?></div>
                                <div class="stat-label">Admitted</div>
                            </div>
                        </div>
                    </div>

                    <!-- Patients List -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h5 class="mb-0">Patient List</h5>
                                        <div class="btn-group">
                                            <button class="btn btn-sm btn-outline-primary" onclick="filterPatients('all')">All</button>
                                            <button class="btn btn-sm btn-outline-warning" onclick="filterPatients('active')">Active</button>
                                            <button class="btn btn-sm btn-outline-danger" onclick="filterPatients('critical')">Critical</button>
                                        </div>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table id="assignedPatientsTable" class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Patient</th>
                                                    <th>Age/Gender</th>
                                                    <th>Ward/Bed</th>
                                                    <th>Admission Date</th>
                                                    <th>Status</th>
                                                    <th>Last Vitals</th>
                                                    <th>Priority Tasks</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Notes Panel -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="mb-3"><i class="ri-sticky-note-line me-2"></i>Quick Patient Note</h5>
                                    <form id="quickNoteForm">
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Select Patient *</label>
                                                <select class="form-select" id="quick_patient_id" name="patient_id" required>
                                                    <option value="">Choose Patient...</option>
                                                </select>
                                            </div>
                                            <div class="col-md-8 mb-3">
                                                <label class="form-label">Quick Note *</label>
                                                <input type="text" class="form-control" name="quick_note" 
                                                       placeholder="Enter quick observation or note..." required>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-success">
                                            <i class="ri-save-line me-1"></i> Save Quick Note
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

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

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

    <script>
        let patientsTable;
        
        $(document).ready(function() {
            loadPatientsTable();
            loadPatientDropdown();
            
            // Auto-refresh every 3 minutes
            setInterval(function() {
                patientsTable.ajax.reload(null, false);
            }, 180000);
        });
        
        function loadPatientsTable() {
            patientsTable = $('#assignedPatientsTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: 'ajax/get_assigned_patients.php',
                    type: 'POST',
                    data: function(d) {
                        d.nurse_id = <?php echo $nurse_id; ?>;
                    }
                },
                columns: [
                    { data: 'patient_info' },
                    { data: 'age_gender' },
                    { data: 'ward_bed' },
                    { data: 'admission_date' },
                    { data: 'status' },
                    { data: 'last_vitals' },
                    { data: 'tasks' },
                    { data: 'actions', orderable: false, searchable: false }
                ],
                order: [[3, 'desc']],
                pageLength: 15
            });
        }
        
        function loadPatientDropdown() {
            $.post('ajax/get_assigned_patients_dropdown.php', {
                nurse_id: <?php echo $nurse_id; ?>
            }, function(response) {
                if (response.success) {
                    let options = '<option value="">Choose Patient...</option>';
                    response.patients.forEach(function(patient) {
                        options += '<option value="' + patient.patient_id + '">' + 
                                  patient.patient_name + ' (' + patient.patient_number + ')</option>';
                    });
                    $('#quick_patient_id').html(options);
                }
            }, 'json');
        }
        
        function filterPatients(type) {
            // Implement filtering logic
            patientsTable.ajax.reload();
        }
        
        function recordVitals(patientId, visitId) {
            window.location.href = 'patient_vitals.php?patient_id=' + patientId + '&visit_id=' + visitId;
        }
        
        function administerMedication(patientId) {
            window.location.href = 'medication_admin.php?patient_id=' + patientId;
        }
        
        function addNursingNote(patientId, visitId) {
            window.location.href = 'nursing_notes.php?patient_id=' + patientId + '&visit_id=' + visitId;
        }
        
        function viewPatient(patientId) {
            window.location.href = 'patient_profile.php?id=' + patientId;
        }
        
        // Quick note form
        $('#quickNoteForm').on('submit', function(e) {
            e.preventDefault();
            
            $.post('ajax/save_quick_note.php', $(this).serialize(), function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Note Saved',
                        text: 'Quick note recorded successfully',
                        timer: 2000
                    });
                    $('#quickNoteForm')[0].reset();
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            }, 'json');
        });
    </script>
</body>
</html>