<?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();
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$ward_filter = isset($_GET['ward']) ? $_GET['ward'] : '';
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Medication Schedule')); ?>
    <?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;
        }
        
        .schedule-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .time-slot {
            background: #f8fafc;
            border-left: 4px solid #2d7a2d;
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 8px;
        }
        
        .medication-item {
            padding: 0.75rem;
            border-bottom: 1px solid #e2e8f0;
            transition: background 0.2s;
        }
        
        .medication-item:hover {
            background: #f8fafc;
        }
        
        .medication-item:last-child {
            border-bottom: none;
        }
        
        .badge-pending {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-administered {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-missed {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .badge-morning {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-afternoon {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .badge-evening {
            background: #e0e7ff;
            color: #4338ca;
        }
        
        .badge-night {
            background: #1e293b;
            color: white;
        }
    </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">Medication Schedule</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">Patient Care</li>
                                        <li class="breadcrumb-item active">Medication Schedule</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-medicine-bottle-line me-2"></i>Medication Administration Schedule</h4>
                                <p class="mb-0">Track and manage medication administration for ward patients</p>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="schedule-card">
                                <form method="GET" class="row g-3 mb-4">
                                    <div class="col-md-4">
                                        <label class="form-label">Date</label>
                                        <input type="date" class="form-control" name="date" 
                                               value="<?php echo $selected_date; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Ward</label>
                                        <select class="form-select" name="ward">
                                            <option value="">All Wards</option>
                                            <option value="ENT_WARD" <?php echo $ward_filter === 'ENT_WARD' ? 'selected' : ''; ?>>ENT Ward</option>
                                            <option value="GENERAL" <?php echo $ward_filter === 'GENERAL' ? 'selected' : ''; ?>>General Ward</option>
                                            <option value="ICU" <?php echo $ward_filter === 'ICU' ? 'selected' : ''; ?>>ICU</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">&nbsp;</label>
                                        <button type="submit" class="btn btn-success w-100">
                                            <i class="ri-search-line me-1"></i> View Schedule
                                        </button>
                                    </div>
                                </form>
                                
                                <div class="table-responsive">
                                    <table id="medicationScheduleTable" class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Time</th>
                                                <th>Patient</th>
                                                <th>Medication</th>
                                                <th>Dosage</th>
                                                <th>Route</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody></tbody>
                                    </table>
                                </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>
        $(document).ready(function() {
            const table = $('#medicationScheduleTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: 'ajax/get_medication_schedule.php',
                    type: 'POST',
                    data: function(d) {
                        d.date = '<?php echo $selected_date; ?>';
                        d.ward = '<?php echo $ward_filter; ?>';
                    }
                },
                columns: [
                    { data: 'time' },
                    { data: 'patient' },
                    { data: 'medication' },
                    { data: 'dosage' },
                    { data: 'route' },
                    { data: 'status' },
                    { data: 'actions', orderable: false, searchable: false }
                ],
                order: [[0, 'asc']],
                pageLength: 50
            });
            
            setInterval(function() {
                table.ajax.reload(null, false);
            }, 120000);
        });

        function administerMedication(prescriptionId) {
            Swal.fire({
                title: 'Confirm Administration',
                text: 'Mark this medication as administered?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Administer',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('ajax/administer_medication.php', {
                        prescription_id: prescriptionId
                    }, function(response) {
                        if (response.success) {
                            Swal.fire('Success', 'Medication administered successfully', 'success');
                            $('#medicationScheduleTable').DataTable().ajax.reload();
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }, 'json');
                }
            });
        }
    </script>
</body>
</html>