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

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

$user_id = $_SESSION['user_id'];
$pat_res = $conn->query("SELECT patient_id FROM patients WHERE user_id = $user_id")->fetch_assoc();
$patient_id = $pat_res['patient_id'];

// Check if specific appointment ID passed (from Appointment History page)
$filter_appt = isset($_GET['appt_id']) ? intval($_GET['appt_id']) : 0;
$filter_sql = "";
if ($filter_appt > 0) {
    // Check if this appointment belongs to patient
    $chk = $conn->query("SELECT appointment_id FROM appointments WHERE appointment_id=$filter_appt AND patient_id=$patient_id");
    if ($chk->num_rows > 0) {
        // Modify query to filter or highlight? 
        // Actually, let's just show all recent visits but highlight the one requested if needed.
        // Or simpler: List all consultations/visits.
    }
}

// Fetch Consultations (Visit Reports)
$sql = "SELECT c.consultation_id, c.consultation_date, c.diagnosis, c.treatment_plan, 
               u.full_name as doctor_name, d.specialization,
               (SELECT GROUP_CONCAT(test_name SEPARATOR ', ') FROM lab_orders lo JOIN lab_tests lt ON lo.test_id = lt.test_id WHERE lo.visit_id = c.visit_id) as lab_tests
        FROM consultations c
        JOIN doctors d ON c.doctor_id = d.user_id 
        JOIN users u ON d.user_id = u.user_id
        WHERE c.patient_id = ?
        ORDER BY c.consultation_date DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Visit Reports')); ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <?php include 'layouts/head-css.php'; ?>
</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">My Visit Reports</h4>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <?php if ($result->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table id="reportsTable"
                                                class="table table-bordered dt-responsive nowrap w-100">
                                                <thead>
                                                    <tr>
                                                        <th>Date</th>
                                                        <th>Doctor</th>
                                                        <th>Diagnosis</th>
                                                        <th>Lab Tests</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while ($row = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($row['consultation_date'])); ?>
                                                            </td>
                                                            <td>Dr. <?php echo htmlspecialchars($row['doctor_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['diagnosis'] ?? 'Pending'); ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($row['lab_tests'] ?? 'None'); ?>
                                                            </td>
                                                            <td>
                                                                <button class="btn btn-sm btn-soft-primary"
                                                                    onclick="viewReport(<?php echo htmlspecialchars(json_encode($row)); ?>)">
                                                                    <i class="ri-file-text-line"></i> Summary
                                                                </button>
                                                                <a href="patient_download_records.php?type=visit&id=<?php echo $row['consultation_id']; ?>"
                                                                    class="btn btn-sm btn-soft-success">
                                                                    <i class="ri-download-line"></i> Download
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="alert alert-info">No visit reports found.</div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Report Modal -->
    <div class="modal fade" id="reportModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Visit Summary</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label text-muted">Date</label>
                            <h6 id="repDate"></h6>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label text-muted">Doctor</label>
                            <h6 id="repDoc"></h6>
                        </div>
                        <div class="col-12 mb-3">
                            <label class="form-label text-muted">Diagnosis</label>
                            <p class="border p-2 rounded bg-light" id="repDiag"></p>
                        </div>
                        <div class="col-12 mb-3">
                            <label class="form-label text-muted">Treatment Plan / Instructions</label>
                            <p class="border p-2 rounded bg-light" id="repPlan"></p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="window.print()">Print</button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#reportsTable').DataTable({
                order: [[0, 'desc']]
            });
        });

        function viewReport(data) {
            $('#repDate').text(new Date(data.consultation_date).toLocaleDateString());
            $('#repDoc').text('Dr. ' + data.doctor_name);
            $('#repDiag').text(data.diagnosis || 'N/A');
            $('#repPlan').text(data.treatment_plan || 'N/A');
            new bootstrap.Modal('#reportModal').show();
        }
    </script>
</body>

</html>