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

$total_earnings  = $conn->query("SELECT COALESCE(SUM(consultation_fee),0) FROM appointments WHERE doctor_id=$doctor_id AND status='completed'")->fetch_row()[0];
$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()) AND YEAR(appointment_date)=YEAR(CURDATE())")->fetch_row()[0];
$today_earnings  = $conn->query("SELECT COALESCE(SUM(consultation_fee),0) FROM appointments WHERE doctor_id=$doctor_id AND status='completed' AND appointment_date=CURDATE()")->fetch_row()[0];
$total_completed = $conn->query("SELECT COUNT(*) FROM appointments WHERE doctor_id=$doctor_id AND status='completed'")->fetch_row()[0];

// Monthly breakdown
$monthly = $conn->query("
    SELECT DATE_FORMAT(appointment_date,'%b %Y') as month, YEAR(appointment_date) as yr, MONTH(appointment_date) as mn,
           COUNT(*) as total_apts, SUM(consultation_fee) as earnings
    FROM appointments WHERE doctor_id=$doctor_id AND status='completed'
    GROUP BY yr, mn ORDER BY yr DESC, mn DESC LIMIT 12
")->fetch_all(MYSQLI_ASSOC);

// Recent transactions
$transactions = $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='completed'
    ORDER BY a.appointment_date DESC LIMIT 20
")->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>Earnings - 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">

    <!-- Stats -->
    <div class="row g-3 mb-4">
      <?php $cards = [
        ['Total Earnings', 'Rs.'.number_format($total_earnings),  'fa-wallet',      '#0B7B6E'],
        ['This Month',     'Rs.'.number_format($month_earnings),  'fa-calendar-alt','#3182ce'],
        ['Today',          'Rs.'.number_format($today_earnings),  'fa-sun',         '#805ad5'],
        ['Consultations',  $total_completed,                      'fa-stethoscope', '#38a169'],
      ]; ?>
      <?php foreach ($cards as [$label,$val,$icon,$color]): ?>
        <div class="col-6 col-md-3">
          <div class="doc-card p-3" style="border-left:4px solid <?= $color ?>;">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <div style="font-size:1.6rem;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:<?= $color ?>;opacity:0.7;"></i>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

    <div class="row g-4">
      <!-- Monthly Breakdown -->
      <div class="col-lg-4">
        <div class="doc-card">
          <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-chart-bar me-2 text-primary"></i>Monthly Breakdown</h6></div>
          <?php if (empty($monthly)): ?>
            <div class="p-4 text-center text-muted">No earnings yet.</div>
          <?php else: ?>
            <?php foreach ($monthly as $m): ?>
              <div class="d-flex align-items-center justify-content-between px-3 py-2" style="border-bottom:1px solid #f0f4f8;">
                <div>
                  <div style="font-weight:600;font-size:0.88rem;"><?= $m['month'] ?></div>
                  <div style="font-size:0.72rem;color:#718096;"><?= $m['total_apts'] ?> consultations</div>
                </div>
                <div style="font-weight:700;color:#0B7B6E;font-size:0.9rem;">Rs. <?= number_format($m['earnings']) ?></div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>

      <!-- Transaction History -->
      <div class="col-lg-8">
        <div class="doc-card">
          <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-list-alt me-2 text-secondary"></i>Transaction History</h6></div>
          <?php if (empty($transactions)): ?>
            <div class="p-4 text-center text-muted">No transactions yet.</div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-sm mb-0">
                <thead class="table-light">
                  <tr><th>Date</th><th>Patient</th><th>Appointment#</th><th>Type</th><th>Fee</th><th>Status</th></tr>
                </thead>
                <tbody>
                  <?php foreach ($transactions as $t): ?>
                    <tr>
                      <td style="font-size:0.82rem;"><?= date('d M Y', strtotime($t['appointment_date'])) ?></td>
                      <td style="font-size:0.82rem;"><?= htmlspecialchars($t['patient_name']) ?></td>
                      <td style="font-size:0.78rem;"><code><?= htmlspecialchars($t['appointment_no'] ?? '') ?></code></td>
                      <td style="font-size:0.78rem;"><?= ucfirst($t['consultation_type'] ?? 'clinic') ?></td>
                      <td style="font-size:0.85rem;font-weight:700;color:#0B7B6E;">Rs. <?= number_format($t['consultation_fee']) ?></td>
                      <td><span class="badge bg-success" style="font-size:0.65rem;">Completed</span></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </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>