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

// Handle status update
if ($_SERVER['REQUEST_METHOD']==='POST') {
    $aid      = (int)$_POST['apt_id'];
    $ns       = clean($_POST['new_status']);
    $notes    = clean($_POST['notes'] ?? '');
    $meeting  = clean($_POST['meeting_link'] ?? '');

    if (in_array($ns, ['confirmed','completed','cancelled'])) {
        $stmt = $conn->prepare("UPDATE appointments SET status=?, notes=?, meeting_link=? WHERE id=? AND doctor_id=?");
        $stmt->bind_param('sssii', $ns, $notes, $meeting, $aid, $doctor_id);
        $stmt->execute();

        // Notify patient
        $apt = $conn->query("SELECT patient_id, appointment_date, appointment_time FROM appointments WHERE id=$aid")->fetch_assoc();
        $msg = $ns==='confirmed' ? "Your appointment on ".date('d M Y', strtotime($apt['appointment_date']))." has been confirmed." : "Your appointment status updated to: $ns";
        $title = $ns==='confirmed' ? 'Appointment Confirmed' : 'Appointment Update';
        $stmt2 = $conn->prepare("INSERT INTO notifications (user_type,user_id,title,message,type,channel,created_at) VALUES ('patient',?,?,?,'appointment','in_app',NOW())");
        $stmt2->bind_param('iss', $apt['patient_id'], $title, $msg);
        $stmt2->execute();
        setFlash('success', 'Appointment updated.');
    }
    header('Location: appointments.php');
    exit;
}

$status_filter = $_GET['status'] ?? '';
$date_filter   = $_GET['date'] ?? '';
$where = "WHERE a.doctor_id=$doctor_id";
if ($status_filter) $where .= " AND a.status='$status_filter'";
if ($date_filter)   $where .= " AND a.appointment_date='$date_filter'";

$appointments = $conn->query("
    SELECT a.*, p.full_name as patient_name, p.health_id, p.phone as patient_phone, p.blood_group
    FROM appointments a JOIN patients p ON a.patient_id=p.id
    $where ORDER BY a.appointment_date DESC, a.appointment_time ASC
")->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>Appointments - 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(); ?>

    <!-- Filters -->
    <div class="doc-card p-3 mb-4">
      <form method="GET" class="row g-2 align-items-end">
        <div class="col-auto">
          <label class="form-label fw-600 mb-1" style="font-size:0.78rem;">Status</label>
          <select name="status" class="form-select form-select-sm">
            <option value="">All Status</option>
            <?php foreach(['pending','confirmed','completed','cancelled'] as $s): ?>
              <option value="<?=$s?>" <?=$status_filter===$s?'selected':''?>><?=ucfirst($s)?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-auto">
          <label class="form-label fw-600 mb-1" style="font-size:0.78rem;">Date</label>
          <input type="date" name="date" class="form-control form-control-sm" value="<?=htmlspecialchars($date_filter)?>">
        </div>
        <div class="col-auto">
          <button type="submit" class="btn btn-primary btn-sm">Filter</button>
          <a href="appointments.php" class="btn btn-outline-secondary btn-sm ms-1">Clear</a>
        </div>
      </form>
    </div>

    <!-- List -->
    <div class="doc-card">
      <div class="p-3 border-bottom"><h6 class="mb-0 fw-700">Appointments <span class="badge bg-secondary"><?=count($appointments)?></span></h6></div>
      <?php if (empty($appointments)): ?>
        <div class="p-5 text-center text-muted">
          <i class="fas fa-calendar-times fa-3x mb-3" style="opacity:0.2;"></i>
          <h5>No appointments found</h5>
        </div>
      <?php else: ?>
        <?php foreach ($appointments as $apt): ?>
          <div class="px-3 py-3" style="border-bottom:1px solid #f0f4f8;">
            <div class="d-flex align-items-start justify-content-between flex-wrap gap-2">
              <div class="d-flex align-items-start gap-3">
                <div style="width:42px;height:42px;border-radius:50%;background:#e6f5f3;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                  <i class="fas fa-user" style="color:#0B7B6E;font-size:1.1rem;"></i>
                </div>
                <div>
                  <div style="font-weight:700;font-size:0.9rem;"><?=htmlspecialchars($apt['patient_name'])?></div>
                  <div style="font-size:0.75rem;color:#718096;">
                    <?=htmlspecialchars($apt['health_id'])?> ·
                    <?=date('d M Y', strtotime($apt['appointment_date']))?> at <?=date('h:i A', strtotime($apt['appointment_time']))?>
                  </div>
                  <div style="font-size:0.72rem;color:#718096;margin-top:2px;">
                    <i class="fas fa-phone me-1"></i><?=htmlspecialchars($apt['patient_phone'] ?? '')?>
                    &nbsp;·&nbsp;<i class="fas fa-tint me-1"></i><?=htmlspecialchars($apt['blood_group'] ?? 'N/A')?>
                    &nbsp;·&nbsp;<?=htmlspecialchars($apt['consultation_type'] ?? 'clinic')?>
                  </div>
                  <?php if (!empty($apt['notes'])): ?>
                    <div style="font-size:0.78rem;color:#4a5568;margin-top:4px;background:#f7fafa;padding:4px 8px;border-radius:6px;">
                      <i class="fas fa-sticky-note me-1"></i><?=htmlspecialchars(substr($apt['notes'],0,80))?>
                    </div>
                  <?php endif; ?>
                  <?php if (!empty($apt['meeting_link'])): ?>
                    <a href="<?=htmlspecialchars($apt['meeting_link'])?>" target="_blank" class="btn btn-xs btn-success mt-1" style="font-size:0.72rem;padding:2px 8px;">
                      <i class="fas fa-video me-1"></i>Join Meeting
                    </a>
                  <?php endif; ?>
                </div>
              </div>
              <div class="d-flex align-items-center gap-2 flex-wrap">
                <span class="badge bg-<?=$status_colors[$apt['status']]?>"><?=ucfirst($apt['status'])?></span>
                <button class="btn btn-sm btn-outline-primary" style="font-size:0.75rem;" data-bs-toggle="modal" data-bs-target="#updateModal<?=$apt['id']?>">
                  <i class="fas fa-edit"></i> Update
                </button>
                <?php if ($apt['status']==='confirmed'): ?>
                  <a href="consultation-notes.php?apt_id=<?=$apt['id']?>" class="btn btn-sm btn-outline-success" style="font-size:0.75rem;">
                    <i class="fas fa-notes-medical"></i> Notes
                  </a>
                <?php endif; ?>
              </div>
            </div>
          </div>

          <!-- Update Modal -->
          <div class="modal fade" id="updateModal<?=$apt['id']?>" tabindex="-1">
            <div class="modal-dialog">
              <div class="modal-content" style="border-radius:14px;">
                <div class="modal-header"><h5 class="modal-title">Update Appointment</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <form method="POST">
                  <input type="hidden" name="apt_id" value="<?=$apt['id']?>">
                  <div class="modal-body">
                    <div class="mb-3">
                      <label class="form-label fw-600">Status</label>
                      <select name="new_status" class="form-select">
                        <?php foreach(['pending','confirmed','completed','cancelled'] as $s): ?>
                          <option value="<?=$s?>" <?=$apt['status']===$s?'selected':''?>><?=ucfirst($s)?></option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="mb-3">
                      <label class="form-label fw-600">Meeting Link (for online appointments)</label>
                      <input type="url" name="meeting_link" class="form-control" placeholder="https://meet.google.com/..." value="<?=htmlspecialchars($apt['meeting_link'] ?? '')?>">
                      <small class="text-muted">Paste Google Meet, Zoom or any video call link</small>
                    </div>
                    <div class="mb-3">
                      <label class="form-label fw-600">Notes / Instructions for Patient</label>
                      <textarea name="notes" class="form-control" rows="3" placeholder="Add consultation notes or instructions..."><?=htmlspecialchars($apt['notes'] ?? '')?></textarea>
                    </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">Save Changes</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>