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

// Save notes
if ($_SERVER['REQUEST_METHOD']==='POST') {
    $aid          = (int)$_POST['apt_id'];
    $notes        = clean($_POST['notes'] ?? '');
    $diagnosis    = clean($_POST['diagnosis'] ?? '');
    $treatment    = clean($_POST['treatment'] ?? '');
    $follow_up    = clean($_POST['follow_up'] ?? '');
    $meeting_link = clean($_POST['meeting_link'] ?? '');

    // Update appointment
    $stmt = $conn->prepare("UPDATE appointments SET notes=?, meeting_link=?, status='completed' WHERE id=? AND doctor_id=?");
    $stmt->bind_param('ssii', $notes, $meeting_link, $aid, $doctor_id);
    $stmt->execute();

    // Save to medical records
    $apt_info = $conn->query("SELECT patient_id, appointment_date FROM appointments WHERE id=$aid")->fetch_assoc();
    if ($apt_info) {
        $title = "Consultation Notes - " . date('d M Y', strtotime($apt_info['appointment_date']));
        $desc  = "Diagnosis: $diagnosis\n\nTreatment: $treatment\n\nNotes: $notes\n\nFollow-up: $follow_up";
        $doc_name = $_SESSION['doctor_name'] ?? 'Doctor';
        $stmt2 = $conn->prepare("INSERT INTO medical_records (patient_id,record_type,title,description,doctor_name,record_date,created_at) VALUES (?,'consultation',?,?,?,?,NOW())");
        $stmt2->bind_param('issss', $apt_info['patient_id'], $title, $desc, $doc_name, $apt_info['appointment_date']);
        $stmt2->execute();
    }
    setFlash('success','Consultation notes saved and linked to patient profile.');
    header('Location: appointments.php');
    exit;
}

// Load appointment details
$apt = null;
if ($apt_id) {
    $stmt = $conn->prepare("SELECT a.*, p.full_name as patient_name, p.health_id, p.blood_group, p.allergies, p.chronic_diseases, p.current_medications FROM appointments a JOIN patients p ON a.patient_id=p.id WHERE a.id=? AND a.doctor_id=?");
    $stmt->bind_param('ii', $apt_id, $doctor_id);
    $stmt->execute();
    $apt = $stmt->get_result()->fetch_assoc();
}

// All appointments needing notes
$pending_notes = $conn->query("
    SELECT a.*, p.full_name as patient_name, p.health_id
    FROM appointments a JOIN patients p ON a.patient_id=p.id
    WHERE a.doctor_id=$doctor_id AND a.status='confirmed'
    ORDER BY a.appointment_date ASC
")->fetch_all(MYSQLI_ASSOC);

$past_notes = $conn->query("
    SELECT a.*, p.full_name as patient_name
    FROM appointments a JOIN patients p ON a.patient_id=p.id
    WHERE a.doctor_id=$doctor_id AND a.status='completed' AND a.notes IS NOT NULL AND a.notes != ''
    ORDER BY a.appointment_date DESC LIMIT 10
")->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>Consultation Notes - 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 ($apt): ?>
      <!-- Consultation form -->
      <div class="row g-4">
        <!-- Patient Info -->
        <div class="col-lg-4">
          <div class="doc-card p-3">
            <h6 class="fw-700 mb-3"><i class="fas fa-user me-2 text-primary"></i>Patient Info</h6>
            <?php $info = [
              ['Patient', $apt['patient_name']],
              ['Health ID', $apt['health_id']],
              ['Blood Group', $apt['blood_group'] ?? 'N/A'],
              ['Appointment', date('d M Y', strtotime($apt['appointment_date'])) . ' at ' . date('h:i A', strtotime($apt['appointment_time']))],
              ['Type', ucfirst($apt['consultation_type'] ?? 'clinic')],
            ]; ?>
            <?php foreach ($info as [$l,$v]): ?>
              <div class="d-flex gap-2 py-2" style="border-bottom:1px solid #f0f4f8;">
                <div style="min-width:90px;font-size:0.72rem;color:#718096;font-weight:700;"><?= $l ?></div>
                <div style="font-size:0.83rem;font-weight:600;"><?= htmlspecialchars($v) ?></div>
              </div>
            <?php endforeach; ?>

            <?php if (!empty($apt['allergies'])): ?>
              <div class="mt-3 p-2" style="background:#fff5f5;border-radius:8px;border-left:3px solid #e53e3e;">
                <div style="font-size:0.68rem;font-weight:700;color:#e53e3e;"><i class="fas fa-exclamation-triangle me-1"></i>ALLERGIES</div>
                <div style="font-size:0.8rem;"><?= htmlspecialchars($apt['allergies']) ?></div>
              </div>
            <?php endif; ?>
            <?php if (!empty($apt['chronic_diseases'])): ?>
              <div class="mt-2 p-2" style="background:#fffaf0;border-radius:8px;border-left:3px solid #d69e2e;">
                <div style="font-size:0.68rem;font-weight:700;color:#d69e2e;"><i class="fas fa-hospital me-1"></i>CHRONIC</div>
                <div style="font-size:0.8rem;"><?= htmlspecialchars($apt['chronic_diseases']) ?></div>
              </div>
            <?php endif; ?>
            <?php if (!empty($apt['current_medications'])): ?>
              <div class="mt-2 p-2" style="background:#f0fff4;border-radius:8px;border-left:3px solid #38a169;">
                <div style="font-size:0.68rem;font-weight:700;color:#38a169;"><i class="fas fa-pills me-1"></i>MEDICATIONS</div>
                <div style="font-size:0.8rem;"><?= htmlspecialchars($apt['current_medications']) ?></div>
              </div>
            <?php endif; ?>

            <?php if (!empty($apt['meeting_link'])): ?>
              <a href="<?= htmlspecialchars($apt['meeting_link']) ?>" target="_blank" class="btn btn-success w-100 mt-3">
                <i class="fas fa-video me-1"></i> Join Video Call
              </a>
            <?php endif; ?>
          </div>
        </div>

        <!-- Notes Form -->
        <div class="col-lg-8">
          <div class="doc-card p-4">
            <h6 class="fw-700 mb-3"><i class="fas fa-pen-alt me-2 text-info"></i>Write Consultation Notes</h6>
            <form method="POST">
              <input type="hidden" name="apt_id" value="<?= $apt['id'] ?>">
              <div class="mb-3">
                <label class="form-label fw-600">Diagnosis</label>
                <input type="text" name="diagnosis" class="form-control" placeholder="e.g. Acute upper respiratory tract infection">
              </div>
              <div class="mb-3">
                <label class="form-label fw-600">Consultation Notes</label>
                <textarea name="notes" class="form-control" rows="4" placeholder="Patient presented with... Chief complaint... Examination findings..."><?= htmlspecialchars($apt['notes'] ?? '') ?></textarea>
              </div>
              <div class="mb-3">
                <label class="form-label fw-600">Treatment Plan</label>
                <textarea name="treatment" class="form-control" rows="3" placeholder="Prescribed medications, procedures recommended..."></textarea>
              </div>
              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label fw-600">Follow-up Recommendation</label>
                  <input type="text" name="follow_up" class="form-control" placeholder="e.g. Review in 7 days">
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">Video Meeting Link</label>
                  <input type="url" name="meeting_link" class="form-control" value="<?= htmlspecialchars($apt['meeting_link'] ?? '') ?>" placeholder="https://meet.google.com/...">
                </div>
              </div>
              <div class="d-flex gap-2 mt-4">
                <button type="submit" class="btn btn-success"><i class="fas fa-save me-1"></i>Save Notes & Complete</button>
                <a href="prescriptions.php" class="btn btn-outline-primary"><i class="fas fa-prescription-bottle-alt me-1"></i>Issue Prescription</a>
              </div>
            </form>
          </div>
        </div>
      </div>

    <?php else: ?>
      <div class="row g-4">
        <!-- Pending consultations -->
        <div class="col-lg-6">
          <div class="doc-card">
            <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-bell me-2 text-primary"></i>Confirmed Appointments <span class="badge bg-primary"><?= count($pending_notes) ?></span></h6></div>
            <?php if (empty($pending_notes)): ?>
              <div class="p-4 text-center text-muted">No confirmed appointments.</div>
            <?php else: ?>
              <?php foreach ($pending_notes as $an): ?>
                <div class="d-flex align-items-center px-3 py-3" style="border-bottom:1px solid #f0f4f8;">
                  <div class="flex-grow-1">
                    <div style="font-weight:600;font-size:0.88rem;"><?= htmlspecialchars($an['patient_name']) ?></div>
                    <div style="font-size:0.75rem;color:#718096;"><?= date('d M Y', strtotime($an['appointment_date'])) ?> at <?= date('h:i A', strtotime($an['appointment_time'])) ?></div>
                  </div>
                  <a href="?apt_id=<?= $an['id'] ?>" class="btn btn-sm btn-success" style="font-size:0.75rem;">Start</a>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>

        <!-- Past notes -->
        <div class="col-lg-6">
          <div class="doc-card">
            <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-clipboard-list me-2 text-secondary"></i>Recent Consultation Notes</h6></div>
            <?php if (empty($past_notes)): ?>
              <div class="p-4 text-center text-muted">No notes yet.</div>
            <?php else: ?>
              <?php foreach ($past_notes as $pn): ?>
                <div class="px-3 py-2" style="border-bottom:1px solid #f0f4f8;">
                  <div class="d-flex justify-content-between">
                    <div>
                      <div style="font-weight:600;font-size:0.85rem;"><?= htmlspecialchars($pn['patient_name']) ?></div>
                      <div style="font-size:0.72rem;color:#718096;"><?= date('d M Y', strtotime($pn['appointment_date'])) ?></div>
                    </div>
                  </div>
                  <div style="font-size:0.78rem;color:#4a5568;margin-top:4px;background:#f7fafa;padding:5px 8px;border-radius:6px;">
                    <?= htmlspecialchars(substr($pn['notes'],0,100)) ?>...
                  </div>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
      </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>