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

/*
|--------------------------------------------------------------------------
| ACCESS CONTROL
|--------------------------------------------------------------------------
*/
$allowed_roles = [
    'SUPER_ADMIN',
    'HOSPITAL_ADMIN',
    'RECEPTIONIST',
    'ENT_DOCTOR',
    'ENT_CONSULTANT',
    'HEAD_NURSE',
    'LAB_TECHNICIAN'
];

if (!isset($_SESSION['role_code']) || !in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: index.php');
    exit();
}

/*
|--------------------------------------------------------------------------
| INPUT VALIDATION
|--------------------------------------------------------------------------
*/
$visit_id   = isset($_GET['visit_id']) ? (int) $_GET['visit_id'] : 0;
$patient_id = isset($_GET['patient_id']) ? (int) $_GET['patient_id'] : 0;

if ($patient_id <= 0) {
    $_SESSION['error_message'] = 'No patient selected for vitals.';
    header('Location: ward_patients.php');
    exit();
}


/*
|--------------------------------------------------------------------------
| FETCH PATIENT DETAILS
|--------------------------------------------------------------------------
*/
$patient_sql = "
    SELECT 
        p.patient_id,
        p.patient_number,
        u.full_name,
        TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) AS age,
        u.gender,
        p.registration_type,
        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 = ?
    LIMIT 1
";

$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 VITALS SUBMISSION
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_vitals'])) {

    // Required
    $systolic_bp       = (int) $_POST['systolic_bp'];
    $diastolic_bp      = (int) $_POST['diastolic_bp'];
    $pulse_rate        = (int) $_POST['pulse_rate'];
    $temperature       = (float) $_POST['temperature'];
    $temperature_route = trim($_POST['temperature_route']);
    $respiratory_rate  = (int) $_POST['respiratory_rate'];
    $oxygen_saturation = (float) $_POST['oxygen_saturation'];
    $consciousness     = trim($_POST['consciousness_level']);

    // Optional
    $weight     = ($_POST['weight'] !== '') ? (float) $_POST['weight'] : null;
    $height     = ($_POST['height'] !== '') ? (float) $_POST['height'] : null;
    $pain_scale = ($_POST['pain_score'] !== '') ? (int) $_POST['pain_score'] : null;
    $notes      = trim($_POST['notes']);

    // Derived
    $blood_pressure = $systolic_bp . '/' . $diastolic_bp;
    $bmi = null;

    if ($weight && $height && $height > 0) {
        $height_m = $height / 100;
        $bmi = round($weight / ($height_m * $height_m), 2);
    }

    // Server-side BP validation
    if ($systolic_bp <= $diastolic_bp) {
        $error_message = "Systolic BP must be greater than Diastolic BP.";
    } else {

        $insert_sql = "
            INSERT INTO vital_signs (
                patient_id,
                visit_id,
                recorded_date,
                blood_pressure,
                systolic_bp,
                diastolic_bp,
                pulse_rate,
                temperature,
                temperature_route,
                respiratory_rate,
                oxygen_saturation,
                weight,
                height,
                bmi,
                pain_scale,
                consciousness_level,
                notes,
                recorded_by
            ) VALUES (
                ?, ?, NOW(),
                ?, ?, ?,
                ?, ?, ?,
                ?, ?,
                ?, ?, ?,
                ?, ?,
                ?, ?
            )
        ";

        $stmt = $conn->prepare($insert_sql);
        $recorded_by = $_SESSION['user_id'];

        $stmt->bind_param(
            "iissii d s i d d d d i s s i",
            $patient_id,
            $visit_id,
            $blood_pressure,
            $systolic_bp,
            $diastolic_bp,
            $pulse_rate,
            $temperature,
            $temperature_route,
            $respiratory_rate,
            $oxygen_saturation,
            $weight,
            $height,
            $bmi,
            $pain_scale,
            $consciousness,
            $notes,
            $recorded_by
        );

        if ($stmt->execute()) {

            $vital_id = $stmt->insert_id;

            // Audit log
            $log_sql = "
                INSERT INTO activity_log (
                    user_id,
                    action,
                    module,
                    record_id,
                    record_type,
                    ip_address,
                    user_agent
                ) VALUES (?, 'RECORD_VITALS', 'VITALS', ?, 'VITAL_SIGNS', ?, ?)
            ";

            $log_stmt = $conn->prepare($log_sql);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
            $agent = $_SERVER['HTTP_USER_AGENT'] ?? 'UNKNOWN';
            $log_stmt->bind_param("iiss", $recorded_by, $vital_id, $ip, $agent);
            $log_stmt->execute();

            $_SESSION['success_message'] = "Vital signs recorded successfully.";
            header("Location: patient_vitals.php?visit_id={$visit_id}&patient_id={$patient_id}");
            exit();

        } else {
            $error_message = "Failed to save vitals. Please try again.";
        }
    }
}

/*
|--------------------------------------------------------------------------
| FETCH RECENT VITALS
|--------------------------------------------------------------------------
*/
$vitals_sql = "
    SELECT 
        vs.*,
        CONCAT(u.first_name, ' ', u.last_name) AS recorded_by_name
    FROM vital_signs vs
    LEFT JOIN users u ON vs.recorded_by = u.user_id
    WHERE vs.patient_id = ?
    ORDER BY vs.recorded_date DESC
    LIMIT 10
";

$stmt = $conn->prepare($vitals_sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$vitals_history = $stmt->get_result();
?>


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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient Vitals')); ?>
    <?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;
        }
        
        .vitals-form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .history-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .vital-input-group {
            margin-bottom: 1.5rem;
        }
        
        .vital-input-group label {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .vital-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2d7a2d;
        }
        
        .vital-label {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .vital-row {
            padding: 1rem;
            border-bottom: 1px solid #e2e8f0;
            transition: background 0.2s;
        }
        
        .vital-row:hover {
            background: #f8fafc;
        }
        
        .vital-row:last-child {
            border-bottom: none;
        }
        
        .status-normal {
            color: #10b981;
        }
        
        .status-warning {
            color: #f59e0b;
        }
        
        .status-critical {
            color: #ef4444;
        }
        
        .pain-scale {
            display: flex;
            gap: 0.5rem;
            margin-top: 0.5rem;
        }
        
        .pain-number {
            width: 40px;
            height: 40px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .pain-number:hover {
            background: #f1f5f9;
        }
        
        .pain-number.selected {
            background: #2d7a2d;
            color: white;
            border-color: #2d7a2d;
        }
    </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">Patient Vitals</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">Vitals</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>
                                        </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>

                    <!-- Vitals Recording Form -->
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="vitals-form-card">
                                <h5 class="mb-4">Record Vital Signs</h5>
                                <form method="POST" id="vitalsForm">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Blood Pressure (mmHg) *</label>
                                                <div class="row g-2">
                                                    <div class="col-6">
                                                        <input type="number" class="form-control" name="systolic_bp" 
                                                               id="systolic_bp" placeholder="Systolic" required>
                                                        <small class="text-muted">Systolic</small>
                                                    </div>
                                                    <div class="col-6">
                                                        <input type="number" class="form-control" name="diastolic_bp" 
                                                               id="diastolic_bp" placeholder="Diastolic" required>
                                                        <small class="text-muted">Diastolic</small>
                                                    </div>
                                                </div>
                                                <input type="hidden" name="blood_pressure" id="blood_pressure">
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Pulse Rate (bpm) *</label>
                                                <input type="number" class="form-control" name="pulse_rate" 
                                                       placeholder="e.g., 72" required>
                                                <small class="text-muted">Normal: 60-100 bpm</small>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Temperature (°C) *</label>
                                                <input type="number" step="0.1" class="form-control" name="temperature" 
                                                       placeholder="e.g., 36.5" required>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Temperature Route *</label>
                                                <select class="form-select" name="temperature_route" required>
                                                    <option value="ORAL">Oral</option>
                                                    <option value="AXILLARY">Axillary (Armpit)</option>
                                                    <option value="RECTAL">Rectal</option>
                                                    <option value="TYMPANIC">Tympanic (Ear)</option>
                                                    <option value="TEMPORAL">Temporal (Forehead)</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Respiratory Rate (breaths/min) *</label>
                                                <input type="number" class="form-control" name="respiratory_rate" 
                                                       placeholder="e.g., 16" required>
                                                <small class="text-muted">Normal: 12-20 breaths/min</small>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Oxygen Saturation (SpO2 %) *</label>
                                                <input type="number" step="0.01" class="form-control" name="oxygen_saturation" 
                                                       placeholder="e.g., 98.5" required>
                                                <small class="text-muted">Normal: 95-100%</small>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Weight (kg)</label>
                                                <input type="number" step="0.1" class="form-control" name="weight" 
                                                       placeholder="e.g., 70.5">
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Height (cm)</label>
                                                <input type="number" step="0.1" class="form-control" name="height" 
                                                       placeholder="e.g., 170">
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Pain Score (0-10)</label>
                                                <input type="hidden" name="pain_score" id="pain_score" value="">
                                                <div class="pain-scale" id="painScale">
                                                    <?php for($i = 0; $i <= 10; $i++): ?>
                                                        <div class="pain-number" data-value="<?php echo $i; ?>"><?php echo $i; ?></div>
                                                    <?php endfor; ?>
                                                </div>
                                                <small class="text-muted">0 = No pain, 10 = Worst pain</small>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="vital-input-group">
                                                <label>Consciousness Level *</label>
                                                <select class="form-select" name="consciousness_level" required>
                                                    <option value="ALERT">Alert</option>
                                                    <option value="DROWSY">Drowsy</option>
                                                    <option value="CONFUSED">Confused</option>
                                                    <option value="UNRESPONSIVE">Unresponsive</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="col-12">
                                            <div class="vital-input-group">
                                                <label>Notes / Observations</label>
                                                <textarea class="form-control" name="notes" rows="3" 
                                                          placeholder="Any observations or notes about the patient's condition"></textarea>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex gap-2 justify-content-end">
                                        <a href="ward_patients.php" class="btn btn-light">Cancel</a>
                                        <button type="submit" name="save_vitals" class="btn btn-success">
                                            <i class="ri-save-line me-1"></i> Save Vitals
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <!-- Vitals History -->
                        <div class="col-xl-4">
                            <div class="history-card">
                                <h5 class="mb-3">Recent Vitals</h5>
                                <div class="vitals-history">
                                    <?php if ($vitals_history->num_rows > 0): ?>
                                        <?php while($vital = $vitals_history->fetch_assoc()): ?>
                                            <div class="vital-row">
                                                <div class="d-flex justify-content-between mb-2">
                                                    <strong><?php echo date('M d, Y H:i', strtotime($vital['recorded_date'])); ?></strong>
                                                    <span class="text-muted"><?php echo htmlspecialchars($vital['recorded_by_name']); ?></span>
                                                </div>
                                                <div class="row g-2 small">
                                                    <div class="col-6">BP: <?php echo $vital['blood_pressure']; ?></div>
                                                    <div class="col-6">HR: <?php echo $vital['pulse_rate']; ?> bpm</div>
                                                    <div class="col-6">Temp: <?php echo $vital['temperature']; ?>°C</div>
                                                    <div class="col-6">SpO2: <?php echo $vital['oxygen_saturation']; ?>%</div>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <p class="text-muted">No previous vitals recorded</p>
                                    <?php endif; ?>
                                </div>
                            </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>
        $(document).ready(function() {
            // Pain scale selection
            $('.pain-number').click(function() {
                $('.pain-number').removeClass('selected');
                $(this).addClass('selected');
                $('#pain_score').val($(this).data('value'));
            });
            
            // Combine BP values
            $('#systolic_bp, #diastolic_bp').on('input', function() {
                const systolic = $('#systolic_bp').val();
                const diastolic = $('#diastolic_bp').val();
                if (systolic && diastolic) {
                    $('#blood_pressure').val(systolic + '/' + diastolic);
                }
            });
            
            // Form validation
            $('#vitalsForm').on('submit', function(e) {
                const systolic = parseInt($('#systolic_bp').val());
                const diastolic = parseInt($('#diastolic_bp').val());
                
                if (systolic <= diastolic) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid Blood Pressure',
                        text: 'Systolic pressure must be greater than diastolic pressure'
                    });
                    return false;
                }
            });
        });
    </script>
</body>
</html>