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

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

$user_id = $_SESSION['user_id'];

// Get order ID
$order_id = isset($_GET['order']) ? intval($_GET['order']) : 0;

if (!$order_id) {
    header('Location: list_lab_orders.php');
    exit();
}

// Fetch order details
$order_sql = "SELECT 
    lo.*,
    p.patient_id,
    p.patient_number,
    p.full_name as patient_name,
    p.date_of_birth,
    p.gender,
    p.phone_primary,
    p.email,
    p.address,
    u.full_name as ordered_by_name,
    pv.registration_type,
    pv.smart_session_id
FROM lab_orders lo
JOIN patients p ON lo.patient_id = p.patient_id
JOIN users u ON lo.ordered_by = u.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("Order not found");
}

// Fetch all tests in this order
$tests_sql = "SELECT 
    lot.*,
    ett.test_name,
    ett.test_code,
    ett.category,
    ett.normal_range,
    u1.full_name as tested_by_name,
    u2.full_name as verified_by_name
FROM lab_order_tests lot
JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
LEFT JOIN users u1 ON lot.tested_by = u1.user_id
LEFT JOIN users u2 ON lot.verified_by = u2.user_id
WHERE lot.order_id = ?
ORDER BY ett.category, ett.test_name";

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

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

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Lab Report')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        @media print {
            .no-print { display: none !important; }
            body { margin: 0; padding: 20px; }
            .page-content { margin: 0; }
        }
        
        .report-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 12px;
            margin-bottom: 2rem;
        }
        
        .report-section {
            border: 2px solid #e9ecef;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            page-break-inside: avoid;
        }
        
        .test-result-card {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 1.5rem;
            margin-bottom: 1rem;
            border-radius: 8px;
        }
        
        .test-result-card.abnormal {
            border-left-color: #ffc107;
            background: #fff3cd;
        }
        
        .test-result-card.critical {
            border-left-color: #dc3545;
            background: #f8d7da;
        }
        
        .result-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #667eea;
        }
        
        .result-value.abnormal {
            color: #ffc107;
        }
        
        .result-value.critical {
            color: #dc3545;
        }
        
        .hospital-logo {
            max-height: 80px;
        }
        
        .signature-section {
            margin-top: 3rem;
            border-top: 1px solid #dee2e6;
            padding-top: 2rem;
        }
    </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 (No Print) -->
                    <div class="row no-print">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">
                                    <i class="ri-file-list-3-line me-2"></i>Laboratory Report
                                </h4>
                                <div class="page-title-right">
                                    <button onclick="window.print()" class="btn btn-primary me-2">
                                        <i class="ri-printer-line me-1"></i>Print Report
                                    </button>
                                    <button onclick="downloadPDF()" class="btn btn-success me-2">
                                        <i class="ri-file-pdf-line me-1"></i>Download PDF
                                    </button>
                                    <button onclick="emailReport()" class="btn btn-info">
                                        <i class="ri-mail-line me-1"></i>Email Report
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Report Content -->
                    <div class="card" id="reportContent">
                        <div class="card-body">
                            <!-- Hospital Header -->
                            <div class="report-header">
                                <div class="row align-items-center">
                                    <div class="col-md-2">
                                        <!-- Add hospital logo here -->
                                        <div class="bg-white p-3 rounded text-center">
                                            <h4 class="text-primary mb-0">ENT</h4>
                                            <small class="text-muted">Hospital</small>
                                        </div>
                                    </div>
                                    <div class="col-md-7">
                                        <h2 class="mb-1">ENT HOSPITAL & WELLNESS CENTER</h2>
                                        <p class="mb-1">Comprehensive Ear, Nose & Throat Care</p>
                                        <p class="mb-0">
                                            <i class="ri-phone-line me-2"></i>+254 700 000 000 |
                                            <i class="ri-mail-line me-2"></i>info@enthospital.co.ke |
                                            <i class="ri-map-pin-line me-2"></i>Nairobi, Kenya
                                        </p>
                                    </div>
                                    <div class="col-md-3 text-end">
                                        <h5 class="mb-1">LABORATORY REPORT</h5>
                                        <p class="mb-0 opacity-90">
                                            Date: <?php echo date('d M Y'); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <!-- Patient & Order Information -->
                            <div class="row mb-4">
                                <div class="col-md-6">
                                    <div class="report-section">
                                        <div class="card-header bg-light">
                                            <h6 class="mb-0"><i class="ri-user-line me-2"></i>Patient Information</h6>
                                        </div>
                                        <div class="card-body">
                                            <table class="table table-sm table-borderless mb-0">
                                                <tr>
                                                    <td width="40%"><strong>Name:</strong></td>
                                                    <td><?php echo htmlspecialchars($order['patient_name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Patient #:</strong></td>
                                                    <td><?php echo $order['patient_number']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Age/Gender:</strong></td>
                                                    <td><?php echo $age; ?> years / <?php echo $order['gender']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Phone:</strong></td>
                                                    <td><?php echo $order['phone_primary']; ?></td>
                                                </tr>
                                                <?php if ($order['smart_session_id']): ?>
                                                <tr>
                                                    <td><strong>Insurance:</strong></td>
                                                    <td>
                                                        <span class="badge bg-primary">SMART Enabled</span>
                                                    </td>
                                                </tr>
                                                <?php endif; ?>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="report-section">
                                        <div class="card-header bg-light">
                                            <h6 class="mb-0"><i class="ri-file-list-3-line me-2"></i>Order Information</h6>
                                        </div>
                                        <div class="card-body">
                                            <table class="table table-sm table-borderless mb-0">
                                                <tr>
                                                    <td width="40%"><strong>Order #:</strong></td>
                                                    <td><?php echo $order['order_number']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Order Date:</strong></td>
                                                    <td><?php echo date('d M Y, h:i A', strtotime($order['ordered_at'])); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Ordered By:</strong></td>
                                                    <td><?php echo htmlspecialchars($order['ordered_by_name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Priority:</strong></td>
                                                    <td>
                                                        <span class="badge <?php 
                                                            echo ($order['priority'] == 'STAT') ? 'bg-danger' : 
                                                                 (($order['priority'] == 'URGENT') ? 'bg-warning' : 'bg-info'); 
                                                        ?>">
                                                            <?php echo $order['priority']; ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Report Date:</strong></td>
                                                    <td><?php echo date('d M Y'); ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Clinical Notes -->
                            <?php if ($order['clinical_notes']): ?>
                            <div class="report-section">
                                <div class="card-header bg-light">
                                    <h6 class="mb-0"><i class="ri-file-text-line me-2"></i>Clinical Notes</h6>
                                </div>
                                <div class="card-body">
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($order['clinical_notes'])); ?></p>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Test Results -->
                            <div class="report-section">
                                <div class="card-header bg-primary text-white">
                                    <h5 class="mb-0"><i class="ri-test-tube-line me-2"></i>Laboratory Test Results</h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($tests->num_rows > 0): ?>
                                        <?php 
                                        $current_category = '';
                                        while($test = $tests->fetch_assoc()): 
                                            if ($current_category != $test['category']) {
                                                if ($current_category != '') echo '</div>';
                                                $current_category = $test['category'];
                                                echo '<h6 class="mt-3 mb-3 text-primary">' . str_replace('_', ' ', $current_category) . '</h6>';
                                                echo '<div class="category-tests">';
                                            }
                                            
                                            $card_class = '';
                                            $value_class = '';
                                            if ($test['abnormal_flag'] == 'CRITICAL') {
                                                $card_class = 'critical';
                                                $value_class = 'critical';
                                            } elseif ($test['abnormal_flag'] != 'NORMAL') {
                                                $card_class = 'abnormal';
                                                $value_class = 'abnormal';
                                            }
                                        ?>
                                        
                                        <div class="test-result-card <?php echo $card_class; ?>">
                                            <div class="row align-items-start">
                                                <div class="col-md-4">
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($test['test_name']); ?></h6>
                                                    <small class="text-muted"><?php echo $test['test_code']; ?></small>
                                                </div>
                                                <div class="col-md-3">
                                                    <small class="text-muted d-block">Result:</small>
                                                    <div class="result-value <?php echo $value_class; ?>">
                                                        <?php 
                                                        // Handle display of result value
                                                        if (strlen($test['result_value']) > 50) {
                                                            echo substr($test['result_value'], 0, 50) . '...';
                                                        } else {
                                                            echo $test['result_value']; 
                                                        }
                                                        ?>
                                                        <?php if ($test['result_unit']): ?>
                                                            <small><?php echo $test['result_unit']; ?></small>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <?php if ($test['normal_range']): ?>
                                                        <small class="text-muted d-block">Reference Range:</small>
                                                        <div><strong><?php echo $test['normal_range']; ?></strong></div>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="col-md-2 text-end">
                                                    <span class="badge <?php 
                                                        echo ($test['abnormal_flag'] == 'NORMAL') ? 'bg-success' : 
                                                             (($test['abnormal_flag'] == 'CRITICAL') ? 'bg-danger' : 'bg-warning'); 
                                                    ?>">
                                                        <?php echo $test['abnormal_flag']; ?>
                                                    </span>
                                                </div>
                                            </div>
                                            
                                            <?php if ($test['interpretation']): ?>
                                                <hr class="my-2">
                                                <div class="mt-2">
                                                    <strong class="text-muted">Interpretation:</strong>
                                                    <p class="mb-0 mt-1"><?php echo nl2br(htmlspecialchars($test['interpretation'])); ?></p>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($test['result_files']): ?>
                                                <?php $files = json_decode($test['result_files'], true); ?>
                                                <hr class="my-2">
                                                <div class="mt-2">
                                                    <strong class="text-muted">Attachments:</strong>
                                                    <div class="no-print">
                                                        <?php foreach ($files as $file): ?>
                                                            <a href="<?php echo $file['path']; ?>" target="_blank" class="btn btn-sm btn-outline-primary me-2 mt-2">
                                                                <i class="ri-attachment-2 me-1"></i><?php echo $file['filename']; ?>
                                                            </a>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <div class="mt-3 pt-2 border-top">
                                                <small class="text-muted">
                                                    <strong>Performed by:</strong> <?php echo $test['tested_by_name'] ?? 'N/A'; ?> | 
                                                    <strong>Date:</strong> <?php echo date('d M Y, h:i A', strtotime($test['completed_at'])); ?>
                                                    <?php if ($test['verified_by_name']): ?>
                                                        | <strong>Verified by:</strong> <?php echo $test['verified_by_name']; ?>
                                                    <?php endif; ?>
                                                </small>
                                            </div>
                                        </div>
                                        
                                        <?php 
                                        endwhile; 
                                        if ($current_category != '') echo '</div>';
                                        ?>
                                    <?php else: ?>
                                        <p class="text-center text-muted py-4">No test results available</p>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Signature Section -->
                            <div class="signature-section">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="text-center">
                                            <div style="height: 60px;"></div>
                                            <div class="border-top d-inline-block px-5 pt-2">
                                                <strong>Lab Technician Signature</strong>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="text-center">
                                            <div style="height: 60px;"></div>
                                            <div class="border-top d-inline-block px-5 pt-2">
                                                <strong>Medical Officer Signature</strong>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Footer -->
                            <div class="text-center mt-4 pt-3 border-top">
                                <p class="text-muted mb-1">
                                    <small>
                                        This is a computer-generated report. For any queries, please contact the laboratory.
                                    </small>
                                </p>
                                <p class="text-muted mb-0">
                                    <small>
                                        ENT Hospital & Wellness Center | Tel: +254 700 000 000 | Email: lab@enthospital.co.ke
                                    </small>
                                </p>
                            </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 src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

    <script>
        function downloadPDF() {
            const element = document.getElementById('reportContent');
            const opt = {
                margin: 10,
                filename: 'Lab_Report_<?php echo $order['order_number']; ?>.pdf',
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2 },
                jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
            };
            
            Swal.fire({
                title: 'Generating PDF...',
                text: 'Please wait',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            html2pdf().set(opt).from(element).save().then(() => {
                Swal.close();
                Swal.fire('Success', 'PDF downloaded successfully', 'success');
            });
        }

        function emailReport() {
            Swal.fire({
                title: 'Email Report',
                html: `
                    <div class="mb-3">
                        <label class="form-label">Email Address</label>
                        <input type="email" id="emailAddress" class="form-control" 
                               value="<?php echo $order['email'] ?? ''; ?>" placeholder="Enter email address">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Message (Optional)</label>
                        <textarea id="emailMessage" class="form-control" rows="3" 
                                  placeholder="Add a personal message..."></textarea>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Send Email',
                preConfirm: () => {
                    const email = document.getElementById('emailAddress').value;
                    if (!email) {
                        Swal.showValidationMessage('Please enter an email address');
                        return false;
                    }
                    return {
                        email: email,
                        message: document.getElementById('emailMessage').value
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/email_lab_report.php',
                        type: 'POST',
                        data: {
                            order_id: <?php echo $order_id; ?>,
                            email: result.value.email,
                            message: result.value.message
                        },
                        success: function(response) {
                            const data = JSON.parse(response);
                            if (data.success) {
                                Swal.fire('Sent!', 'Report has been emailed successfully', 'success');
                            } else {
                                Swal.fire('Error', data.message, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Failed to send email', 'error');
                        }
                    });
                }
            });
        }
    </script>
</body>
</html>