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

header('Content-Type: application/json');

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'HEAD_NURSE') {
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$conn = db_connect();

// DataTables parameters
$draw = isset($_POST['draw']) ? intval($_POST['draw']) : 1;
$start = isset($_POST['start']) ? intval($_POST['start']) : 0;
$length = isset($_POST['length']) ? intval($_POST['length']) : 50;

// Filters
$date_filter = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
$ward_filter = isset($_POST['ward']) ? $_POST['ward'] : '';

// Base query for medications due today
$base_query = "FROM prescriptions pr
               INNER JOIN patients p ON pr.patient_id = p.patient_id
               INNER JOIN users u ON p.user_id = u.user_id
               LEFT JOIN patient_visits pv ON pr.visit_id = pv.visit_id
               WHERE pr.status = 'ACTIVE'
               AND DATE(pr.prescribed_date) <= ?
               AND (pr.end_date IS NULL OR DATE(pr.end_date) >= ?)
               AND pr.dispensed = 1";

$params = [$date_filter, $date_filter];
$types = 'ss';

if (!empty($ward_filter)) {
    $base_query .= " AND pv.ward_assignment = ?";
    $params[] = $ward_filter;
    $types .= 's';
}

// Count total records
$count_sql = "SELECT COUNT(*) as total " . $base_query;
$stmt = $conn->prepare($count_sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$total_records = $stmt->get_result()->fetch_assoc()['total'];

// Fetch data
$data_sql = "SELECT pr.prescription_id, pr.prescription_number,
             p.patient_id, p.patient_number,
             CONCAT(u.first_name, ' ', u.last_name) as patient_name,
             pr.medication_name, pr.dosage, pr.frequency, pr.route,
             pr.prescribed_date, pr.start_date, pr.end_date,
             pv.ward_assignment, pv.bed_number
             " . $base_query . "
             ORDER BY pr.prescribed_date ASC, u.first_name ASC
             LIMIT ? OFFSET ?";

$params[] = $length;
$params[] = $start;
$types .= 'ii';
$stmt = $conn->prepare($data_sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
$current_hour = date('H');

while ($row = $result->fetch_assoc()) {
    // Parse frequency to determine administration times
    $frequency = strtolower($row['frequency']);
    $times = [];
    
    if (strpos($frequency, 'once') !== false || strpos($frequency, '1') !== false) {
        $times[] = '08:00';
    } elseif (strpos($frequency, 'twice') !== false || strpos($frequency, '2') !== false) {
        $times[] = '08:00';
        $times[] = '20:00';
    } elseif (strpos($frequency, 'three') !== false || strpos($frequency, '3') !== false) {
        $times[] = '08:00';
        $times[] = '14:00';
        $times[] = '20:00';
    } elseif (strpos($frequency, 'four') !== false || strpos($frequency, '4') !== false || strpos($frequency, '6 hours') !== false) {
        $times[] = '06:00';
        $times[] = '12:00';
        $times[] = '18:00';
        $times[] = '00:00';
    } elseif (strpos($frequency, '8 hours') !== false) {
        $times[] = '08:00';
        $times[] = '16:00';
        $times[] = '00:00';
    } else {
        $times[] = '08:00'; // Default
    }
    
    // Create entry for each administration time
    foreach ($times as $time) {
        $time_hour = intval(substr($time, 0, 2));
        
        // Determine status based on current time
        $status = 'PENDING';
        $status_class = 'badge-pending';
        
        if ($time_hour < $current_hour) {
            // Check if already administered (in production, check administration log)
            $status = 'ADMINISTERED';
            $status_class = 'badge-administered';
        } elseif ($time_hour < $current_hour - 1) {
            $status = 'MISSED';
            $status_class = 'badge-missed';
        }
        
        // Time slot badge
        $time_badge = '';
        if ($time_hour >= 6 && $time_hour < 12) {
            $time_badge = 'badge-morning';
            $time_label = 'Morning';
        } elseif ($time_hour >= 12 && $time_hour < 17) {
            $time_badge = 'badge-afternoon';
            $time_label = 'Afternoon';
        } elseif ($time_hour >= 17 && $time_hour < 21) {
            $time_badge = 'badge-evening';
            $time_label = 'Evening';
        } else {
            $time_badge = 'badge-night';
            $time_label = 'Night';
        }
        
        $time_display = '<span class="badge ' . $time_badge . '">' . $time . ' - ' . $time_label . '</span>';
        
        // Patient info
        $patient_info = htmlspecialchars($row['patient_name']) . '<br><small class="text-muted">' . 
                       htmlspecialchars($row['patient_number']) . '</small>';
        
        // Medication
        $medication = '<strong>' . htmlspecialchars($row['medication_name']) . '</strong>';
        
        // Status
        $status_display = '<span class="badge ' . $status_class . '">' . $status . '</span>';
        
        // Actions
        if ($status === 'PENDING') {
            $actions = '
                <button class="btn btn-sm btn-success" onclick="administerMedication(' . $row['prescription_id'] . ', \'' . $time . '\')" title="Administer">
                    <i class="ri-check-line me-1"></i> Administer
                </button>
            ';
        } else {
            $actions = '
                <button class="btn btn-sm btn-outline-secondary" disabled>
                    <i class="ri-check-double-line"></i> Done
                </button>
            ';
        }
        
        $data[] = [
            'time' => $time_display,
            'patient' => $patient_info,
            'medication' => $medication,
            'dosage' => htmlspecialchars($row['dosage']),
            'route' => ucfirst(strtolower($row['route'])),
            'status' => $status_display,
            'actions' => $actions
        ];
    }
}

$response = [
    'draw' => $draw,
    'recordsTotal' => $total_records,
    'recordsFiltered' => $total_records,
    'data' => $data
];

echo json_encode($response);
$conn->close();
?>