<?php
require_once '../config.php';
requireDoctor();
$doctor_id = $_SESSION['doctor_id'];

$view_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Patient detail view
if ($view_id) {
    $stmt = $conn->prepare("SELECT * FROM patients WHERE id=?");
    $stmt->bind_param('i', $view_id);
    $stmt->execute();
    $patient = $stmt->get_result()->fetch_assoc();

    // Verify doctor has access (has at least one appointment with this patient)
    $access = $conn->query("SELECT COUNT(*) FROM appointments WHERE doctor_id=$doctor_id AND patient_id=$view_id")->fetch_row()[0];
    if (!$access) { setFlash('error','Access denied.'); header('Location: patients.php'); exit; }

    $records    = $conn->query("SELECT * FROM medical_records WHERE patient_id=$view_id ORDER BY record_date DESC")->fetch_all(MYSQLI_ASSOC);
    $apt_history = $conn->query("SELECT a.*, d.full_name as doctor_name FROM appointments a JOIN doctors d ON a.doctor_id=d.id WHERE a.patient_id=$view_id ORDER BY a.appointment_date DESC")->fetch_all(MYSQLI_ASSOC);
    $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=$view_id ORDER BY p.created_at DESC")->fetch_all(MYSQLI_ASSOC);
}

// Patients list
$patients = $conn->query("
    SELECT p.*, COUNT(a.id) as total_apts, MAX(a.appointment_date) as last_visit
    FROM appointments a JOIN patients p ON a.patient_id=p.id
    WHERE a.doctor_id=$doctor_id
    GROUP BY p.id ORDER BY last_visit DESC
")->fetch_all(MYSQLI_ASSOC);

$status_colors = ['pending'=>'warning','confirmed'=>'success','completed'=>'info','cancelled'=>'danger'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Patients - 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 { font-family: Inter, sans-serif; background: #f0f4ff; margin: 0; }
    .doc-body { padding: 20px 24px; }
    .doc-card { background:#fff; border:1px solid #e8edf8; border-radius:14px; overflow:hidden; box-shadow:0 2px 12px rgba(11,74,203,.07); }
    @media(max-width:768px) { .doc-body { padding: 12px; } }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<?php include 'topbar.php'; ?>
<div class="doc-main">
  <div class="doc-body">
    <?php displayFlash(); ?>

    <?php if ($view_id && isset($patient)): ?>
      <!-- Patient Detail View -->
      <!-- Profile -->
      <div class="doc-card mb-4 p-4">
        <div class="d-flex align-items-center gap-4 flex-wrap mb-3">
          <div style="width:70px;height:70px;border-radius:50%;background:#e6f5f3;display:flex;align-items:center;justify-content:center;">
            <i class="fas fa-user-circle" style="font-size:2.5rem;color:#0B7B6E;"></i>
          </div>
          <div>
            <h4 class="mb-1 fw-800"><?= htmlspecialchars($patient['full_name']) ?></h4>
            <span style="background:#e6f5f3;color:#0B7B6E;border-radius:20px;padding:3px 12px;font-size:0.78rem;font-weight:700;"><?= htmlspecialchars($patient['health_id']) ?></span>
          </div>
        </div>
        <div class="row g-2">
          <?php $info = [
            ['DOB', $patient['date_of_birth'] ? date('d M Y', strtotime($patient['date_of_birth'])) : 'N/A'],
            ['Gender', ucfirst($patient['gender'] ?? 'N/A')],
            ['Blood Group', $patient['blood_group'] ?? 'N/A'],
            ['Phone', $patient['phone']],
            ['Allergies', $patient['allergies'] ?? 'None'],
            ['Chronic Diseases', $patient['chronic_diseases'] ?? 'None'],
            ['Current Medications', $patient['current_medications'] ?? 'None'],
            ['Emergency Contact', ($patient['emergency_contact_name'] ?? '') . ' ' . ($patient['emergency_contact_phone'] ?? '')],
          ]; ?>
          <?php foreach ($info as [$label,$val]): ?>
            <div class="col-md-3 col-6">
              <div style="background:#f7fafa;border-radius:10px;padding:10px 12px;">
                <div style="font-size:0.68rem;color:#718096;font-weight:700;text-transform:uppercase;"><?= $label ?></div>
                <div style="font-size:0.85rem;font-weight:600;"><?= htmlspecialchars($val) ?></div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- Tabs -->
      <ul class="nav nav-tabs mb-3">
        <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab-records"><i class="fas fa-clipboard-list me-1"></i>Medical Records</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-history"><i class="fas fa-stethoscope me-1"></i>Visit History</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-presc"><i class="fas fa-pills me-1"></i>Prescriptions</a></li>
      </ul>
      <div class="tab-content">
        <!-- Medical Records -->
        <div class="tab-pane fade show active" id="tab-records">
          <div class="doc-card">
            <?php if (empty($records)): ?>
              <div class="p-4 text-center text-muted">No medical records uploaded.</div>
            <?php else: ?>
              <?php foreach ($records as $r): ?>
                <div class="d-flex align-items-center gap-3 px-3 py-2" style="border-bottom:1px solid #f0f4f8;">
                  <div style="width:36px;height:36px;border-radius:8px;background:#e6f5f3;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                    <i class="fas fa-file-medical" style="color:#0B7B6E;"></i>
                  </div>
                  <div class="flex-grow-1">
                    <div style="font-weight:600;font-size:0.88rem;"><?= htmlspecialchars($r['title']) ?></div>
                    <div style="font-size:0.75rem;color:#718096;"><?= ucfirst(str_replace('_',' ',$r['record_type'])) ?> · <?= date('d M Y', strtotime($r['record_date'])) ?></div>
                  </div>
                  <?php if ($r['file_path']): ?>
                    <a href="<?= SITE_URL ?>/<?= $r['file_path'] ?>" target="_blank" class="btn btn-xs btn-outline-primary" style="font-size:0.72rem;padding:2px 8px;">View</a>
                  <?php endif; ?>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
        <!-- Visit History -->
        <div class="tab-pane fade" id="tab-history">
          <div class="doc-card">
            <?php foreach ($apt_history as $ah): ?>
              <div class="px-3 py-2" style="border-bottom:1px solid #f0f4f8;">
                <div class="d-flex justify-content-between">
                  <div>
                    <div style="font-size:0.88rem;font-weight:600;"><?= date('d M Y', strtotime($ah['appointment_date'])) ?> at <?= date('h:i A', strtotime($ah['appointment_time'])) ?></div>
                    <div style="font-size:0.75rem;color:#718096;">Dr. <?= htmlspecialchars($ah['doctor_name']) ?> · <?= htmlspecialchars($ah['consultation_type'] ?? 'clinic') ?></div>
                    <?php if ($ah['notes']): ?><div style="font-size:0.78rem;color:#4a5568;margin-top:3px;"><i class="fas fa-sticky-note me-1"></i><?= htmlspecialchars($ah['notes']) ?></div><?php endif; ?>
                  </div>
                  <span class="badge bg-<?= $status_colors[$ah['status']] ?>"><?= ucfirst($ah['status']) ?></span>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
        <!-- Prescriptions -->
        <div class="tab-pane fade" id="tab-presc">
          <div class="row g-3">
            <?php if (empty($prescriptions)): ?>
              <div class="col-12 text-center text-muted py-4">No prescriptions yet.</div>
            <?php else: ?>
              <?php foreach ($prescriptions as $pr): ?>
                <div class="col-md-6">
                  <div class="doc-card p-3" style="border-left:4px solid #0B7B6E;">
                    <div class="d-flex justify-content-between mb-2">
                      <strong>Dr. <?= htmlspecialchars($pr['doctor_name'] ?? '') ?></strong>
                      <small class="text-muted"><?= date('d M Y', strtotime($pr['created_at'])) ?></small>
                    </div>
                    <?php if ($pr['diagnosis']): ?><div style="font-size:0.8rem;"><b>Diagnosis:</b> <?= htmlspecialchars($pr['diagnosis']) ?></div><?php endif; ?>
                    <?php if ($pr['medicines']): ?><div style="font-size:0.8rem;margin-top:4px;"><b>Medicines:</b> <?= htmlspecialchars($pr['medicines']) ?></div><?php endif; ?>
                  </div>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
      </div>

    <?php else: ?>
      <!-- Patients List -->
      <div class="doc-card">
        <div class="p-3 border-bottom"><h6 class="mb-0 fw-700">All My Patients <span class="badge bg-secondary"><?= count($patients) ?></span></h6></div>
        <?php if (empty($patients)): ?>
          <div class="p-5 text-center text-muted">
            <i class="fas fa-users fa-3x mb-3" style="opacity:0.2;"></i>
            <h5>No patients yet</h5>
            <p>Patients who book appointments will appear here.</p>
          </div>
        <?php else: ?>
          <?php foreach ($patients as $p): ?>
            <div class="d-flex align-items-center px-3 py-3" style="border-bottom:1px solid #f0f4f8;">
              <div style="width:40px;height:40px;border-radius:50%;background:#e6f5f3;display:flex;align-items:center;justify-content:center;margin-right:14px;">
                <i class="fas fa-user" style="color:#0B7B6E;"></i>
              </div>
              <div class="flex-grow-1">
                <div style="font-weight:600;font-size:0.88rem;"><?= htmlspecialchars($p['full_name']) ?></div>
                <div style="font-size:0.75rem;color:#718096;"><?= htmlspecialchars($p['health_id']) ?> · <?= $p['total_apts'] ?> visits · Last: <?= date('d M Y', strtotime($p['last_visit'])) ?></div>
              </div>
              <a href="?id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-primary" style="font-size:0.78rem;">View Records</a>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    <?php endif; ?>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>