<?php
/**
 * View Lab Order Page
 * Display detailed information about a lab order including all tests
 */

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) {
    header('Location: list_lab_orders.php');
    exit();
}

// 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.phone_secondary,
    u.email,
    u.address,
    ordered_user.full_name as ordered_by_name,
    ordered_user.email as ordered_by_email,
    pv.visit_id,
    pv.registration_type,
    pv.smart_session_id,
    inv.invoice_id,
    inv.invoice_number,
    inv.total_amount as invoice_total,
    inv.status as invoice_status,
    inv.amount_paid as invoice_amount_paid,
    inv.balance as invoice_balance
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
LEFT JOIN invoices inv ON lo.invoice_id = inv.invoice_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.order_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, lot.result_files,
    lot.tested_by, lot.verified_by, lot.created_at,
    ett.test_name, ett.test_code, ett.category, ett.normal_range, ett.sample_type,
    ett.description as test_description, ett.cost as test_base_cost,
    ett.turnaround_time_hours,
    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, lot.created_at";

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

// Calculate order statistics
$total_tests = $tests_result->num_rows;
$completed_tests = 0;
$pending_tests = 0;
$in_progress_tests = 0;
$total_cost = 0;

$tests = [];
while ($test = $tests_result->fetch_assoc()) {
    $tests[] = $test;
    $total_cost += floatval($test['test_cost']);
    
    if ($test['status'] == 'COMPLETED') {
        $completed_tests++;
    } elseif ($test['status'] == 'PENDING' || $test['status'] == 'SCHEDULED') {
        $pending_tests++;
    } elseif ($test['status'] == 'IN_PROGRESS') {
        $in_progress_tests++;
    }
}

$page_title = "Lab Order - " . htmlspecialchars($order['order_number']);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .order-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 12px;
            margin-bottom: 2rem;
        }
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
            border: 1px solid #e2e8f0;
        }
        .info-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        .info-row:last-child {
            border-bottom: none;
        }
        .info-label {
            font-weight: 600;
            color: #64748b;
            min-width: 150px;
        }
        .info-value {
            color: #1e293b;
            flex: 1;
            text-align: right;
        }
        .test-item {
            background: #f8fafc;
            border-left: 4px solid #3b82f6;
            padding: 1rem;
            margin-bottom: 0.75rem;
            border-radius: 8px;
        }
        .test-item.completed {
            border-left-color: #10b981;
        }
        .test-item.in-progress {
            border-left-color: #f59e0b;
        }
        .test-item.pending {
            border-left-color: #64748b;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <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"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_lab_orders.php">Lab Orders</a></li>
                                        <li class="breadcrumb-item active">View Order</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Order Header -->
                    <div class="order-header">
                        <div class="d-flex justify-content-between align-items-start flex-wrap">
                            <div>
                                <h2 class="text-white mb-2">Lab Order #<?php echo htmlspecialchars($order['order_number']); ?></h2>
                                <div class="d-flex flex-wrap align-items-center gap-3">
                                    <span class="badge bg-<?php 
                                        echo $order['status'] == 'COMPLETED' ? 'success' : 
                                            ($order['status'] == 'IN_PROGRESS' ? 'warning' : 'info'); 
                                    ?> fs-6">
                                        <?php echo htmlspecialchars($order['status']); ?>
                                    </span>
                                    <span class="badge bg-<?php 
                                        echo $order['priority'] == 'STAT' ? 'danger' : 
                                            ($order['priority'] == 'URGENT' ? 'warning' : 'secondary'); 
                                    ?> fs-6">
                                        <?php echo htmlspecialchars($order['priority']); ?> Priority
                                    </span>
                                    <?php if ($order['invoice_status']): ?>
                                    <span class="badge bg-<?php 
                                        echo $order['invoice_status'] == 'PAID' ? 'success' : 
                                            ($order['invoice_status'] == 'PARTIAL_PAYMENT' ? 'warning' : 'info'); 
                                    ?> fs-6">
                                        Status: <?php echo htmlspecialchars($order['invoice_status']); ?>
                                    </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="text-end">
                                <a href="print_lab_order.php?order_id=<?php echo $order_id; ?>" target="_blank" class="btn btn-light me-2">
                                    <i class="ri-printer-line me-1"></i> Print
                                </a>
                                <a href="list_lab_orders.php" class="btn btn-light">
                                    <i class="ri-arrow-left-line me-1"></i> Back
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="info-card text-center">
                                <h3 class="mb-1" style="color: #3b82f6;"><?php echo $total_tests; ?></h3>
                                <p class="text-muted mb-0">Total Tests</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="info-card text-center">
                                <h3 class="mb-1" style="color: #10b981;"><?php echo $completed_tests; ?></h3>
                                <p class="text-muted mb-0">Completed</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="info-card text-center">
                                <h3 class="mb-1" style="color: #f59e0b;"><?php echo $in_progress_tests; ?></h3>
                                <p class="text-muted mb-0">In Progress</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="info-card text-center">
                                <h3 class="mb-1" style="color: #64748b;"><?php echo $pending_tests; ?></h3>
                                <p class="text-muted mb-0">Pending</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <!-- Patient Information -->
                        <div class="col-xl-6 mb-4">
                            <div class="info-card">
                                <h5><i class="ri-user-line me-2"></i>Patient Information</h5>
                                <div class="info-row">
                                    <span class="info-label">Name:</span>
                                    <span class="info-value"><strong><?php echo htmlspecialchars($order['patient_name']); ?></strong></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Patient Number:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($order['patient_number']); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Age / Gender:</span>
                                    <span class="info-value"><?php echo $age !== null ? $age . ' years' : 'N/A'; ?> / <?php echo htmlspecialchars($order['gender'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Phone:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($order['phone_primary'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Email:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($order['email'] ?? 'N/A'); ?></span>
                                </div>
                                <?php if ($order['address']): ?>
                                <div class="info-row">
                                    <span class="info-label">Address:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($order['address']); ?></span>
                                </div>
                                <?php endif; ?>
                                <?php if ($order['smart_session_id']): ?>
                                <div class="info-row">
                                    <span class="info-label">Insurance:</span>
                                    <span class="info-value">
                                        <span class="badge bg-primary">SMART Enabled</span>
                                        <small class="text-muted d-block">Session: <?php echo htmlspecialchars($order['smart_session_id']); ?></small>
                                    </span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Order Information -->
                        <div class="col-xl-6 mb-4">
                            <div class="info-card">
                                <h5><i class="ri-file-list-3-line me-2"></i>Order Information</h5>
                                <div class="info-row">
                                    <span class="info-label">Order Number:</span>
                                    <span class="info-value"><strong><?php echo htmlspecialchars($order['order_number']); ?></strong></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Order Date:</span>
                                    <span class="info-value"><?php echo date('M d, Y H:i', strtotime($order['ordered_at'])); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Ordered By:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($order['ordered_by_name']); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Priority:</span>
                                    <span class="info-value">
                                        <span class="badge bg-<?php 
                                            echo $order['priority'] == 'STAT' ? 'danger' : 
                                                ($order['priority'] == 'URGENT' ? 'warning' : 'secondary'); 
                                        ?>">
                                            <?php echo htmlspecialchars($order['priority']); ?>
                                        </span>
                                    </span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Total Cost:</span>
                                    <span class="info-value"><strong>KES <?php echo number_format($order['total_cost'] ?? $total_cost, 2); ?></strong></span>
                                </div>
                                <?php if ($order['invoice_number']): ?>
                                <div class="info-row">
                                    <span class="info-label">Invoice:</span>
                                    <span class="info-value">
                                        <a href="view_invoice.php?id=<?php echo $order['invoice_id']; ?>" class="text-primary">
                                            <?php echo htmlspecialchars($order['invoice_number']); ?>
                                        </a>
                                        <span class="badge bg-<?php 
                                            echo $order['invoice_status'] == 'PAID' ? 'success' : 
                                                ($order['invoice_status'] == 'PARTIAL_PAYMENT' ? 'warning' : 'info'); 
                                        ?> ms-2">
                                            <?php echo htmlspecialchars($order['invoice_status']); ?>
                                        </span>
                                        <?php if ($order['invoice_balance'] > 0): ?>
                                            <small class="text-muted d-block mt-1">
                                                Balance: KES <?php echo number_format($order['invoice_balance'], 2); ?>
                                            </small>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Clinical Notes -->
                    <?php if ($order['clinical_notes']): ?>
                    <div class="info-card">
                        <h5><i class="ri-file-text-line me-2"></i>Clinical Notes</h5>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($order['clinical_notes'])); ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Tests List -->
                    <div class="info-card">
                        <h5><i class="ri-test-tube-line me-2"></i>Tests in This Order (<?php echo $total_tests; ?>)</h5>
                        
                        <?php if (!empty($tests)): ?>
                            <?php 
                            $current_category = '';
                            foreach ($tests as $test): 
                                if ($current_category != $test['category']) {
                                    if ($current_category != '') echo '</div>';
                                    $current_category = $test['category'];
                                    echo '<h6 class="mt-3 mb-2 text-primary"><i class="ri-folder-line me-1"></i>' . str_replace('_', ' ', $current_category) . '</h6>';
                                    echo '<div class="category-tests">';
                                }
                                
                                $test_class = 'pending';
                                if ($test['status'] == 'COMPLETED') {
                                    $test_class = 'completed';
                                } elseif ($test['status'] == 'IN_PROGRESS') {
                                    $test_class = 'in-progress';
                                }
                            ?>
                            <div class="test-item <?php echo $test_class; ?>">
                                <div class="d-flex justify-content-between align-items-start flex-wrap">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1">
                                            <?php echo htmlspecialchars($test['test_name']); ?>
                                            <small class="text-muted">(<?php echo htmlspecialchars($test['test_code']); ?>)</small>
                                        </h6>
                                        <div class="d-flex flex-wrap gap-3 mt-2">
                                            <small class="text-muted">
                                                <i class="ri-money-dollar-circle-line me-1"></i>
                                                Cost: KES <?php echo number_format($test['test_cost'], 2); ?>
                                            </small>
                                            <?php if ($test['sample_type']): ?>
                                            <small class="text-muted">
                                                <i class="ri-drop-line me-1"></i>
                                                Sample: <?php echo htmlspecialchars($test['sample_type']); ?>
                                            </small>
                                            <?php endif; ?>
                                            <?php if ($test['turnaround_time_hours']): ?>
                                            <small class="text-muted">
                                                <i class="ri-time-line me-1"></i>
                                                Turnaround: <?php echo $test['turnaround_time_hours']; ?> hours
                                            </small>
                                            <?php endif; ?>
                                        </div>
                                        <?php if ($test['status'] == 'COMPLETED' && $test['result_value']): ?>
                                        <div class="mt-2 p-2 bg-white rounded">
                                            <small class="text-muted d-block">Result:</small>
                                            <strong><?php echo htmlspecialchars($test['result_value']); ?></strong>
                                            <?php if ($test['result_unit']): ?>
                                                <small><?php echo htmlspecialchars($test['result_unit']); ?></small>
                                            <?php endif; ?>
                                            <?php if ($test['abnormal_flag'] && $test['abnormal_flag'] != 'NORMAL'): ?>
                                                <span class="badge bg-<?php echo $test['abnormal_flag'] == 'CRITICAL' ? 'danger' : 'warning'; ?> ms-2">
                                                    <?php echo htmlspecialchars($test['abnormal_flag']); ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="text-end">
                                        <span class="badge bg-<?php 
                                            echo $test['status'] == 'COMPLETED' ? 'success' : 
                                                ($test['status'] == 'IN_PROGRESS' ? 'warning' : 'secondary'); 
                                        ?>">
                                            <?php echo htmlspecialchars($test['status']); ?>
                                        </span>
                                        <div class="mt-2">
                                            <?php if ($test['status'] == 'COMPLETED'): ?>
                                                <a href="view_test_results.php?test_id=<?php echo $test['order_test_id']; ?>" 
                                                   class="btn btn-sm btn-primary">
                                                    <i class="ri-eye-line me-1"></i> View Results
                                                </a>
                                            <?php elseif ($test['status'] == 'IN_PROGRESS'): ?>
                                                <a href="test_results_entry.php?test_id=<?php echo $test['order_test_id']; ?>" 
                                                   class="btn btn-sm btn-warning">
                                                    <i class="ri-edit-line me-1"></i> Enter Results
                                                </a>
                                            <?php else: ?>
                                                <a href="pending_lab_tests.php" class="btn btn-sm btn-secondary">
                                                    <i class="ri-time-line me-1"></i> Pending
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                        <?php if ($test['technician_name']): ?>
                                        <small class="text-muted d-block mt-1">
                                            By: <?php echo htmlspecialchars($test['technician_name']); ?>
                                        </small>
                                        <?php endif; ?>
                                        <?php if ($test['completed_at']): ?>
                                        <small class="text-muted d-block">
                                            <?php echo date('M d, Y H:i', strtotime($test['completed_at'])); ?>
                                        </small>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php 
                            endforeach; 
                            if ($current_category != '') echo '</div>';
                            ?>
                        <?php else: ?>
                            <div class="alert alert-info">
                                <i class="ri-information-line me-2"></i>
                                No tests found in this order.
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="row">
                        <div class="col-12">
                            <div class="d-flex gap-2">
                                <a href="list_lab_orders.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-1"></i> Back to Orders
                                </a>
                                <a href="print_lab_order.php?order_id=<?php echo $order_id; ?>" target="_blank" class="btn btn-primary">
                                    <i class="ri-printer-line me-1"></i> Print Order
                                </a>
                                <?php if ($order['status'] != 'COMPLETED'): ?>
                                <a href="edit_lab_order.php?order_id=<?php echo $order_id; ?>" class="btn btn-warning">
                                    <i class="ri-edit-line me-1"></i> Edit Order
                                </a>
                                <?php endif; ?>
                            </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="assets/js/app.js"></script>
</body>
</html>
