<?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(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$conn = db_connect();

try {
    $prescription_id = isset($_POST['prescription_id']) ? intval($_POST['prescription_id']) : 0;
    $admin_time = isset($_POST['admin_time']) ? $_POST['admin_time'] : date('H:i');
    
    if ($prescription_id <= 0) {
        throw new Exception('Invalid prescription ID');
    }
    
    // Get prescription details
    $check_sql = "SELECT pr.*, p.patient_id, p.patient_number 
                  FROM prescriptions pr
                  INNER JOIN patients p ON pr.patient_id = p.patient_id
                  WHERE pr.prescription_id = ? AND pr.status = 'ACTIVE'";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param('i', $prescription_id);
    $stmt->execute();
    $prescription = $stmt->get_result()->fetch_assoc();
    
    if (!$prescription) {
        throw new Exception('Prescription not found or not active');
    }
    
    $conn->begin_transaction();
    
    // In a full implementation, you would have a medication_administration table
    // For now, we'll create a nursing note to record the administration
    $note_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(), ?, ?, NOW())";
    
    $stmt = $conn->prepare($note_sql);
    $user_id = $_SESSION['user_id'];
    $title = "Medication Administration - " . $prescription['medication_name'];
    $notes = "Administered: " . $prescription['medication_name'] . "\n" .
             "Dosage: " . $prescription['dosage'] . "\n" .
             "Route: " . $prescription['route'] . "\n" .
             "Time: " . date('H:i') . "\n" .
             "Administered by: Nurse";
    
    $stmt->bind_param('iiissss', 
        $prescription['patient_id'],
        $prescription['visit_id'],
        $user_id,
        $title,
        $notes,
        $admin_time,
        $admin_time
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to record medication administration');
    }
    
    $note_id = $stmt->insert_id;
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                     new_values, ip_address, user_agent)
                     VALUES (?, 'ADMINISTER_MEDICATION', 'MEDICATION', ?, 'PRESCRIPTION', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $log_data = json_encode([
        'prescription_id' => $prescription_id,
        'medication' => $prescription['medication_name'],
        'dosage' => $prescription['dosage'],
        'time' => $admin_time
    ]);
    $ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $stmt->bind_param('iisss', $user_id, $prescription_id, $log_data, $ip, $user_agent);
    $stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Medication administered successfully',
        'note_id' => $note_id
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>