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

$patient_id = $_SESSION['patient_id'];

$stmt = $conn->prepare("SELECT * FROM patients WHERE id = ?");
$stmt->bind_param('i', $patient_id);
$stmt->execute();
$patient = $stmt->get_result()->fetch_assoc();

$total_apts    = $conn->query("SELECT COUNT(*) FROM appointments WHERE patient_id=$patient_id")->fetch_row()[0];
$upcoming_apts = $conn->query("SELECT COUNT(*) FROM appointments WHERE patient_id=$patient_id AND appointment_date >= CURDATE() AND status IN('pending','confirmed')")->fetch_row()[0];
$total_records = $conn->query("SELECT COUNT(*) FROM medical_records WHERE patient_id=$patient_id")->fetch_row()[0];
$total_presc   = $conn->query("SELECT COUNT(*) FROM prescriptions WHERE patient_id=$patient_id")->fetch_row()[0];

$recent_apts = $conn->query("
    SELECT a.*, d.full_name as doctor_name, s.name as specialization
    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
    ORDER BY a.appointment_date DESC LIMIT 6
")->fetch_all(MYSQLI_ASSOC);

$status_cfg = [
    'pending'   => ['color'=>'#d97706','bg'=>'#fef3c7','label'=>'Pending'],
    'confirmed' => ['color'=>'#059669','bg'=>'#d1fae5','label'=>'Confirmed'],
    'completed' => ['color'=>'#2563eb','bg'=>'#dbeafe','label'=>'Completed'],
    'cancelled' => ['color'=>'#dc2626','bg'=>'#fee2e2','label'=>'Cancelled'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dashboard - HealthLink Patient Portal</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.4.0/css/all.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <style>
    * { box-sizing: border-box; }
    body { font-family: Inter, sans-serif; background: #f0f4ff; color: #1e293b; margin: 0; }

    .page-body { padding: 20px 24px; }

    /* STAT CARDS */
    .stat-card {
      border-radius: 16px; padding: 18px 16px;
      display: flex; align-items: center; gap: 14px;
      box-shadow: 0 4px 20px rgba(11,74,203,.12);
      transition: transform .25s, box-shadow .25s;
      position: relative; overflow: hidden;
    }
    .stat-card:hover { transform: translateY(-4px); box-shadow: 0 10px 30px rgba(11,74,203,.2); }
    .stat-card::after { content:''; position:absolute; right:-20px; top:-20px; width:80px; height:80px; border-radius:50%; background:rgba(255,255,255,.12); }
    .stat-icon { width:46px; height:46px; border-radius:14px; background:rgba(255,255,255,.22); display:grid; place-items:center; flex-shrink:0; font-size:20px; color:#fff; }
    .stat-num  { font-size:26px; font-weight:800; color:#fff; line-height:1; }
    .stat-lbl  { font-size:11px; color:rgba(255,255,255,.8); margin-top:3px; font-weight:500; }

    /* CARDS */
    .dash-card { background:#fff; border:1px solid #e8edf8; border-radius:16px; overflow:hidden; box-shadow:0 2px 12px rgba(11,74,203,.07); }
    .dash-card-header { padding:14px 18px; border-bottom:1px solid #f1f5fd; display:flex; align-items:center; justify-content:space-between; background:#fff; }
    .dash-card-header h6 { margin:0; font-size:13px; font-weight:700; color:#0f172a; display:flex; align-items:center; gap:8px; }
    .dash-card-header h6 i { color:#0B4ACB; }
    .view-btn { font-size:12px; color:#0B4ACB; text-decoration:none; font-weight:600; background:#eff4ff; border:1px solid #c7d7fc; padding:4px 12px; border-radius:20px; transition:all .2s; white-space:nowrap; }
    .view-btn:hover { background:#0B4ACB; color:#fff; }

    /* APT ROW */
    .apt-row { display:flex; align-items:center; gap:12px; padding:11px 18px; border-bottom:1px solid #f8faff; transition:background .15s; flex-wrap:wrap; }
    .apt-row:last-child { border-bottom:none; }
    .apt-row:hover { background:#f8faff; }
    .apt-avatar { width:38px; height:38px; border-radius:12px; background:linear-gradient(135deg,#eff4ff,#dbeafe); border:1px solid #c7d7fc; display:grid; place-items:center; flex-shrink:0; }
    .apt-avatar i { color:#0B4ACB; font-size:15px; }
    .apt-name { font-size:13px; font-weight:600; color:#0f172a; }
    .apt-meta { font-size:11px; color:#94a3b8; margin-top:2px; }
    .s-pill { font-size:11px; font-weight:600; padding:3px 10px; border-radius:20px; white-space:nowrap; }

    /* QUICK ACTIONS */
    .qa-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:10px; padding:16px; }
    .qa-btn { display:flex; flex-direction:column; align-items:center; gap:6px; padding:14px 8px; border-radius:12px; text-decoration:none; font-size:11px; font-weight:600; color:#334155; background:#f8faff; border:1.5px solid #e2eafc; transition:all .22s; text-align:center; }
    .qa-btn i { font-size:20px; }
    .qa-btn:hover { transform:translateY(-3px); color:#fff; box-shadow:0 6px 20px rgba(11,74,203,.25); }
    .qa-btn.c1 i{color:#0B4ACB;} .qa-btn.c1:hover{background:linear-gradient(135deg,#0B4ACB,#3B63E6);border-color:#0B4ACB;}
    .qa-btn.c2 i{color:#7c3aed;} .qa-btn.c2:hover{background:linear-gradient(135deg,#7c3aed,#a855f7);border-color:#7c3aed;}
    .qa-btn.c3 i{color:#0891b2;} .qa-btn.c3:hover{background:linear-gradient(135deg,#0891b2,#06b6d4);border-color:#0891b2;}
    .qa-btn.c4 i{color:#059669;} .qa-btn.c4:hover{background:linear-gradient(135deg,#059669,#10b981);border-color:#059669;}
    .qa-btn.c5 i{color:#d97706;} .qa-btn.c5:hover{background:linear-gradient(135deg,#d97706,#f59e0b);border-color:#d97706;}
    .qa-btn.c6 i{color:#dc2626;} .qa-btn.c6:hover{background:linear-gradient(135deg,#dc2626,#ef4444);border-color:#dc2626;}

    /* PROFILE ROWS */
    .p-row { display:flex; align-items:center; gap:10px; padding:10px 18px; border-bottom:1px solid #f8faff; }
    .p-row:last-child { border-bottom:none; }
    .p-ico { width:32px; height:32px; border-radius:9px; display:grid; place-items:center; font-size:13px; flex-shrink:0; }
    .p-lbl { font-size:10px; color:#94a3b8; text-transform:uppercase; letter-spacing:.5px; }
    .p-val { font-size:12px; font-weight:600; color:#0f172a; }

    /* HEALTH SCORE */
    .score-wrap { padding:20px 16px; text-align:center; }
    .score-ring { width:100px; height:100px; border-radius:50%; background:conic-gradient(#0B4ACB 0% 78%,#e8edf8 78% 100%); display:grid; place-items:center; margin:0 auto 12px; position:relative; }
    .score-ring::before { content:''; position:absolute; inset:11px; border-radius:50%; background:#fff; }
    .score-ring span { position:relative; z-index:1; font-size:22px; font-weight:800; color:#0B4ACB; }

    /* WELCOME BANNER */
    .welcome-banner { background:linear-gradient(135deg,#0B4ACB 0%,#245CDB 50%,#3B63E6 100%); border-radius:18px; padding:22px 24px; display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; position:relative; overflow:hidden; box-shadow:0 8px 30px rgba(11,74,203,.3); gap:12px; }
    .welcome-banner::before { content:''; position:absolute; right:-40px; top:-40px; width:180px; height:180px; border-radius:50%; background:rgba(255,255,255,.07); }
    .wb-title { font-size:18px; font-weight:800; color:#fff; margin-bottom:4px; }
    .wb-sub   { font-size:12px; color:rgba(255,255,255,.75); }
    .wb-hid   { display:inline-flex; align-items:center; gap:6px; background:rgba(255,255,255,.15); border:1px solid rgba(255,255,255,.3); color:#fff; font-size:11px; font-weight:600; padding:4px 12px; border-radius:20px; margin-top:8px; }
    .wb-btn   { background:#fff; color:#0B4ACB; font-size:12px; font-weight:700; padding:9px 18px; border-radius:10px; text-decoration:none; box-shadow:0 4px 14px rgba(0,0,0,.15); transition:all .2s; position:relative; z-index:1; white-space:nowrap; flex-shrink:0; }
    .wb-btn:hover { transform:translateY(-2px); color:#0B4ACB; }

    .empty-state { text-align:center; padding:30px 16px; color:#94a3b8; }
    .empty-state i { font-size:28px; margin-bottom:8px; opacity:.4; display:block; }
    .empty-state a { color:#0B4ACB; font-weight:600; }
    .tb-btn { display:flex; align-items:center; gap:7px; padding:9px 18px; border-radius:10px; font-size:13px; font-weight:600; text-decoration:none; border:none; cursor:pointer; transition:all .2s; }
    .tb-btn.primary { background:linear-gradient(135deg,#0B4ACB,#3B63E6); color:#fff; box-shadow:0 4px 14px rgba(11,74,203,.3); }
    .tb-btn.primary:hover { opacity:.9; }

    /* RESPONSIVE */
    @media(max-width:768px) {
      .page-body { padding: 12px; }
      .welcome-banner { flex-direction:column; align-items:flex-start; padding:18px; }
      .wb-btn { width:100%; text-align:center; justify-content:center; display:flex; }
      .wb-title { font-size:16px; }
      .stat-num { font-size:22px; }
      .qa-grid { grid-template-columns:repeat(3,1fr); gap:8px; padding:12px; }
      .qa-btn { padding:12px 6px; font-size:10px; }
      .qa-btn i { font-size:18px; }
      .apt-row { padding:10px 14px; }
      .apt-meta { font-size:10px; }
      .s-pill { font-size:10px; padding:2px 8px; }
    }
    @media(max-width:480px) {
      .stat-card { padding:14px 12px; gap:10px; }
      .stat-icon { width:38px; height:38px; font-size:16px; }
      .stat-num { font-size:20px; }
      .stat-lbl { font-size:10px; }
      .qa-grid { grid-template-columns:repeat(3,1fr); }
    }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>

<div class="main-content">
<?php $page_title = 'Patient Dashboard'; include 'topbar.php'; ?>

  <div class="page-body">
    <?php displayFlash(); ?>

    <!-- WELCOME BANNER -->
    <div class="welcome-banner">
      <div>
        <div class="wb-title">Welcome back, <?= htmlspecialchars(explode(' ', $patient['full_name'])[0]) ?></div>
        <div class="wb-sub">Here's your health summary for today.</div>
        <div class="wb-hid"><i class="fas fa-id-card"></i> <?= htmlspecialchars($patient['health_id']) ?></div>
      </div>
      <a href="book-appointment.php" class="wb-btn"><i class="fas fa-calendar-plus me-2"></i>New Appointment</a>
    </div>

    <!-- STAT CARDS -->
    <div class="row g-3 mb-4">
      <?php
      $stats = [
        ['num'=>$total_apts,    'lbl'=>'Total Appointments', 'icon'=>'fa-calendar-alt',           'grad'=>'linear-gradient(135deg,#0B4ACB,#3B63E6)'],
        ['num'=>$upcoming_apts, 'lbl'=>'Upcoming',           'icon'=>'fa-clock',                  'grad'=>'linear-gradient(135deg,#7c3aed,#a855f7)'],
        ['num'=>$total_records, 'lbl'=>'Health Records',     'icon'=>'fa-file-medical',            'grad'=>'linear-gradient(135deg,#0891b2,#06b6d4)'],
        ['num'=>$total_presc,   'lbl'=>'Prescriptions',      'icon'=>'fa-prescription-bottle-alt', 'grad'=>'linear-gradient(135deg,#059669,#10b981)'],
      ];
      foreach($stats as $s): ?>
      <div class="col-6 col-sm-6 col-xl-3">
        <div class="stat-card" style="background:<?=$s['grad']?>;">
          <div class="stat-icon"><i class="fas <?=$s['icon']?>"></i></div>
          <div>
            <div class="stat-num"><?=$s['num']?></div>
            <div class="stat-lbl"><?=$s['lbl']?></div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>

    <div class="row g-4">

      <!-- LEFT -->
      <div class="col-lg-8">

        <!-- RECENT APPOINTMENTS -->
        <div class="dash-card mb-4">
          <div class="dash-card-header">
            <h6><i class="fas fa-calendar-check"></i> Recent Appointments</h6>
            <a href="appointments.php" class="view-btn">View All</a>
          </div>
          <?php if (empty($recent_apts)): ?>
            <div class="empty-state">
              <i class="fas fa-calendar-times"></i>
              <p>No appointments yet. <a href="doctors.php">Book one now</a></p>
            </div>
          <?php else: ?>
            <?php foreach ($recent_apts as $apt):
              $sc = $status_cfg[$apt['status']] ?? ['color'=>'#64748b','bg'=>'#f1f5f9','label'=>ucfirst($apt['status'])];
            ?>
            <div class="apt-row">
              <div class="apt-avatar"><i class="fas fa-user-md"></i></div>
              <div class="flex-grow-1">
                <div class="apt-name">Dr. <?= htmlspecialchars($apt['doctor_name']) ?></div>
                <div class="apt-meta">
                  <i class="fas fa-stethoscope me-1"></i><?= htmlspecialchars($apt['specialization'] ?? 'General') ?>
                  &nbsp;&middot;&nbsp;<i class="fas fa-calendar me-1"></i><?= date('d M Y', strtotime($apt['appointment_date'])) ?>
                  <?php if(!empty($apt['appointment_time'])): ?>
                    &nbsp;&middot;&nbsp;<i class="fas fa-clock me-1"></i><?= date('h:i A', strtotime($apt['appointment_time'])) ?>
                  <?php endif; ?>
                </div>
              </div>
              <span class="s-pill" style="color:<?=$sc['color']?>;background:<?=$sc['bg']?>;"><?=$sc['label']?></span>
            </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>

        <!-- QUICK ACTIONS -->
        <div class="dash-card">
          <div class="dash-card-header">
            <h6><i class="fas fa-bolt"></i> Quick Actions</h6>
          </div>
          <div class="qa-grid">
            <a href="doctors.php"          class="qa-btn c1"><i class="fas fa-user-md"></i>Find Doctor</a>
            <a href="book-appointment.php" class="qa-btn c2"><i class="fas fa-calendar-plus"></i>Book Apt</a>
            <a href="health-records.php"   class="qa-btn c3"><i class="fas fa-file-medical"></i>Records</a>
            <a href="prescriptions.php"    class="qa-btn c4"><i class="fas fa-prescription-bottle-alt"></i>Prescriptions</a>
            <a href="lab-reports.php"      class="qa-btn c5"><i class="fas fa-flask"></i>Lab Reports</a>
            <a href="profile.php"          class="qa-btn c6"><i class="fas fa-user-edit"></i>My Profile</a>
          </div>
        </div>

      </div>

      <!-- RIGHT -->
      <div class="col-lg-4">

        <!-- HEALTH SCORE -->
        <div class="dash-card mb-4">
          <div class="dash-card-header">
            <h6><i class="fas fa-heartbeat"></i> Health Score</h6>
          </div>
          <div class="score-wrap">
            <div class="score-ring"><span>78%</span></div>
            <div style="font-size:14px;font-weight:700;color:#0f172a;margin-bottom:4px;">Good Health Status</div>
            <div style="font-size:12px;color:#94a3b8;margin-bottom:16px;">Complete your profile to improve score</div>
            <a href="profile.php" class="tb-btn primary" style="display:inline-flex;justify-content:center;">
              <i class="fas fa-arrow-up me-2"></i>Improve Score
            </a>
          </div>
        </div>

        <!-- PROFILE SUMMARY -->
        <div class="dash-card">
          <div class="dash-card-header">
            <h6><i class="fas fa-id-card"></i> Profile Summary</h6>
            <a href="profile.php" class="view-btn">Edit</a>
          </div>
          <?php
          $pf = [
            ['Blood Group',      'blood_group',            'fa-tint',               '#0B4ACB','#eff4ff'],
            ['Date of Birth',    'date_of_birth',          'fa-birthday-cake',      '#7c3aed','#f5f3ff'],
            ['Allergies',        'allergies',              'fa-exclamation-circle', '#d97706','#fffbeb'],
            ['Chronic Diseases', 'chronic_diseases',       'fa-heartbeat',          '#dc2626','#fef2f2'],
            ['Emergency Contact','emergency_contact_name', 'fa-phone-alt',          '#059669','#f0fdf4'],
          ];
          foreach($pf as [$lbl,$key,$ico,$clr,$bg]): ?>
          <div class="p-row">
            <div class="p-ico" style="background:<?=$bg?>;color:<?=$clr?>;"><i class="fas <?=$ico?>"></i></div>
            <div>
              <div class="p-lbl"><?=$lbl?></div>
              <div class="p-val">
                <?php if(!empty($patient[$key])): ?>
                  <?= $key==='date_of_birth' ? date('d M Y',strtotime($patient[$key])) : htmlspecialchars($patient[$key]) ?>
                <?php else: ?>
                  <span style="color:#cbd5e1;font-weight:400;font-size:12px;">Not set</span>
                <?php endif; ?>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>

      </div>
    </div>
  </div>
</div>

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