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

$doctor_id = $_SESSION['doctor_id'];

$stmt = $conn->prepare("SELECT d.*, s.name as specialization_name FROM doctors d LEFT JOIN specializations s ON d.specialization_id = s.id WHERE d.id = ?");
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$doctor = $stmt->get_result()->fetch_assoc();

// Stats
$total_consultations  = $conn->query("SELECT COUNT(*) FROM appointments WHERE doctor_id=$doctor_id AND status='completed'")->fetch_row()[0];
$today_appointments   = $conn->query("SELECT COUNT(*) FROM appointments WHERE doctor_id=$doctor_id AND appointment_date=CURDATE()")->fetch_row()[0];
$pending_appointments = $conn->query("SELECT COUNT(*) FROM appointments WHERE doctor_id=$doctor_id AND status='pending'")->fetch_row()[0];
$total_patients       = $conn->query("SELECT COUNT(DISTINCT patient_id) FROM appointments WHERE doctor_id=$doctor_id")->fetch_row()[0];
$r = $conn->query("SELECT COALESCE(AVG(r.rating),0) FROM reviews r JOIN appointments a ON r.appointment_id=a.id WHERE a.doctor_id=$doctor_id");
$avg_rating = number_format($r->fetch_row()[0], 1);
$month_earnings = $conn->query("SELECT COALESCE(SUM(consultation_fee),0) FROM appointments WHERE doctor_id=$doctor_id AND status='completed' AND MONTH(appointment_date)=MONTH(CURDATE())")->fetch_row()[0];

// Today's schedule
$today_apts = $conn->query("
    SELECT a.*, p.full_name as patient_name, p.health_id, p.phone as patient_phone
    FROM appointments a JOIN patients p ON a.patient_id = p.id
    WHERE a.doctor_id=$doctor_id AND a.appointment_date=CURDATE()
    ORDER BY a.appointment_time
")->fetch_all(MYSQLI_ASSOC);

// Pending requests
$pending_reqs = $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='pending'
    ORDER BY a.appointment_date ASC LIMIT 5
")->fetch_all(MYSQLI_ASSOC);

// Handle appointment status update
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['apt_id'], $_POST['new_status'])) {
    $aid = (int)$_POST['apt_id'];
    $ns  = clean($_POST['new_status']);
    if (in_array($ns, ['confirmed','completed','cancelled'])) {
        $conn->query("UPDATE appointments SET status='$ns' WHERE id=$aid AND doctor_id=$doctor_id");
    }
    header('Location: dashboard.php');
    exit;
}

$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>Doctor Dashboard - 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(); ?>

    <!-- Stats -->
    <div class="row g-3 mb-4">
      <?php $stats = [
        ['Today',         'fa-calendar-day',   $today_appointments,              'primary', '#3182ce'],
        ['Total Patients','fa-users',           $total_patients,                  'success', '#38a169'],
        ['Consultations', 'fa-stethoscope',     $total_consultations,             'info',    '#0B7B6E'],
        ['Avg Rating',    'fa-star',            $avg_rating.' / 5',               'warning', '#d69e2e'],
        ['Month Earnings','fa-rupee-sign',      'Rs.'.number_format($month_earnings),'purple','#805ad5'],
      ]; ?>
      <?php foreach ($stats as [$label,$icon,$val,$color,$hex]): ?>
        <div class="col-6 col-xl">
          <div class="doc-card p-3" style="border-left:4px solid <?= $hex ?>;">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <div style="font-size:1.5rem;font-weight:800;color:#0D2340;"><?= $val ?></div>
                <div style="font-size:0.75rem;color:#718096;"><?= $label ?></div>
              </div>
              <i class="fas <?= $icon ?>" style="font-size:1.4rem;color:<?= $hex ?>;opacity:0.7;"></i>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

    <div class="row g-4">
      <!-- Today's Schedule -->
      <div class="col-lg-7">
        <div class="doc-card">
          <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
            <h6 class="mb-0 fw-700"><i class="fas fa-calendar-day me-2 text-primary"></i>Today's Schedule</h6>
            <a href="appointments.php" class="btn btn-sm btn-outline-primary">View All</a>
          </div>
          <?php if (empty($today_apts)): ?>
            <div class="p-4 text-center text-muted">
              <i class="fas fa-calendar-times fa-2x mb-2"></i>
              <p class="mb-0">No appointments today</p>
            </div>
          <?php else: ?>
            <?php foreach ($today_apts as $apt): ?>
              <div class="d-flex align-items-center px-3 py-3" style="border-bottom:1px solid #f0f4f8;">
                <div style="min-width:65px;font-size:0.78rem;font-weight:700;color:#0B7B6E;"><?= date('h:i A', strtotime($apt['appointment_time'])) ?></div>
                <div class="flex-grow-1">
                  <div style="font-weight:600;font-size:0.88rem;"><?= htmlspecialchars($apt['patient_name']) ?></div>
                  <div style="font-size:0.72rem;color:#718096;"><?= htmlspecialchars($apt['health_id']) ?> · <?= htmlspecialchars($apt['consultation_type'] ?? 'clinic') ?></div>
                </div>
                <div class="d-flex align-items-center gap-2">
                  <span class="badge bg-<?= $status_colors[$apt['status']] ?>"><?= ucfirst($apt['status']) ?></span>
                  <?php if ($apt['status']==='confirmed' && !empty($apt['meeting_link'])): ?>
                    <a href="<?= htmlspecialchars($apt['meeting_link']) ?>" target="_blank" class="btn btn-sm btn-success" style="font-size:0.72rem;padding:3px 8px;">
                      <i class="fas fa-video"></i> Join
                    </a>
                  <?php elseif ($apt['status']==='pending'): ?>
                    <form method="POST" style="display:inline;">
                      <input type="hidden" name="apt_id" value="<?= $apt['id'] ?>">
                      <button name="new_status" value="confirmed" class="btn btn-sm btn-success" style="font-size:0.7rem;padding:3px 8px;">Confirm</button>
                    </form>
                  <?php endif; ?>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>

      <!-- Pending Requests -->
      <div class="col-lg-5">
        <div class="doc-card">
          <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
            <h6 class="mb-0 fw-700"><i class="fas fa-bell me-2 text-danger"></i>Pending Requests <span class="badge bg-danger"><?= $pending_appointments ?></span></h6>
            <a href="appointments.php?status=pending" class="btn btn-sm btn-outline-warning">All</a>
          </div>
          <?php if (empty($pending_reqs)): ?>
            <div class="p-4 text-center text-muted"><p class="mb-0">No pending requests</p></div>
          <?php else: ?>
            <?php foreach ($pending_reqs as $req): ?>
              <div class="px-3 py-2" style="border-bottom:1px solid #f0f4f8;">
                <div class="d-flex justify-content-between align-items-start">
                  <div>
                    <div style="font-weight:600;font-size:0.85rem;"><?= htmlspecialchars($req['patient_name']) ?></div>
                    <div style="font-size:0.72rem;color:#718096;"><?= date('d M Y', strtotime($req['appointment_date'])) ?> · <?= date('h:i A', strtotime($req['appointment_time'])) ?></div>
                  </div>
                  <div style="display:flex;gap:4px;">
                    <form method="POST" style="display:inline;">
                      <input type="hidden" name="apt_id" value="<?= $req['id'] ?>">
                      <button name="new_status" value="confirmed" class="btn btn-xs btn-success" style="font-size:0.7rem;padding:2px 8px;"><i class="fas fa-check"></i></button>
                    </form>
                    <form method="POST" style="display:inline;">
                      <input type="hidden" name="apt_id" value="<?= $req['id'] ?>">
                      <button name="new_status" value="cancelled" class="btn btn-xs btn-danger" style="font-size:0.7rem;padding:2px 8px;"><i class="fas fa-times"></i></button>
                    </form>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>

        <!-- Quick Actions -->
        <div class="doc-card mt-3 p-3">
          <h6 class="fw-700 mb-3"><i class="fas fa-bolt me-2 text-warning"></i>Quick Actions</h6>
          <div class="row g-2">
            <div class="col-6"><a href="availability.php" class="btn btn-outline-primary w-100 btn-sm"><i class="fas fa-clock"></i><br>Set Availability</a></div>
            <div class="col-6"><a href="prescriptions.php" class="btn btn-outline-success w-100 btn-sm"><i class="fas fa-prescription-bottle-alt"></i><br>Prescriptions</a></div>
            <div class="col-6"><a href="patients.php" class="btn btn-outline-info w-100 btn-sm"><i class="fas fa-users"></i><br>My Patients</a></div>
            <div class="col-6"><a href="earnings.php" class="btn btn-outline-warning w-100 btn-sm"><i class="fas fa-rupee-sign"></i><br>Earnings</a></div>
          </div>
        </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>