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

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

$test_id = $_GET['test_id'] ?? 0;

if (!$test_id) {
    header('Location: audiometry_tests.php');
    exit();
}

// Fetch Test Details
$sql = "SELECT t.*, tt.test_name, tt.test_code, tt.category,
               o.order_number, p.patient_id, p.patient_number, u.full_name as patient_name, u.gender, u.date_of_birth
        FROM lab_order_tests t
        INNER JOIN lab_orders o ON t.order_id = o.order_id
        INNER JOIN patients p ON o.patient_id = p.patient_id
        INNER JOIN users u ON p.user_id = u.user_id
        INNER JOIN ent_test_types tt ON t.test_type_id = tt.test_type_id
        WHERE t.order_test_id = ?";

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

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

$is_audiometry = ($test['category'] === 'AUDIOMETRY');
$existing_results = json_decode($test['result_value'] ?? '[]', true);

// Handle Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $interpretation = $_POST['interpretation'];
    $status = isset($_POST['complete']) ? 'COMPLETED' : 'IN_PROGRESS';
    $completed_at = isset($_POST['complete']) ? date('Y-m-d H:i:s') : NULL;
    $tested_by = $_SESSION['user_id'];

    // Prepare result data
    $result_data = [];
    if ($is_audiometry) {
        $result_data = [
            'right' => $_POST['right'] ?? [],
            'left' => $_POST['left'] ?? [],
            'bone_right' => $_POST['bone_right'] ?? [],
            'bone_left' => $_POST['bone_left'] ?? []
        ];
    } else {
        $result_data = ['value' => $_POST['result_value_text'] ?? ''];
    }

    $json_result = json_encode($result_data);

    // Handle File Uploads (Simplified for now, assumes existing logic or future implementation)
    // For this task, we'll focus on the data saving.

    $update_sql = "UPDATE lab_order_tests SET 
                   result_value = ?, interpretation = ?, 
                   status = ?, tested_by = ?, completed_at = ? 
                   WHERE order_test_id = ?";

    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("sssisi", $json_result, $interpretation, $status, $tested_by, $completed_at, $test_id);

    if ($stmt->execute()) {
        if ($status === 'COMPLETED') {
            header("Location: view_test_details.php?test_id=" . $test_id);
            exit();
        } else {
            $msg = "Draft saved successfully.";
        }
    } else {
        $error = "Failed to save results: " . $conn->error;
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Enter Results')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .input-cell {
            min-width: 60px;
        }

        .freq-header {
            background-color: #f8fafc;
            font-weight: 600;
            text-align: center;
        }

        .ear-label {
            font-weight: 600;
            vertical-align: middle;
        }

        .right-ear {
            color: #dc2626;
            border-left: 4px solid #dc2626;
        }

        .left-ear {
            color: #2563eb;
            border-left: 4px solid #2563eb;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <!-- Title & Breadcrumbs -->
                    <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">Enter Test Results</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="audiometry_tests.php">Audiometry</a></li>
                                        <li class="breadcrumb-item active">Enter Results</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($msg)): ?>
                        <div class="alert alert-success">
                            <?php echo $msg; ?>
                        </div>
                    <?php endif; ?>
                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger">
                            <?php echo $error; ?>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Patient Summary -->
                        <div class="col-xl-3">
                            <div class="card">
                                <div class="card-header bg-light">
                                    <h5 class="card-title mb-0">Patient Info</h5>
                                </div>
                                <div class="card-body">
                                    <h6>
                                        <?php echo htmlspecialchars($test['patient_name']); ?>
                                    </h6>
                                    <p class="text-muted mb-1">ID:
                                        <?php echo htmlspecialchars($test['patient_number']); ?>
                                    </p>
                                    <p class="text-muted mb-1">Gender:
                                        <?php echo $test['gender']; ?>
                                    </p>
                                    <hr>
                                    <h6>Test Info</h6>
                                    <p class="text-muted mb-1">
                                        <?php echo htmlspecialchars($test['test_name']); ?>
                                    </p>
                                    <p class="text-muted mb-0">Order: #
                                        <?php echo htmlspecialchars($test['order_number']); ?>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Result Entry Form -->
                        <div class="col-xl-9">
                            <form method="POST">
                                <div class="card">
                                    <div class="card-header align-items-center d-flex">
                                        <h4 class="card-title mb-0 flex-grow-1">Audiometry Data Entry</h4>
                                    </div>
                                    <div class="card-body">

                                        <?php if ($is_audiometry): ?>
                                            <!-- Air Conduction -->
                                            <h5 class="mb-3">Air Conduction (dB HL)</h5>
                                            <div class="table-responsive mb-4">
                                                <table class="table table-bordered text-center align-middle">
                                                    <thead>
                                                        <tr>
                                                            <th class="freq-header">Frequency (Hz)</th>
                                                            <th class="freq-header">250</th>
                                                            <th class="freq-header">500</th>
                                                            <th class="freq-header">1000</th>
                                                            <th class="freq-header">2000</th>
                                                            <th class="freq-header">4000</th>
                                                            <th class="freq-header">8000</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr class="right-ear">
                                                            <td class="ear-label">Right Ear (Red)</td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="right[250]"
                                                                    value="<?php echo $existing_results['right'][250] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="right[500]"
                                                                    value="<?php echo $existing_results['right'][500] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="right[1000]"
                                                                    value="<?php echo $existing_results['right'][1000] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="right[2000]"
                                                                    value="<?php echo $existing_results['right'][2000] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="right[4000]"
                                                                    value="<?php echo $existing_results['right'][4000] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="right[8000]"
                                                                    value="<?php echo $existing_results['right'][8000] ?? ''; ?>">
                                                            </td>
                                                        </tr>
                                                        <tr class="left-ear">
                                                            <td class="ear-label">Left Ear (Blue)</td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="left[250]"
                                                                    value="<?php echo $existing_results['left'][250] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="left[500]"
                                                                    value="<?php echo $existing_results['left'][500] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="left[1000]"
                                                                    value="<?php echo $existing_results['left'][1000] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="left[2000]"
                                                                    value="<?php echo $existing_results['left'][2000] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="left[4000]"
                                                                    value="<?php echo $existing_results['left'][4000] ?? ''; ?>">
                                                            </td>
                                                            <td><input type="number" step="5"
                                                                    class="form-control form-control-sm text-center"
                                                                    name="left[8000]"
                                                                    value="<?php echo $existing_results['left'][8000] ?? ''; ?>">
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>

                                            <!-- Bone Conduction -->
                                            <h5 class="mb-3">Bone Conduction (dB HL)</h5>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <table class="table table-bordered text-center align-middle">
                                                        <thead>
                                                            <tr>
                                                                <th class="freq-header" colspan="5">Right Ear [ < ]</th>
                                                            </tr>
                                                            <tr>
                                                                <th>Freq (Hz)</th>
                                                                <th>500</th>
                                                                <th>1000</th>
                                                                <th>2000</th>
                                                                <th>4000</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr>
                                                                <td class="text-muted">dB</td>
                                                                <td><input type="number" step="5"
                                                                        class="form-control form-control-sm text-center"
                                                                        name="bone_right[500]"
                                                                        value="<?php echo $existing_results['bone_right'][500] ?? ''; ?>">
                                                                </td>
                                                                <td><input type="number" step="5"
                                                                        class="form-control form-control-sm text-center"
                                                                        name="bone_right[1000]"
                                                                        value="<?php echo $existing_results['bone_right'][1000] ?? ''; ?>">
                                                                </td>
                                                                <td><input type="number" step="5"
                                                                        class="form-control form-control-sm text-center"
                                                                        name="bone_right[2000]"
                                                                        value="<?php echo $existing_results['bone_right'][2000] ?? ''; ?>">
                                                                </td>
                                                                <td><input type="number" step="5"
                                                                        class="form-control form-control-sm text-center"
                                                                        name="bone_right[4000]"
                                                                        value="<?php echo $existing_results['bone_right'][4000] ?? ''; ?>">
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                                <div class="col-md-6">
                                                    <table class="table table-bordered text-center align-middle">
                                                        <thead>
                                                            <tr>
                                                                <th class="freq-header" colspan="5">Left Ear [ > ]</th>
                                                            </tr>
                                                            <tr>
                                                                <th>Freq (Hz)</th>
                                                                <th>500</th>
                                                                <th>1000</th>
                                                                <th>2000</th>
                                                                <th>4000</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr>
                                                                <td class="text-muted">dB</td>
                                                                <td><input type="number" step="5"
                                                                        class="form-control form-control-sm text-center"
                                                                        name="bone_left[500]"
                                                                        value="<?php echo $existing_results['bone_left'][500] ?? ''; ?>">
                                                                </td>
                                                                <td><input type="number" step="5"
                                                                        class="form-control form-control-sm text-center"
                                                                        name="bone_left[1000]"
                                                                        value="<?php echo $existing_results['bone_left'][1000] ?? ''; ?>">
                                                                </td>
                                                                <td><input type="number" step="5"
                                                                        class="form-control form-control-sm text-center"
                                                                        name="bone_left[2000]"
                                                                        value="<?php echo $existing_results['bone_left'][2000] ?? ''; ?>">
                                                                </td>
                                                                <td><input type="number" step="5"
                                                                        class="form-control form-control-sm text-center"
                                                                        name="bone_left[4000]"
                                                                        value="<?php echo $existing_results['bone_left'][4000] ?? ''; ?>">
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>

                                        <?php else: ?>
                                            <!-- Standard Text Input -->
                                            <div class="mb-3">
                                                <label class="form-label">Result Value</label>
                                                <textarea class="form-control" name="result_value_text"
                                                    rows="5"><?php echo htmlspecialchars($test['result_value'] ?? ''); ?></textarea>
                                            </div>
                                        <?php endif; ?>

                                        <div class="mb-4 mt-4">
                                            <label class="form-label fw-bold">Clinical Interpretation &
                                                Recommendations</label>
                                            <textarea class="form-control" name="interpretation" rows="4"
                                                placeholder="Enter findings, interpretation, and recommendations..."><?php echo htmlspecialchars($test['interpretation'] ?? ''); ?></textarea>
                                        </div>

                                        <hr>

                                        <div class="d-flex justify-content-end gap-2">
                                            <button type="submit" name="save_draft" class="btn btn-warning">
                                                <i class="ri-save-3-line me-1"></i>Save Draft
                                            </button>
                                            <button type="submit" name="complete" class="btn btn-success"
                                                onclick="return confirm('Are you sure you want to finalize these results?');">
                                                <i class="ri-check-double-line me-1"></i>Finalize & Complete
                                            </button>
                                        </div>

                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>

</html>