<?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 test ID
$order_test_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$order_test_id) {
    header('Location: pending_tests.php');
    exit();
}

// Fetch test details
$test_sql = "SELECT 
    lot.*,
    lo.order_number,
    lo.priority,
    lo.clinical_notes,
    p.patient_id,
    p.patient_number,
    p.full_name as patient_name,
    p.date_of_birth,
    p.gender,
    ett.test_name,
    ett.test_code,
    ett.category,
    ett.normal_range,
    ett.sample_type,
    pv.smart_session_id
FROM lab_order_tests lot
JOIN lab_orders lo ON lot.order_id = lo.order_id
JOIN patients p ON lo.patient_id = p.patient_id
JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
LEFT JOIN patient_visits pv ON lo.visit_id = pv.visit_id
WHERE lot.order_test_id = ?";

$stmt = $conn->prepare($test_sql);
$stmt->bind_param("i", $order_test_id);
$stmt->execute();
$test = $stmt->get_result()->fetch_assoc();

if (!$test) {
    die("Test not found");
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $conn->begin_transaction();
    
    try {
        $result_value = $_POST['result_value'];
        $result_unit = $_POST['result_unit'] ?? null;
        $interpretation = $_POST['interpretation'];
        $abnormal_flag = $_POST['abnormal_flag'];
        
        // Handle file uploads
        $result_files = [];
        if (isset($_FILES['result_files']) && !empty($_FILES['result_files']['name'][0])) {
            $upload_dir = 'uploads/lab_results/' . date('Y/m/');
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            foreach ($_FILES['result_files']['name'] as $key => $filename) {
                if ($_FILES['result_files']['error'][$key] == 0) {
                    $ext = pathinfo($filename, PATHINFO_EXTENSION);
                    $new_filename = uniqid() . '.' . $ext;
                    $filepath = $upload_dir . $new_filename;
                    
                    if (move_uploaded_file($_FILES['result_files']['tmp_name'][$key], $filepath)) {
                        $result_files[] = [
                            'filename' => $filename,
                            'path' => $filepath,
                            'uploaded_at' => date('Y-m-d H:i:s')
                        ];
                    }
                }
            }
        }
        
        // Update test results
        $update_sql = "UPDATE lab_order_tests SET 
            result_value = ?,
            result_unit = ?,
            interpretation = ?,
            abnormal_flag = ?,
            result_files = ?,
            tested_by = ?,
            status = 'COMPLETED',
            completed_at = NOW()
        WHERE order_test_id = ?";
        
        $files_json = json_encode($result_files);
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param(
            "sssssii",
            $result_value, $result_unit, $interpretation, $abnormal_flag,
            $files_json, $user_id, $order_test_id
        );
        $stmt->execute();
        
        // Check if all tests in the order are completed
        $check_sql = "SELECT COUNT(*) as pending 
                      FROM lab_order_tests 
                      WHERE order_id = (SELECT order_id FROM lab_order_tests WHERE order_test_id = ?) 
                      AND status != 'COMPLETED'";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param("i", $order_test_id);
        $stmt->execute();
        $pending = $stmt->get_result()->fetch_assoc()['pending'];
        
        if ($pending == 0) {
            // Update order status to completed
            $update_order_sql = "UPDATE lab_orders SET status = 'COMPLETED' WHERE order_id = ?";
            $stmt = $conn->prepare($update_order_sql);
            $order_id = $test['order_id'];
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
        }
        
        // Log activity
        $activity_sql = "INSERT INTO activity_logs (
            user_id, action, entity_type, entity_id, description
        ) VALUES (?, 'UPDATE', 'LAB_TEST_RESULT', ?, ?)";
        
        $description = "Completed test results for " . $test['test_name'] . " - Order: " . $test['order_number'];
        $stmt = $conn->prepare($activity_sql);
        $stmt->bind_param("iis", $user_id, $order_test_id, $description);
        $stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = 'Test results saved successfully!';
        header('Location: lab_reports.php?order=' . $test['order_id']);
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = 'Error saving results: ' . $e->getMessage();
    }
}

// Calculate patient age
$age = '';
if ($test['date_of_birth']) {
    $dob = new DateTime($test['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' => 'Enter Test Results')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/dropzone/dropzone.css" rel="stylesheet">
    
    <style>
        .test-header-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .result-entry-card {
            border: 2px solid #e9ecef;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .result-entry-card:hover {
            border-color: #667eea;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
        }
        
        .reference-range-box {
            background: #f8f9fa;
            border-left: 4px solid #198754;
            padding: 1rem;
            border-radius: 8px;
            margin: 1rem 0;
        }
        
        .abnormal-flag-selector {
            display: flex;
            gap: 1rem;
            margin: 1rem 0;
        }
        
        .flag-option {
            flex: 1;
            padding: 1rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            cursor: pointer;
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .flag-option input[type="radio"] {
            display: none;
        }
        
        .flag-option:hover {
            border-color: #667eea;
        }
        
        .flag-option input[type="radio"]:checked + label {
            font-weight: 600;
        }
        
        .flag-option.normal {
            border-color: #198754;
        }
        
        .flag-option.abnormal {
            border-color: #ffc107;
        }
        
        .flag-option.critical {
            border-color: #dc3545;
        }
    </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">
                                    <i class="ri-file-list-3-line me-2"></i>Enter Test Results
                                </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="pending_tests.php">Pending Tests</a></li>
                                        <li class="breadcrumb-item active">Test Results</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Test Header -->
                    <div class="test-header-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h4 class="mb-2">
                                    <i class="ri-test-tube-line me-2"></i>
                                    <?php echo htmlspecialchars($test['test_name']); ?>
                                </h4>
                                <p class="mb-1">
                                    <strong>Order:</strong> <?php echo $test['order_number']; ?> | 
                                    <strong>Test Code:</strong> <?php echo $test['test_code']; ?> |
                                    <strong>Category:</strong> <?php echo str_replace('_', ' ', $test['category']); ?>
                                </p>
                                <p class="mb-0 opacity-90">
                                    <strong>Patient:</strong> <?php echo htmlspecialchars($test['patient_name']); ?> 
                                    (<?php echo $test['patient_number']; ?>) | 
                                    <?php echo $age; ?>y, <?php echo $test['gender']; ?>
                                    <?php if ($test['smart_session_id']): ?>
                                        <span class="badge bg-light text-dark ms-2">
                                            <i class="ri-shield-check-line me-1"></i>SMART
                                        </span>
                                    <?php endif; ?>
                                </p>
                            </div>
                            <div class="col-md-4 text-end">
                                <span class="badge <?php echo ($test['priority'] == 'STAT') ? 'bg-danger' : (($test['priority'] == 'URGENT') ? 'bg-warning' : 'bg-info'); ?> px-3 py-2 fs-6">
                                    <?php echo $test['priority']; ?>
                                </span>
                            </div>
                        </div>
                    </div>

                    <form method="POST" enctype="multipart/form-data" id="resultsForm">
                        <div class="row">
                            <!-- Left Column: Results Entry -->
                            <div class="col-lg-8">
                                <div class="card result-entry-card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="ri-edit-line me-2"></i>Test Results
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <!-- Clinical Notes -->
                                        <?php if ($test['clinical_notes']): ?>
                                            <div class="alert alert-info">
                                                <strong><i class="ri-information-line me-2"></i>Clinical Notes:</strong>
                                                <p class="mb-0 mt-2"><?php echo htmlspecialchars($test['clinical_notes']); ?></p>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Reference Range -->
                                        <?php if ($test['normal_range']): ?>
                                            <div class="reference-range-box">
                                                <strong><i class="ri-star-line me-2"></i>Reference Range:</strong>
                                                <p class="mb-0 mt-1"><?php echo htmlspecialchars($test['normal_range']); ?></p>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Result Value -->
                                        <div class="mb-4">
                                            <label class="form-label">Result Value *</label>
                                            <div class="input-group">
                                                <textarea class="form-control" name="result_value" rows="4" 
                                                          required placeholder="Enter test result value"></textarea>
                                                <input type="text" class="form-control" name="result_unit" 
                                                       style="max-width: 150px;" placeholder="Unit (e.g., dB, Hz)">
                                            </div>
                                            <small class="text-muted">Enter the measured/observed value and unit if applicable</small>
                                        </div>

                                        <!-- Abnormal Flag -->
                                        <div class="mb-4">
                                            <label class="form-label">Result Classification *</label>
                                            <div class="abnormal-flag-selector">
                                                <div class="flag-option normal">
                                                    <input type="radio" name="abnormal_flag" value="NORMAL" 
                                                           id="flag_normal" required checked>
                                                    <label for="flag_normal" class="d-block">
                                                        <i class="ri-checkbox-circle-line text-success fs-3 d-block mb-2"></i>
                                                        <strong>Normal</strong>
                                                        <p class="text-muted small mb-0">Within reference range</p>
                                                    </label>
                                                </div>
                                                
                                                <div class="flag-option abnormal">
                                                    <input type="radio" name="abnormal_flag" value="HIGH" id="flag_high">
                                                    <label for="flag_high" class="d-block">
                                                        <i class="ri-arrow-up-circle-line text-warning fs-3 d-block mb-2"></i>
                                                        <strong>High</strong>
                                                        <p class="text-muted small mb-0">Above normal range</p>
                                                    </label>
                                                </div>
                                                
                                                <div class="flag-option abnormal">
                                                    <input type="radio" name="abnormal_flag" value="LOW" id="flag_low">
                                                    <label for="flag_low" class="d-block">
                                                        <i class="ri-arrow-down-circle-line text-warning fs-3 d-block mb-2"></i>
                                                        <strong>Low</strong>
                                                        <p class="text-muted small mb-0">Below normal range</p>
                                                    </label>
                                                </div>
                                                
                                                <div class="flag-option critical">
                                                    <input type="radio" name="abnormal_flag" value="CRITICAL" id="flag_critical">
                                                    <label for="flag_critical" class="d-block">
                                                        <i class="ri-alert-line text-danger fs-3 d-block mb-2"></i>
                                                        <strong>Critical</strong>
                                                        <p class="text-muted small mb-0">Requires immediate attention</p>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Interpretation -->
                                        <div class="mb-4">
                                            <label class="form-label">Clinical Interpretation *</label>
                                            <textarea class="form-control" name="interpretation" rows="6" 
                                                      required placeholder="Enter clinical interpretation and observations"></textarea>
                                            <small class="text-muted">
                                                Provide detailed interpretation of the results, clinical significance, and any recommendations
                                            </small>
                                        </div>

                                        <!-- File Uploads -->
                                        <div class="mb-4">
                                            <label class="form-label">Attach Files (Audiograms, Images, Reports)</label>
                                            <input type="file" class="form-control" name="result_files[]" 
                                                   multiple accept="image/*,.pdf">
                                            <small class="text-muted">
                                                Supported formats: JPG, PNG, PDF. Max 10MB per file.
                                            </small>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Right Column: Patient Info & Actions -->
                            <div class="col-lg-4">
                                <!-- Patient Summary -->
                                <div class="card">
                                    <div class="card-header bg-primary text-white">
                                        <h6 class="mb-0">
                                            <i class="ri-user-line me-2"></i>Patient Summary
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <p class="mb-2">
                                            <strong>Name:</strong><br>
                                            <?php echo htmlspecialchars($test['patient_name']); ?>
                                        </p>
                                        <p class="mb-2">
                                            <strong>Patient #:</strong><br>
                                            <?php echo $test['patient_number']; ?>
                                        </p>
                                        <p class="mb-2">
                                            <strong>Age/Gender:</strong><br>
                                            <?php echo $age; ?> years / <?php echo $test['gender']; ?>
                                        </p>
                                        <?php if ($test['sample_type']): ?>
                                            <p class="mb-0">
                                                <strong>Sample Type:</strong><br>
                                                <?php echo $test['sample_type']; ?>
                                            </p>
                                        <?php endif; ?>
                                        
                                        <hr>
                                        
                                        <a href="patient_profile.php?id=<?php echo $test['patient_id']; ?>" 
                                           class="btn btn-sm btn-outline-primary w-100" target="_blank">
                                            <i class="ri-external-link-line me-1"></i>View Full Profile
                                        </a>
                                    </div>
                                </div>

                                <!-- Quick AI Assist (if category is AUDIOMETRY) -->
                                <?php if ($test['category'] == 'AUDIOMETRY'): ?>
                                    <div class="card">
                                        <div class="card-header bg-info text-white">
                                            <h6 class="mb-0">
                                                <i class="ri-brain-line me-2"></i>AI Assist Available
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <p class="text-muted">AI-powered audiogram analysis is available for this test.</p>
                                            <a href="audiometry_ai_analysis.php?test_id=<?php echo $order_test_id; ?>" 
                                               class="btn btn-info w-100" target="_blank">
                                                <i class="ri-magic-line me-1"></i>Use AI Analysis
                                            </a>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <!-- Submit Actions -->
                                <div class="card">
                                    <div class="card-body">
                                        <button type="submit" class="btn btn-success w-100 mb-2">
                                            <i class="ri-save-line me-1"></i>Save & Complete
                                        </button>
                                        <a href="pending_tests.php" class="btn btn-outline-secondary w-100">
                                            <i class="ri-arrow-left-line me-1"></i>Back to Pending
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </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>
        // Form validation
        document.getElementById('resultsForm').addEventListener('submit', function(e) {
            const resultValue = document.querySelector('[name="result_value"]').value.trim();
            const interpretation = document.querySelector('[name="interpretation"]').value.trim();
            
            if (!resultValue || !interpretation) {
                e.preventDefault();
                Swal.fire('Error', 'Please fill in all required fields', 'error');
                return false;
            }
            
            // Confirm before saving
            e.preventDefault();
            Swal.fire({
                title: 'Save Test Results?',
                text: 'This will mark the test as completed',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, save results',
                cancelButtonText: 'Review again'
            }).then((result) => {
                if (result.isConfirmed) {
                    this.submit();
                }
            });
        });

        // Flag option styling
        document.querySelectorAll('.flag-option').forEach(option => {
            option.addEventListener('click', function() {
                const radio = this.querySelector('input[type="radio"]');
                radio.checked = true;
                
                // Remove active class from all
                document.querySelectorAll('.flag-option').forEach(opt => {
                    opt.style.backgroundColor = '';
                    opt.style.borderWidth = '2px';
                });
                
                // Add active styling
                this.style.backgroundColor = 'rgba(102, 126, 234, 0.1)';
                this.style.borderWidth = '3px';
            });
        });
    </script>
</body>
</html>