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

// Save prescription
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action']) && $_POST['action']==='save') {
    $patient_id  = (int)$_POST['patient_id'];
    $apt_id      = (int)($_POST['appointment_id'] ?? 0) ?: null;
    $diagnosis   = clean($_POST['diagnosis'] ?? '');
    $medicines   = clean($_POST['medicines'] ?? '');
    $instructions= clean($_POST['instructions'] ?? '');
    $follow_up   = clean($_POST['follow_up_date'] ?? '');

    // Verify patient is doctor's patient
    $access = $conn->query("SELECT COUNT(*) FROM appointments WHERE doctor_id=$doctor_id AND patient_id=$patient_id")->fetch_row()[0];
    if ($access) {
        $stmt = $conn->prepare("INSERT INTO prescriptions (patient_id,doctor_id,appointment_id,diagnosis,medicines,instructions,follow_up_date,created_at) VALUES (?,?,?,?,?,?,?,NOW())");
        $stmt->bind_param('iiisssss', $patient_id, $doctor_id, $apt_id, $diagnosis, $medicines, $instructions, $follow_up ?: null);
        $stmt->execute();

        // Also add to medical_records
        $presc_id = $conn->insert_id;
        $title = "Prescription - " . date('d M Y');
        $stmt2 = $conn->prepare("INSERT INTO medical_records (patient_id,record_type,title,description,doctor_name,record_date,created_at) VALUES (?,'prescription',?,?,?,NOW(),NOW())");
        $doc_name = $_SESSION['doctor_name'] ?? 'Doctor';
        $stmt2->bind_param('isss', $patient_id, $title, $diagnosis, $doc_name);
        $stmt2->execute();

        setFlash('success', 'Prescription saved and linked to patient profile.');
    }
    header('Location: prescriptions.php');
    exit;
}

// My patients for dropdown
$my_patients = $conn->query("SELECT DISTINCT p.id, p.full_name, p.health_id FROM appointments a JOIN patients p ON a.patient_id=p.id WHERE a.doctor_id=$doctor_id ORDER BY p.full_name")->fetch_all(MYSQLI_ASSOC);

// All prescriptions I issued
$prescriptions = $conn->query("
    SELECT pr.*, p.full_name as patient_name, p.health_id
    FROM prescriptions pr JOIN patients p ON pr.patient_id=p.id
    WHERE pr.doctor_id=$doctor_id
    ORDER BY pr.created_at 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 { 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(); ?>
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h6 class="mb-0 fw-bold"><i class="fas fa-prescription-bottle-alt me-2 text-success"></i>Prescriptions</h6>
      <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#prescModal">
        <i class="fas fa-plus me-1"></i> New Prescription
      </button>
    </div>
    <?php if (empty($prescriptions)): ?>
      <div class="doc-card p-5 text-center text-muted">
        <i class="fas fa-prescription-bottle-alt fa-4x mb-3" style="opacity:0.2;"></i>
        <h5>No prescriptions yet</h5>
        <p>Issue your first prescription using the button above.</p>
      </div>
    <?php else: ?>
      <div class="row g-3">
        <?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 align-items-start mb-2">
                <div>
                  <h6 class="mb-0 fw-700"><?= htmlspecialchars($pr['patient_name']) ?></h6>
                  <small style="color:#0B7B6E;font-size:0.72rem;"><?= htmlspecialchars($pr['health_id']) ?></small>
                </div>
                <small class="text-muted"><?= date('d M Y', strtotime($pr['created_at'])) ?></small>
              </div>
              <?php if ($pr['diagnosis']): ?>
                <div class="mb-2">
                  <span style="font-size:0.68rem;font-weight:700;color:#718096;text-transform:uppercase;">Diagnosis</span>
                  <div style="font-size:0.85rem;"><?= htmlspecialchars($pr['diagnosis']) ?></div>
                </div>
              <?php endif; ?>
              <?php if ($pr['medicines']): ?>
                <div class="mb-2">
                  <span style="font-size:0.68rem;font-weight:700;color:#718096;text-transform:uppercase;">Medicines</span>
                  <div>
                    <?php foreach (explode("\n", $pr['medicines']) as $m): ?>
                      <?php if(trim($m)): ?><span style="background:#e6f5f3;color:#0B7B6E;padding:2px 8px;border-radius:10px;font-size:0.75rem;display:inline-block;margin:2px;"><i class="fas fa-pills me-1"></i><?= htmlspecialchars(trim($m)) ?></span><?php endif; ?>
                    <?php endforeach; ?>
                  </div>
                </div>
              <?php endif; ?>
              <?php if ($pr['instructions']): ?>
                <div style="font-size:0.8rem;color:#4a5568;background:#f7fafa;padding:6px 10px;border-radius:8px;">
                  <i class="fas fa-clipboard-list me-1"></i><?= nl2br(htmlspecialchars($pr['instructions'])) ?>
                </div>
              <?php endif; ?>
              <?php if ($pr['follow_up_date']): ?>
                <div style="background:#fff3cd;border-radius:8px;padding:5px 10px;margin-top:8px;font-size:0.78rem;">
                  <i class="fas fa-calendar-alt me-1 text-warning"></i>Follow-up: <strong><?= date('d M Y', strtotime($pr['follow_up_date'])) ?></strong>
                </div>
              <?php endif; ?>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- New Prescription Modal -->
<div class="modal fade" id="prescModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content" style="border-radius:14px;">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-prescription-bottle-alt me-2 text-success"></i>New Prescription</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <input type="hidden" name="action" value="save">
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-600">Patient *</label>
              <select name="patient_id" class="form-select" required>
                <option value="">Select Patient</option>
                <?php foreach ($my_patients as $mp): ?>
                  <option value="<?= $mp['id'] ?>"><?= htmlspecialchars($mp['full_name']) ?> (<?= htmlspecialchars($mp['health_id']) ?>)</option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Follow-up Date</label>
              <input type="date" name="follow_up_date" class="form-control">
            </div>
            <div class="col-md-12">
              <label class="form-label fw-600">Diagnosis</label>
              <input type="text" name="diagnosis" class="form-control" placeholder="e.g. Upper respiratory tract infection">
            </div>
            <div class="col-md-12">
              <label class="form-label fw-600">Medicines (one per line) *</label>
              <textarea name="medicines" class="form-control" rows="5" placeholder="Amoxicillin 500mg - 1 tablet 3 times daily for 7 days&#10;Paracetamol 500mg - as needed for fever" required></textarea>
            </div>
            <div class="col-md-12">
              <label class="form-label fw-600">Instructions</label>
              <textarea name="instructions" class="form-control" rows="3" placeholder="Take medicines after meals. Drink plenty of water. Rest for 3 days."></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-success"><i class="fas fa-save me-1"></i>Save Prescription</button>
        </div>
      </form>
    </div>
  </div>
</div>

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