<?php
/**
 * Print Lab Order Page
 * Print-friendly version of lab order details
 */

session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : (isset($_GET['id']) ? intval($_GET['id']) : 0);

if (!$order_id) {
    die("Order ID required");
}

// Fetch order details
$order_sql = "SELECT 
    lo.*,
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.gender,
    u.date_of_birth,
    u.phone_primary,
    u.email,
    u.address,
    ordered_user.full_name as ordered_by_name,
    pv.registration_type,
    pv.smart_session_id
FROM lab_orders lo
INNER JOIN patients p ON lo.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
INNER JOIN users ordered_user ON lo.ordered_by = ordered_user.user_id
LEFT JOIN patient_visits pv ON lo.visit_id = pv.visit_id
WHERE lo.order_id = ?";

$stmt = $conn->prepare($order_sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();

if (!$order) {
    die("Lab order not found");
}

// Calculate patient age
$age = null;
if ($order['date_of_birth']) {
    $dob = new DateTime($order['date_of_birth']);
    $now = new DateTime();
    $age = $now->diff($dob)->y;
}

// Fetch all tests in this order
$tests_sql = "SELECT 
    lot.order_test_id, lot.test_type_id, lot.test_cost, lot.status,
    lot.scheduled_at, lot.started_at, lot.completed_at, lot.result_value, lot.result_unit,
    lot.reference_range, lot.interpretation, lot.abnormal_flag,
    ett.test_name, ett.test_code, ett.category, ett.normal_range, ett.sample_type,
    ett.description as test_description,
    tech_user.full_name as technician_name,
    ver_user.full_name as verified_by_name
FROM lab_order_tests lot
INNER JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
LEFT JOIN users tech_user ON lot.tested_by = tech_user.user_id
LEFT JOIN users ver_user ON lot.verified_by = ver_user.user_id
WHERE lot.order_id = ?
ORDER BY ett.category, ett.test_name";

$stmt = $conn->prepare($tests_sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$tests_result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lab Order - <?php echo htmlspecialchars($order['order_number']); ?></title>
    <style>
        @media print {
            body { margin: 0; padding: 20px; }
            .no-print { display: none !important; }
            .page-break { page-break-after: always; }
        }
        
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            line-height: 1.6;
            color: #333;
        }
        
        .print-header {
            border-bottom: 3px solid #333;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        
        .hospital-name {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .hospital-details {
            font-size: 11px;
            color: #666;
        }
        
        .order-title {
            font-size: 18px;
            font-weight: bold;
            margin: 20px 0;
            text-align: center;
        }
        
        .info-section {
            margin-bottom: 20px;
            border: 1px solid #ddd;
            padding: 15px;
        }
        
        .info-section h4 {
            font-size: 14px;
            margin: 0 0 10px 0;
            padding-bottom: 5px;
            border-bottom: 1px solid #ddd;
        }
        
        .info-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .info-table td {
            padding: 5px 10px;
            border-bottom: 1px solid #eee;
        }
        
        .info-table td:first-child {
            font-weight: bold;
            width: 30%;
        }
        
        .tests-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        
        .tests-table th {
            background: #f5f5f5;
            padding: 8px;
            text-align: left;
            border: 1px solid #ddd;
            font-size: 11px;
        }
        
        .tests-table td {
            padding: 8px;
            border: 1px solid #ddd;
            font-size: 11px;
        }
        
        .footer {
            margin-top: 30px;
            padding-top: 15px;
            border-top: 2px solid #333;
            text-align: center;
            font-size: 10px;
            color: #666;
        }
        
        .signature-section {
            margin-top: 40px;
            display: flex;
            justify-content: space-around;
        }
        
        .signature-box {
            text-align: center;
            width: 200px;
        }
        
        .signature-line {
            border-top: 1px solid #333;
            margin-top: 50px;
            padding-top: 5px;
        }
        
        .badge {
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
        }
        
        .badge-success { background: #d4edda; color: #155724; }
        .badge-warning { background: #fff3cd; color: #856404; }
        .badge-danger { background: #f8d7da; color: #721c24; }
        .badge-info { background: #d1ecf1; color: #0c5460; }
        .badge-secondary { background: #e2e3e5; color: #383d41; }
    </style>
</head>
<body>
    <div class="no-print" style="text-align: center; padding: 20px; background: #f5f5f5; margin-bottom: 20px;">
        <button onclick="window.print()" style="padding: 10px 20px; font-size: 16px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;">
            <i class="ri-printer-line"></i> Print Order
        </button>
        <button onclick="window.close()" style="padding: 10px 20px; font-size: 16px; background: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer; margin-left: 10px;">
            Close
        </button>
    </div>
    
    <div class="print-header">
        <div class="hospital-name">ENT HOSPITAL & WELLNESS CENTER</div>
        <div class="hospital-details">
            Comprehensive Ear, Nose & Throat Care<br>
            Tel: +254 700 000 000 | Email: info@enthospital.co.ke | Nairobi, Kenya
        </div>
    </div>
    
    <div class="order-title">LABORATORY ORDER</div>
    
    <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
        <div class="info-section" style="width: 48%;">
            <h4>Patient Information</h4>
            <table class="info-table">
                <tr>
                    <td>Name:</td>
                    <td><?php echo htmlspecialchars($order['patient_name']); ?></td>
                </tr>
                <tr>
                    <td>Patient Number:</td>
                    <td><?php echo htmlspecialchars($order['patient_number']); ?></td>
                </tr>
                <tr>
                    <td>Age / Gender:</td>
                    <td><?php echo $age !== null ? $age . ' years' : 'N/A'; ?> / <?php echo htmlspecialchars($order['gender'] ?? 'N/A'); ?></td>
                </tr>
                <tr>
                    <td>Phone:</td>
                    <td><?php echo htmlspecialchars($order['phone_primary'] ?? 'N/A'); ?></td>
                </tr>
                <tr>
                    <td>Email:</td>
                    <td><?php echo htmlspecialchars($order['email'] ?? 'N/A'); ?></td>
                </tr>
                <?php if ($order['address']): ?>
                <tr>
                    <td>Address:</td>
                    <td><?php echo htmlspecialchars($order['address']); ?></td>
                </tr>
                <?php endif; ?>
                <?php if ($order['smart_session_id']): ?>
                <tr>
                    <td>Insurance:</td>
                    <td>SMART Enabled (Session: <?php echo htmlspecialchars($order['smart_session_id']); ?>)</td>
                </tr>
                <?php endif; ?>
            </table>
        </div>
        
        <div class="info-section" style="width: 48%;">
            <h4>Order Information</h4>
            <table class="info-table">
                <tr>
                    <td>Order Number:</td>
                    <td><strong><?php echo htmlspecialchars($order['order_number']); ?></strong></td>
                </tr>
                <tr>
                    <td>Order Date:</td>
                    <td><?php echo date('d M Y, h:i A', strtotime($order['ordered_at'])); ?></td>
                </tr>
                <tr>
                    <td>Ordered By:</td>
                    <td><?php echo htmlspecialchars($order['ordered_by_name']); ?></td>
                </tr>
                <tr>
                    <td>Priority:</td>
                    <td>
                        <span class="badge badge-<?php 
                            echo $order['priority'] == 'STAT' ? 'danger' : 
                                ($order['priority'] == 'URGENT' ? 'warning' : 'secondary'); 
                        ?>">
                            <?php echo htmlspecialchars($order['priority']); ?>
                        </span>
                    </td>
                </tr>
                <tr>
                    <td>Status:</td>
                    <td>
                        <span class="badge badge-<?php 
                            echo $order['status'] == 'COMPLETED' ? 'success' : 
                                ($order['status'] == 'IN_PROGRESS' ? 'warning' : 'info'); 
                        ?>">
                            <?php echo htmlspecialchars($order['status']); ?>
                        </span>
                    </td>
                </tr>
                <tr>
                    <td>Total Cost:</td>
                    <td><strong>KES <?php echo number_format($order['total_cost'], 2); ?></strong></td>
                </tr>
            </table>
        </div>
    </div>
    
    <?php if ($order['clinical_notes']): ?>
    <div class="info-section">
        <h4>Clinical Notes</h4>
        <p style="margin: 0;"><?php echo nl2br(htmlspecialchars($order['clinical_notes'])); ?></p>
    </div>
    <?php endif; ?>
    
    <div class="info-section">
        <h4>Tests Ordered</h4>
        <table class="tests-table">
            <thead>
                <tr>
                    <th>Test Name</th>
                    <th>Code</th>
                    <th>Category</th>
                    <th>Sample Type</th>
                    <th>Status</th>
                    <th>Cost</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($tests_result->num_rows > 0): ?>
                    <?php while($test = $tests_result->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($test['test_name']); ?></td>
                        <td><?php echo htmlspecialchars($test['test_code']); ?></td>
                        <td><?php echo htmlspecialchars(str_replace('_', ' ', $test['category'])); ?></td>
                        <td><?php echo htmlspecialchars($test['sample_type'] ?? 'N/A'); ?></td>
                        <td>
                            <span class="badge badge-<?php 
                                echo $test['status'] == 'COMPLETED' ? 'success' : 
                                    ($test['status'] == 'IN_PROGRESS' ? 'warning' : 'info'); 
                            ?>">
                                <?php echo htmlspecialchars($test['status']); ?>
                            </span>
                        </td>
                        <td>KES <?php echo number_format($test['test_cost'], 2); ?></td>
                    </tr>
                    <?php endwhile; ?>
                    <tr style="background: #f5f5f5; font-weight: bold;">
                        <td colspan="5" style="text-align: right;">Total:</td>
                        <td>KES <?php echo number_format($order['total_cost'], 2); ?></td>
                    </tr>
                <?php else: ?>
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 20px;">No tests found in this order</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <div class="signature-section">
        <div class="signature-box">
            <div class="signature-line">
                <strong>Ordered By</strong><br>
                <?php echo htmlspecialchars($order['ordered_by_name']); ?><br>
                <?php echo date('d M Y'); ?>
            </div>
        </div>
        <div class="signature-box">
            <div class="signature-line">
                <strong>Received By</strong><br>
                <br>
                Date: _______________
            </div>
        </div>
    </div>
    
    <div class="footer">
        <p><strong>ENT Hospital & Wellness Center</strong></p>
        <p>This is a computer-generated lab order. For any queries, please contact the laboratory.</p>
        <p>Printed on: <?php echo date('d M Y, h:i A'); ?></p>
    </div>
    
    <script>
        // Auto-print when page loads (optional)
        // window.onload = function() {
        //     window.print();
        // }
    </script>
</body>
</html>
