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

$patient_id = $_SESSION['patient_id'];

// Fetch all prescriptions linked to this patient
$prescriptions = $conn->query("
    SELECT p.*, d.full_name as doctor_name, s.name as specialization, a.appointment_date, a.appointment_no
    FROM prescriptions p
    LEFT JOIN doctors d ON p.doctor_id = d.id
    LEFT JOIN specializations s ON d.specialization_id = s.id
    LEFT JOIN appointments a ON p.appointment_id = a.id
    WHERE p.patient_id = $patient_id
    ORDER BY p.created_at DESC
")->fetch_all(MYSQLI_ASSOC);

// Also get prescriptions from medical_records table
$record_prescriptions = $conn->query("
    SELECT * FROM medical_records
    WHERE patient_id = $patient_id AND record_type = 'prescription'
    ORDER BY record_date DESC
")->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Prescriptions - 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,0.07); }
    .top-bar { display:none; }
    .page-body { padding: 20px 24px; }
    @media(max-width:768px){ .page-body{ padding:12px; } }
    .presc-card { border-left: 4px solid #0B4ACB; transition: transform 0.2s; }
    .presc-card:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(11,74,203,.12); }
    .medicine-badge { background: #eff4ff; color: #0B4ACB; padding: 3px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; display: inline-block; margin: 2px; border: 1px solid #c7d7fc; }
    .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; cursor:pointer; transition:all .2s; text-decoration:none; display:inline-flex; align-items:center; gap:6px; }
    .btn-blue:hover { opacity:.9; transform:translateY(-1px); }
    .sec-title { font-size:13px; font-weight:700; color:#0f172a; margin-bottom:14px; display:flex; align-items:center; gap:8px; }
    .sec-title i { color:#0B4ACB; }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main-content">
<?php $page_title = 'Prescriptions'; include 'topbar.php'; ?>
  <div class="page-body">
    <?php displayFlash(); ?>

    <?php if (empty($prescriptions) && empty($record_prescriptions)): ?>
      <div class="card p-5 text-center text-muted">
        <i class="fas fa-prescription-bottle-alt fa-4x mb-3" style="color:#0B7B6E;opacity:0.3;"></i>
        <h5>No Prescriptions Found</h5>
        <p>Your prescriptions from doctors will appear here automatically after consultations.</p>
        <a href="doctors.php" class="btn-blue mt-2"><i class="fas fa-calendar-plus"></i> Book a Consultation</a>
      </div>
    <?php else: ?>

      <!-- Doctor Prescriptions -->
      <?php if (!empty($prescriptions)): ?>
        <h6 class="sec-title"><i class="fas fa-user-md"></i>Doctor Issued Prescriptions</h6>
        <div class="row g-3 mb-4">
          <?php foreach ($prescriptions as $presc): ?>
            <div class="col-md-6">
              <div class="card presc-card p-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                  <div>
                    <h6 class="mb-0 fw-700">Dr. <?= htmlspecialchars($presc['doctor_name'] ?? 'Unknown') ?></h6>
                    <small class="text-muted"><?= htmlspecialchars($presc['specialization'] ?? '') ?></small>
                  </div>
                  <div class="text-end">
                    <small class="text-muted"><?= $presc['appointment_date'] ? date('d M Y', strtotime($presc['appointment_date'])) : date('d M Y', strtotime($presc['created_at'])) ?></small>
                    <?php if ($presc['appointment_no']): ?>
                      <div><span class="badge bg-secondary" style="font-size:0.65rem;"><?= htmlspecialchars($presc['appointment_no']) ?></span></div>
                    <?php endif; ?>
                  </div>
                </div>

                <?php if (!empty($presc['diagnosis'])): ?>
                  <div class="mb-2">
                    <span style="font-size:0.75rem;color:#718096;font-weight:600;">DIAGNOSIS</span>
                    <div style="font-size:0.85rem;"><?= htmlspecialchars($presc['diagnosis']) ?></div>
                  </div>
                <?php endif; ?>

                <?php if (!empty($presc['medicines'])): ?>
                  <div class="mb-2">
                    <span style="font-size:0.75rem;color:#718096;font-weight:600;">MEDICINES</span>
                    <div>
                      <?php foreach (explode("\n", $presc['medicines']) as $med): ?>
                        <?php if (trim($med)): ?>
                          <span class="medicine-badge"><i class="fas fa-pills me-1"></i><?= htmlspecialchars(trim($med)) ?></span>
                        <?php endif; ?>
                      <?php endforeach; ?>
                    </div>
                  </div>
                <?php endif; ?>

                <?php if (!empty($presc['instructions'])): ?>
                  <div class="mb-2">
                    <span style="font-size:0.75rem;color:#718096;font-weight:600;">INSTRUCTIONS</span>
                    <div style="font-size:0.82rem;color:#4a5568;"><?= nl2br(htmlspecialchars($presc['instructions'])) ?></div>
                  </div>
                <?php endif; ?>

                <?php if (!empty($presc['follow_up_date'])): ?>
                  <div style="background:#fff3cd;border-radius:8px;padding:6px 10px;margin-top:8px;">
                    <i class="fas fa-calendar-alt text-warning me-1"></i>
                    <span style="font-size:0.8rem;">Follow-up: <strong><?= date('d M Y', strtotime($presc['follow_up_date'])) ?></strong></span>
                  </div>
                <?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <!-- Uploaded Prescription Records -->
      <?php if (!empty($record_prescriptions)): ?>
        <h6 class="sec-title"><i class="fas fa-upload"></i>Uploaded Prescriptions</h6>
        <div class="row g-3">
          <?php foreach ($record_prescriptions as $r): ?>
            <div class="col-md-6">
              <div class="card presc-card p-3">
                <div class="d-flex justify-content-between align-items-start">
                  <div>
                    <h6 class="mb-1 fw-700"><i class="fas fa-prescription-bottle-alt me-1 text-success"></i><?= htmlspecialchars($r['title']) ?></h6>
                    <?php if ($r['doctor_name']): ?>
                      <small class="text-muted"><i class="fas fa-user-md me-1"></i>Dr. <?= htmlspecialchars($r['doctor_name']) ?></small>
                    <?php endif; ?>
                  </div>
                  <small class="text-muted"><?= date('d M Y', strtotime($r['record_date'])) ?></small>
                </div>
                <?php if ($r['description']): ?>
                  <p style="font-size:0.82rem;color:#718096;margin-top:8px;margin-bottom:8px;"><?= htmlspecialchars($r['description']) ?></p>
                <?php endif; ?>
                <?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 File
                  </a>
                <?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

    <?php endif; ?>
  </div>
</div>

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