<?php
require_once '../config.php';
requirePatient();

$patient_id = $_SESSION['patient_id'];

// All lab-related records
$lab_types = ['lab_report', 'blood_test', 'xray', 'mri', 'ct_scan', 'ultrasound'];
$type_filter = $_GET['type'] ?? '';

$where_type = $type_filter && in_array($type_filter, $lab_types)
    ? "AND record_type = '$type_filter'"
    : "AND record_type IN ('lab_report','blood_test','xray','mri','ct_scan','ultrasound')";

$reports = $conn->query("
    SELECT * FROM medical_records
    WHERE patient_id = $patient_id $where_type
    ORDER BY record_date DESC
")->fetch_all(MYSQLI_ASSOC);

// Counts per type
$type_info = [
    'lab_report'  => ['label' => 'Lab Reports',       'fa' => 'fa-flask',       'color' => 'info'],
    'blood_test'  => ['label' => 'Blood Tests',        'fa' => 'fa-tint',        'color' => 'danger'],
    'xray'        => ['label' => 'X-Rays',             'fa' => 'fa-x-ray',       'color' => 'dark'],
    'mri'         => ['label' => 'MRI Reports',        'fa' => 'fa-magnet',      'color' => 'secondary'],
    'ct_scan'     => ['label' => 'CT Scans',           'fa' => 'fa-microscope',  'color' => 'warning'],
    'ultrasound'  => ['label' => 'Ultrasound Reports', 'fa' => 'fa-wave-square', 'color' => 'primary'],
];

$counts = [];
foreach ($lab_types as $lt) {
    $counts[$lt] = $conn->query("SELECT COUNT(*) FROM medical_records WHERE patient_id=$patient_id AND record_type='$lt'")->fetch_row()[0];
}
$total = array_sum($counts);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Lab Reports - HealthLink</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    body { background: #f0f4ff; font-family: Inter, 'Segoe UI', sans-serif; overflow-x:hidden; }
    .card { border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 2px 10px rgba(11,74,203,.07); }
    .page-body { padding: 20px 24px; }

    .type-card {
      padding: 14px 10px; text-align: center; border-radius: 14px;
      border: 1.5px solid #e2e8f0; background: #fff;
      transition: all .2s; cursor: pointer;
    }
    .type-card:hover { border-color: #0B4ACB; background: #eff4ff; transform: translateY(-2px); }
    .type-card.active { border-color: #0B4ACB; background: linear-gradient(135deg,#eff4ff,#dbeafe); }

    .report-row {
      display: flex; align-items: flex-start; gap: 14px;
      padding: 14px 20px; border-bottom: 1px solid #f0f4ff;
      transition: background .15s;
    }
    .report-row:last-child { border-bottom: none; }
    .report-row:hover { background: #f8faff; }
    .report-icon { width: 42px; flex-shrink: 0; text-align: center; margin-top: 2px; }

    .btn-blue { background: linear-gradient(135deg,#0B4ACB,#3B63E6); color: #fff !important; border: none; padding: 8px 18px; border-radius: 10px; font-size: 13px; font-weight: 600; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; transition: all .2s; }
    .btn-blue:hover { opacity: .9; transform: translateY(-1px); }

    @media(max-width:768px) {
      .page-body { padding: 12px; }
      .report-row { padding: 12px 14px; gap: 10px; }
      .type-card { padding: 10px 6px; }
      .type-card i { font-size: 1.1rem !important; }
      .type-card div { font-size: 9px !important; }
    }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main-content">
<?php $page_title = 'Lab Reports'; include 'topbar.php'; ?>
  <div class="page-body">
    <?php displayFlash(); ?>

    <!-- Type Filter Cards -->
    <div class="row g-2 mb-4">
      <div class="col-4 col-md-2">
        <a href="lab-reports.php" class="text-decoration-none">
          <div class="card type-card <?= !$type_filter ? 'active' : '' ?>">
            <i class="fas fa-folder-open" style="font-size:1.4rem;color:#0B4ACB;"></i>
            <div style="font-size:11px;font-weight:700;margin-top:4px;color:#0f172a;">All</div>
            <div style="font-size:13px;font-weight:800;color:#0B4ACB;margin-top:2px;"><?= $total ?></div>
          </div>
        </a>
      </div>
      <?php foreach ($type_info as $key => $ti): ?>
        <div class="col-4 col-md-2">
          <a href="?type=<?= $key ?>" class="text-decoration-none">
            <div class="card type-card <?= $type_filter === $key ? 'active' : '' ?>">
              <i class="fas <?= $ti['fa'] ?>" style="font-size:1.4rem;color:#0B4ACB;"></i>
              <div style="font-size:11px;font-weight:700;margin-top:4px;line-height:1.2;color:#0f172a;"><?= $ti['label'] ?></div>
              <div style="font-size:13px;font-weight:800;color:#0B4ACB;margin-top:2px;"><?= $counts[$key] ?></div>
            </div>
          </a>
        </div>
      <?php endforeach; ?>
    </div>

    <!-- Reports List -->
    <div class="card">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-700">
          <?= $type_filter ? ('<i class="fas '.$type_info[$type_filter]['fa'].' me-1"></i>'.$type_info[$type_filter]['label']) : '<i class="fas fa-folder-open me-1"></i>All Lab Reports & Tests' ?>
          <span class="badge ms-2" style="background:#eff4ff;color:#0B4ACB;font-size:11px;"><?= count($reports) ?></span>
        </h6>
        <?php if ($type_filter): ?>
          <a href="lab-reports.php" class="btn btn-sm" style="background:#f1f5f9;color:#64748b;border:1px solid #e2e8f0;font-weight:600;border-radius:8px;">Show All</a>
        <?php endif; ?>
      </div>

      <?php if (empty($reports)): ?>
        <div class="p-5 text-center text-muted">
          <i class="fas fa-flask fa-4x mb-3" style="opacity:0.2;"></i>
          <h5>No reports found</h5>
          <p>Upload your lab reports using the button above.</p>
          <a href="health-records.php" class="btn-blue" style="padding:6px 14px;font-size:12px;">Upload Report</a>
        </div>
      <?php else: ?>
        <?php foreach ($reports as $r):
          $ti = $type_info[$r['record_type']] ?? ['fa' => 'fa-paperclip', 'label' => 'Report', 'color' => 'secondary'];
        ?>
          <div class="report-row">
            <div class="report-icon"><i class="fas <?= $ti['fa'] ?>" style="font-size:1.4rem;color:#0B4ACB;"></i></div>
            <div class="flex-grow-1">
              <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
                <div>
                  <div style="font-weight:700;font-size:0.9rem;"><?= htmlspecialchars($r['title']) ?></div>
                  <div class="mt-1">
                    <span class="badge ms-1" style="background:#eff4ff;color:#0B4ACB;font-size:11px;"><?= $ti['label'] ?></span>
                    <?php if ($r['doctor_name']): ?>
                      <span class="text-muted ms-2" style="font-size:0.78rem;"><i class="fas fa-user-md"></i> Dr. <?= htmlspecialchars($r['doctor_name']) ?></span>
                    <?php endif; ?>
                  </div>
                  <?php if ($r['description']): ?>
                    <div style="font-size:0.78rem;color:#718096;margin-top:4px;"><?= htmlspecialchars(substr($r['description'], 0, 100)) ?></div>
                  <?php endif; ?>
                </div>
                <div class="text-end" style="flex-shrink:0;">
                  <div style="font-size:0.78rem;color:#718096;"><i class="fas fa-calendar me-1"></i><?= date('d M Y', strtotime($r['record_date'])) ?></div>
                  <div class="mt-2">
                    <?php if ($r['file_path']): ?>
                      <a href="<?= SITE_URL ?>/<?= $r['file_path'] ?>" target="_blank" class="btn btn-sm" style="background:#eff4ff;color:#0B4ACB;border:1px solid #c7d7fc;font-size:12px;font-weight:600;border-radius:8px;"><i class="fas fa-eye me-1"></i>View</a>
                      <a href="<?= SITE_URL ?>/<?= $r['file_path'] ?>" download class="btn btn-sm ms-1" style="background:#f1f5f9;color:#64748b;border:1px solid #e2e8f0;font-size:12px;border-radius:8px;"><i class="fas fa-download"></i></a>
                    <?php else: ?>
                      <span class="text-muted" style="font-size:0.75rem;">No file</span>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
