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

$patient_id = $_SESSION['patient_id'];

// Fetch all patient data permanently linked to profile
$stmt = $conn->prepare("SELECT * FROM patients WHERE id = ?");
$stmt->bind_param('i', $patient_id);
$stmt->execute();
$p = $stmt->get_result()->fetch_assoc();

// All medical records grouped by type
$all_records = $conn->query("SELECT * FROM medical_records WHERE patient_id=$patient_id ORDER BY record_date DESC")->fetch_all(MYSQLI_ASSOC);

// All appointments / consultation history
$consultations = $conn->query("
    SELECT a.*, d.full_name as doctor_name, s.name as specialization, d.qualification
    FROM appointments a
    JOIN doctors d ON a.doctor_id = d.id
    LEFT JOIN specializations s ON d.specialization_id = s.id
    WHERE a.patient_id = $patient_id AND a.status = 'completed'
    ORDER BY a.appointment_date DESC
")->fetch_all(MYSQLI_ASSOC);

// Prescriptions
$prescriptions = $conn->query("
    SELECT p.*, d.full_name as doctor_name
    FROM prescriptions p
    LEFT JOIN doctors d ON p.doctor_id = d.id
    WHERE p.patient_id = $patient_id
    ORDER BY p.created_at DESC
")->fetch_all(MYSQLI_ASSOC);

// Group records by type
$records_by_type = [];
foreach ($all_records as $r) {
    $records_by_type[$r['record_type']][] = $r;
}

$record_icons = [
    'lab_report'=>'fa-flask','blood_test'=>'fa-tint','xray'=>'fa-x-ray','mri'=>'fa-magnet',
    'ct_scan'=>'fa-microscope','ultrasound'=>'fa-wave-square','vaccination'=>'fa-syringe',
    'health_assessment'=>'fa-chart-bar','doctor_note'=>'fa-sticky-note','other'=>'fa-paperclip',
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Medical History - 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; }
    @media(max-width:768px){ .page-body{ padding:12px; } }

    .section-header { font-size:13px; font-weight:700; color:#0f172a; padding:6px 0; border-bottom:2px solid #eff4ff; margin-bottom:10px; display:flex; align-items:center; }

    .info-row { display:flex; align-items:flex-start; gap:10px; padding:8px 0; border-bottom:1px solid #f0f4ff; }
    .info-row:last-child { border-bottom:none; }
    .info-label { min-width:130px; font-size:11px; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:.4px; flex-shrink:0; padding-top:2px; }
    .info-value { font-size:13px; font-weight:600; color:#0f172a; word-break:break-word; }

    .timeline-item { padding:12px 0; border-bottom:1px solid #f0f4ff; }
    .timeline-item:last-child { border-bottom:none; }

    @media(max-width:576px) {
      .info-label { min-width:100px; font-size:10px; }
      .info-value { font-size:12px; }
      .info-row { flex-wrap:wrap; gap:4px; }
      .card.p-4 { padding:14px !important; }
      .card.p-3 { padding:12px !important; }
      table thead { display:none; }
      table tr { display:block; margin-bottom:10px; border:1px solid #e2e8f0; border-radius:10px; padding:8px; }
      table td { display:flex; justify-content:space-between; font-size:0.8rem; padding:4px 6px; border:none; }
      table td::before { content:attr(data-label); font-weight:700; color:#94a3b8; font-size:10px; text-transform:uppercase; }
    }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main-content">
<?php $page_title = 'Medical History'; include 'topbar.php'; ?>
  <div class="page-body">

    <!-- Patient Summary Card -->
    <div class="card mb-4 p-4">
      <div class="section-header mb-3"><i class="fas fa-user me-2 text-primary"></i>Patient Profile Summary</div>
      <div class="row g-3">
        <div class="col-md-6">
          <div class="info-row"><span class="info-label">Full Name</span><span class="info-value"><?= htmlspecialchars($p['full_name']) ?></span></div>
          <div class="info-row"><span class="info-label">Health ID</span><span class="info-value" style="color:#0B4ACB;font-weight:700;"><?= htmlspecialchars($p['health_id']) ?></span></div>
          <div class="info-row"><span class="info-label">Date of Birth</span><span class="info-value"><?= $p['date_of_birth'] ? date('d M Y', strtotime($p['date_of_birth'])) : 'Not set' ?></span></div>
          <div class="info-row"><span class="info-label">Gender</span><span class="info-value"><?= ucfirst($p['gender'] ?? 'Not set') ?></span></div>
          <div class="info-row"><span class="info-label">Blood Group</span><span class="info-value"><strong style="color:#e53e3e;"><?= htmlspecialchars($p['blood_group'] ?? 'Not set') ?></strong></span></div>
          <div class="info-row"><span class="info-label">Height / Weight</span><span class="info-value"><?= ($p['height'] ?? '--') ?> cm / <?= ($p['weight'] ?? '--') ?> kg</span></div>
        </div>
        <div class="col-md-6">
          <div class="info-row"><span class="info-label">Phone</span><span class="info-value"><?= htmlspecialchars($p['phone']) ?></span></div>
          <div class="info-row"><span class="info-label">Email</span><span class="info-value"><?= htmlspecialchars($p['email']) ?></span></div>
          <div class="info-row"><span class="info-label">City</span><span class="info-value"><?= htmlspecialchars($p['city'] ?? 'Not set') ?></span></div>
          <div class="info-row"><span class="info-label">Smoking</span><span class="info-value"><?= ucfirst($p['smoking'] ?? 'Not set') ?></span></div>
          <div class="info-row"><span class="info-label">Alcohol</span><span class="info-value"><?= ucfirst($p['alcohol'] ?? 'Not set') ?></span></div>
          <div class="info-row"><span class="info-label">Emergency Contact</span>
            <span class="info-value"><?= htmlspecialchars($p['emergency_contact_name'] ?? 'Not set') ?> <?= $p['emergency_contact_phone'] ? '(' . htmlspecialchars($p['emergency_contact_phone']) . ')' : '' ?></span>
          </div>
        </div>
      </div>
    </div>

    <div class="row g-4">
      <!-- Medical Conditions -->
      <div class="col-md-6">
        <div class="card h-100 p-3">
          <div class="section-header"><i class="fas fa-exclamation-triangle me-2 text-warning"></i>Allergies</div>
          <p style="font-size:0.88rem;"><?= !empty($p['allergies']) ? nl2br(htmlspecialchars($p['allergies'])) : '<span class="text-muted">None recorded</span>' ?></p>

          <div class="section-header mt-3"><i class="fas fa-hospital me-2 text-info"></i>Chronic Diseases</div>
          <p style="font-size:0.88rem;"><?= !empty($p['chronic_diseases']) ? nl2br(htmlspecialchars($p['chronic_diseases'])) : '<span class="text-muted">None recorded</span>' ?></p>

          <div class="section-header mt-3"><i class="fas fa-pills me-2 text-success"></i>Current Medications</div>
          <p style="font-size:0.88rem;"><?= !empty($p['current_medications']) ? nl2br(htmlspecialchars($p['current_medications'])) : '<span class="text-muted">None recorded</span>' ?></p>
        </div>
      </div>

      <div class="col-md-6">
        <div class="card h-100 p-3">
          <div class="section-header"><i class="fas fa-clipboard-list me-2 text-primary"></i>Medical History</div>
          <p style="font-size:0.88rem;"><?= !empty($p['medical_history']) ? nl2br(htmlspecialchars($p['medical_history'])) : '<span class="text-muted">Not recorded</span>' ?></p>

          <div class="section-header mt-3"><i class="fas fa-users me-2 text-secondary"></i>Family History</div>
          <p style="font-size:0.88rem;"><?= !empty($p['family_history']) ? nl2br(htmlspecialchars($p['family_history'])) : '<span class="text-muted">Not recorded</span>' ?></p>
        </div>
      </div>
    </div>

    <!-- Consultation History -->
    <div class="card mt-4">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-700"><i class="fas fa-stethoscope me-2 text-primary"></i>Consultation History (<?= count($consultations) ?>)</h6>
      </div>
      <div class="card-body">
        <?php if (empty($consultations)): ?>
          <p class="text-muted text-center py-3">No completed consultations yet.</p>
        <?php else: ?>
          <?php foreach ($consultations as $c): ?>
            <div class="timeline-item">
              <div class="d-flex justify-content-between flex-wrap gap-1">
                <div>
                  <strong>Dr. <?= htmlspecialchars($c['doctor_name']) ?></strong>
                <span class="badge ms-1" style="background:#eff4ff;color:#0B4ACB;font-size:11px;"><?= htmlspecialchars($c['specialization'] ?? '') ?></span>
                </div>
                <small class="text-muted"><?= date('d M Y', strtotime($c['appointment_date'])) ?></small>
              </div>
              <div style="font-size:0.8rem;color:#718096;margin-top:3px;">
                <?= htmlspecialchars($c['consultation_type'] ?? 'clinic') ?> &middot; Apt# <?= htmlspecialchars($c['appointment_no']) ?>
              </div>
              <?php if (!empty($c['notes'])): ?>
                <div style="font-size:12px;margin-top:5px;background:#f8faff;padding:8px;border-radius:8px;border-left:3px solid #c7d7fc;">
                  <i class="fas fa-sticky-note me-1 text-muted"></i><?= nl2br(htmlspecialchars($c['notes'])) ?>
                </div>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>

    <!-- Records by Type -->
    <?php foreach ($record_icons as $type => $icon):
      $type_records = $records_by_type[$type] ?? [];
      if (empty($type_records)) continue;
      $labels = ['lab_report'=>'Lab Reports','blood_test'=>'Blood Tests','xray'=>'X-Rays','mri'=>'MRI Reports','ct_scan'=>'CT Scans','ultrasound'=>'Ultrasound Reports','vaccination'=>'Vaccination Records','health_assessment'=>'Health Assessments','doctor_note'=>'Doctor Notes','other'=>'Other Records'];
    ?>
    <div class="card mt-4">
      <div class="card-header bg-white">
        <h6 class="mb-0 fw-700"><i class="fas <?= $icon ?> me-2 text-primary"></i><?= $labels[$type] ?? ucfirst($type) ?> (<?= count($type_records) ?>)</h6>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover mb-0">
            <thead class="table-light">
              <tr><th>Title</th><th>Doctor</th><th>Date</th><th>Description</th><th>File</th></tr>
            </thead>
            <tbody>
              <?php foreach ($type_records as $r): ?>
                <tr>
                  <td style="font-size:0.85rem;font-weight:600;"><?= htmlspecialchars($r['title']) ?></td>
                  <td style="font-size:0.82rem;"><?= htmlspecialchars($r['doctor_name'] ?? '-') ?></td>
                  <td style="font-size:0.82rem;"><?= date('d M Y', strtotime($r['record_date'])) ?></td>
                  <td style="font-size:0.8rem;color:#718096;"><?= htmlspecialchars(substr($r['description'] ?? '', 0, 60)) ?><?= strlen($r['description'] ?? '') > 60 ? '...' : '' ?></td>
                  <td>
                    <?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;padding:2px 10px;">
                        <i class="fas fa-eye"></i> View
                      </a>
                    <?php else: ?>
                      <span class="text-muted" style="font-size:0.75rem;">No file</span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <?php endforeach; ?>

  </div>
</div>

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