<?php
// File: /dripend/includes/consultation/searchConsultations.php
session_start();
require_once '../db.php';

if (!isset($_GET['patient_no'])) die("<tr><td colspan='4'>Invalid Request</td></tr>");

$patient_no = $_GET['patient_no'];
$date_from = $_GET['date_from'] ?? '1970-01-01';
$date_to = $_GET['date_to'] ?? date('Y-m-d');

// Optimize: We only query the visit_master and the PRIMARY diagnosis.
$query = "
    SELECT 
        v.id AS visit_id, 
        v.visit_date, 
        v.clinical_outcome,
        s.first_name, 
        s.last_name,
        (SELECT description FROM clinical_diagnoses cd WHERE cd.visit_id = v.id AND cd.is_principal = 1 LIMIT 1) AS primary_diag
    FROM visit_master v
    LEFT JOIN staff s ON v.primary_doctor_id = s.staff_id
    WHERE v.patient_no = ? AND v.visit_date BETWEEN ? AND ? AND v.status = 'Completed'
    ORDER BY v.visit_date DESC
";

$stmt = $conn->prepare($query);
$stmt->bind_param("sss", $patient_no, $date_from, $date_to);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    echo "<tr><td colspan='4' style='text-align:center; padding:30px; color:#64748b;'>No completed consultations found for this period.</td></tr>";
} else {
    while ($row = $res->fetch_assoc()) {
        $date = date('d M Y', strtotime($row['visit_date']));
        $doc = !empty($row['first_name']) ? "Dr. " . $row['first_name'] . " " . $row['last_name'] : "Unknown";
        $diag = !empty($row['primary_diag']) ? htmlspecialchars($row['primary_diag']) : "<i style='color:#94a3b8;'>No primary diagnosis</i>";
        
        echo "<tr style='border-bottom: 1px solid #e2e8f0;'>";
        echo "<td style='padding:12px; font-weight:700;'>{$date}</td>";
        echo "<td style='padding:12px;'>{$doc}</td>";
        echo "<td style='padding:12px;'>{$diag}</td>";
        echo "<td style='padding:12px; text-align:right;'>
                <button class='btn-history' onclick='openConsultDetail({$row['visit_id']}, \"{$date}\")'><i class='fa-solid fa-eye'></i> View</button>
              </td>";
        echo "</tr>";
    }
}
$stmt->close();
?>