<?php
// Get visit ID
$visit_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$visit_id) {
    echo "Visit ID not specified."; exit;
}

// Fetch the current visit to get patient and department info
$stmt = $pdo->prepare("
    SELECT v.patient_id, v.department_id 
    FROM visits v 
    WHERE v.id = ?
");
$stmt->execute([$visit_id]);
$current_visit = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$current_visit) {
    echo "Visit not found."; exit;
}

$patient_id = $current_visit['patient_id'];
$current_department_id = $current_visit['department_id'];

// Check user permissions
$user_id = $_SESSION['user_id'] ?? 0;
$user_role = $_SESSION['user_role'] ?? '';
// ADDED 'Nurse' to roles that can see all visits
$can_see_all_visits = in_array($user_role, ['Super_admin', 'Admin', 'Receptionist', 'Cashier', 'Nurse']);

// If user can't see all visits, check if they belong to the current visit's department
if (!$can_see_all_visits) {
    // Get user's department
    $stmt = $pdo->prepare("SELECT department_id FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user_department = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // If user doesn't have a department or their department doesn't match the visit's department
    if (!$user_department || (int)$user_department['department_id'] !== (int)$current_department_id) {
        echo "You don't have permission to view visits from this department."; 
        exit;
    }
}

// Pagination
$perPage = 5;
$page = isset($_GET['visit_page']) ? (int)$_GET['visit_page'] : 1;
$offset = ($page - 1) * $perPage;

// Build WHERE clause based on user role
$whereClause = "WHERE v.patient_id = :patient_id";
$params = ['patient_id' => $patient_id];

// If user can't see all visits, filter by their department
if (!$can_see_all_visits && isset($user_department['department_id'])) {
    $whereClause .= " AND v.department_id = :department_id";
    $params['department_id'] = $user_department['department_id'];
}

// Fetch total visits count
$totalVisitsQuery = $pdo->prepare("
    SELECT COUNT(*) 
    FROM visits v
    $whereClause
");
$totalVisitsQuery->execute($params);
$totalVisits = $totalVisitsQuery->fetchColumn();
$totalPages = ceil($totalVisits / $perPage);

// Fetch current page visits with ticket info
$visitsQuery = $pdo->prepare("
    SELECT v.id AS visit_id, v.department_id, t.id AS ticket_id, t.*, v.visit_date, d.name as department_name
    FROM visits v
    LEFT JOIN visit_tickets t ON t.visit_id = v.id
    LEFT JOIN departments d ON d.id = v.department_id
    $whereClause
    ORDER BY v.visit_date DESC
    LIMIT :limit OFFSET :offset
");

// Bind parameters
foreach ($params as $key => $value) {
    $visitsQuery->bindValue(':' . $key, $value, PDO::PARAM_INT);
}
$visitsQuery->bindValue(':limit', $perPage, PDO::PARAM_INT);
$visitsQuery->bindValue(':offset', $offset, PDO::PARAM_INT);
$visitsQuery->execute();
$visits = $visitsQuery->fetchAll(PDO::FETCH_ASSOC);

// Fetch Lab Orders, Imaging, Diagnoses, Prescriptions for each visit ticket
foreach ($visits as &$visit) {
    $ticket_id = $visit['ticket_id'];
    
    if (!$ticket_id) continue; // Skip if no ticket

    // Lab Orders
    $stmtLab = $pdo->prepare("
        SELECT lo.*, p.name AS lab_name 
        FROM lab_orders lo 
        JOIN products p ON lo.product_id = p.id 
        WHERE lo.visit_ticket_id = ?
    ");
    $stmtLab->execute([$ticket_id]);
    $visit['lab_orders'] = $stmtLab->fetchAll(PDO::FETCH_ASSOC);

    // Imaging Reports
    $visit['imaging_reports'] = !empty($visit['imaging_reports']) ? json_decode($visit['imaging_reports'], true) : [];

    // Final Diagnoses
    $visit['final_diagnoses'] = [
        'title' => !empty($visit['final_diagnosis_title']) ? json_decode($visit['final_diagnosis_title'], true) : [],
        'code' => !empty($visit['final_diagnosis_code']) ? json_decode($visit['final_diagnosis_code'], true) : [],
        'comment' => !empty($visit['final_diagnosis_comment']) ? json_decode($visit['final_diagnosis_comment'], true) : []
    ];

    // Prescriptions
    $visit['prescriptions'] = [
        'in' => !empty($visit['drug_name_in']) ? json_decode($visit['drug_name_in'], true) : [],
        'dosage_in' => !empty($visit['dosage_in']) ? json_decode($visit['dosage_in'], true) : [],
        'out' => !empty($visit['drug_name_out']) ? json_decode($visit['drug_name_out'], true) : [],
        'dosage_out' => !empty($visit['dosage_out']) ? json_decode($visit['dosage_out'], true) : []
    ];

    // Other Management
    $visit['other_management'] = $visit['other_management'] ?? '';

    // HMIS Report
    $visit['hmis_report'] = !empty($visit['hmis_report']) ? json_decode($visit['hmis_report'], true) : [];
}
unset($visit);
?>


    <div class="card-header">
        <h4 class="card-title">Patient Visit History List</h4>
        <?php if (!$can_see_all_visits): ?>
            <small class="text-muted">(Showing only visits from your department)</small>
        <?php else: ?>
            <small class="text-muted">(Showing all department visits)</small>
        <?php endif; ?>
    </div>
    <div class="card-body">

        <?php if(!empty($visits)): ?>
            <?php foreach($visits as $visit): ?>
                <?php
                    $modalId = 'historyModal'.$visit['ticket_id'];
                    $visitDate = date('d-M-Y', strtotime($visit['visit_date']));
                ?>
                <button type="button" class="btn btn-info btn-block mb-2"
                        data-toggle="modal" data-target="#<?= $modalId ?>">
                    Visit on <?= $visitDate ?>
                    <small class="text-light">(<?= htmlspecialchars($visit['department_name'] ?? 'Unknown') ?>)</small>
                </button>

                <!-- Modal -->
                <div class="modal fade" id="<?= $modalId ?>" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    Visit Details (<?= $visitDate ?>)
                                    <small class="text-muted">- <?= htmlspecialchars($visit['department_name'] ?? 'Unknown Department') ?></small>
                                </h5>
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                            </div>
                            <div class="modal-body">
                                <!-- Vital Signs -->
                                <p><strong>Catchment Area:</strong> <?= htmlspecialchars($visit['catchment_area'] ?? '') ?></p>
                                <p><strong>New Case:</strong> <?= htmlspecialchars($visit['new_case'] ?? '') ?></p>
                                <p><strong>Systolic / Diastolic:</strong> <?= $visit['systolic'] ?? '-' ?>/<?= $visit['diastolic'] ?? '-' ?></p>
                                <p><strong>Heart Rate:</strong> <?= $visit['heart_rate'] ?? '-' ?></p>
                                <p><strong>Temperature:</strong> <?= $visit['temperature'] ?? '-' ?>”ĘC</p>
                                <p><strong>Resp Rate:</strong> <?= $visit['resp_rate'] ?? '-' ?></p>
                                <p><strong>SpO2:</strong> <?= $visit['spo2'] ?? '-' ?>%</p>
                                <p><strong>Weight / Height:</strong> <?= $visit['weight'] ?? '-' ?> kg / <?= $visit['height'] ?? '-' ?> cm</p>
                                <p><strong>Comment:</strong> <?= htmlspecialchars($visit['vital_comment'] ?? '') ?></p>

                                <hr>
                                <!-- History -->
                                <h6>Chief Complaints</h6>
                                <p><?= htmlspecialchars($visit['chief_complaints'] ?? '') ?></p>
                                <h6>History of Presenting Illness</h6>
                                <p><?= htmlspecialchars($visit['presenting_history'] ?? '') ?></p>
                                <h6>Past Medical History</h6>
                                <p><?= htmlspecialchars($visit['past_medical_history'] ?? '') ?></p>
                                <h6>Systemic Review</h6>
                                <p><?= htmlspecialchars($visit['systemic_review'] ?? '') ?></p>
                                <h6>Physical Examination</h6>
                                <p><?= htmlspecialchars($visit['physical_examination'] ?? '') ?></p>
                                <h6>Summary</h6>
                                <p><?= htmlspecialchars($visit['summary'] ?? '') ?></p>
                                <h6>Differential Diagnosis</h6>
                                <p><?= htmlspecialchars($visit['differential_diagnosis'] ?? '') ?></p>

                                <hr>
                                <!-- Lab Orders -->
                                <h6>Lab Orders</h6>
                                <?php if(!empty($visit['lab_orders'])): ?>
                                    <ul>
                                    <?php foreach($visit['lab_orders'] as $lab): ?>
                                        <li><?= htmlspecialchars($lab['lab_name'] ?? '') ?> - Result: <?= htmlspecialchars($lab['result_value'] ?? 'Pending') ?></li>
                                    <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p>No lab orders.</p>
                                <?php endif; ?>

                                <!-- Imaging Reports -->
                                <h6>Imaging Reports</h6>
                                <?php if(!empty($visit['imaging_reports'])): ?>
                                    <ul>
                                    <?php foreach($visit['imaging_reports'] as $img): ?>
                                        <li><?= htmlspecialchars($img['type'] ?? '') ?> - Report: <?= htmlspecialchars($img['report'] ?? '') ?> - Recommendation: <?= htmlspecialchars($img['recommendation'] ?? '') ?></li>
                                    <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p>No imaging reports.</p>
                                <?php endif; ?>

                                <!-- Final Diagnoses -->
                                <h6>Final Diagnoses</h6>
                                <?php if(!empty($visit['final_diagnoses']['title'])): ?>
                                    <ul>
                                    <?php foreach($visit['final_diagnoses']['title'] as $i => $title): ?>
                                        <li><?= htmlspecialchars($title ?? '') ?> (Code: <?= htmlspecialchars($visit['final_diagnoses']['code'][$i] ?? '') ?>) - Comment: <?= htmlspecialchars($visit['final_diagnoses']['comment'][$i] ?? '') ?></li>
                                    <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p>No final diagnoses.</p>
                                <?php endif; ?>

                                <!-- Prescriptions -->
                                <h6>Prescriptions (Internal)</h6>
                                <?php if(!empty($visit['prescriptions']['in'])): ?>
                                    <ul>
                                    <?php foreach($visit['prescriptions']['in'] as $i => $drug): ?>
                                        <li><?= htmlspecialchars($drug) ?> - Dosage: <?= htmlspecialchars($visit['prescriptions']['dosage_in'][$i] ?? '') ?></li>
                                    <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p>No internal prescriptions.</p>
                                <?php endif; ?>

                                <h6>Prescriptions (External)</h6>
                                <?php if(!empty($visit['prescriptions']['out'])): ?>
                                    <ul>
                                    <?php foreach($visit['prescriptions']['out'] as $i => $drug): ?>
                                        <li><?= htmlspecialchars($drug) ?> - Dosage: <?= htmlspecialchars($visit['prescriptions']['dosage_out'][$i] ?? '') ?></li>
                                    <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p>No external prescriptions.</p>
                                <?php endif; ?>

                                <!-- Other Management -->
                                <h6>Other Management</h6>
                                <p><?= htmlspecialchars($visit['other_management']) ?></p>

                                <!-- HMIS Report -->
                                <h6>HMIS Report</h6>
                                <?php if(!empty($visit['hmis_report'])): ?>
                                    <ul>
                                    <?php foreach($visit['hmis_report'] as $hmis): ?>
                                        <li><?= htmlspecialchars($hmis) ?></li>
                                    <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p>No HMIS report.</p>
                                <?php endif; ?>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>

            <!-- Pagination -->
            <nav>
                <ul class="pagination justify-content-center mt-2">
                    <?php for($p=1; $p<=$totalPages; $p++): ?>
                        <li class="page-item <?= $p==$page?'active':'' ?>">
                            <a class="page-link" href="?visit_page=<?= $p ?>"><?= $p ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>

        <?php else: ?>
            <p>
                No previous visits found for this patient.
                <?php if (!$can_see_all_visits): ?>
                    <small class="text-muted d-block">(You only see visits from your department)</small>
                <?php endif; ?>
            </p>
        <?php endif; ?>

    </div>