<?php
session_start();
require_once '../config.php';
requireAdmin();
$page_title = 'Payments';

$search        = clean($_GET['search'] ?? '');
$status_filter = clean($_GET['status'] ?? '');
$date_filter   = clean($_GET['date'] ?? '');

// Use appointments table for payment data since payments table may not exist
$total_revenue  = $conn->query("SELECT COALESCE(SUM(consultation_fee),0) FROM appointments WHERE status='completed'")->fetch_row()[0];
$today_revenue  = $conn->query("SELECT COALESCE(SUM(consultation_fee),0) FROM appointments WHERE status='completed' AND DATE(appointment_date)=CURDATE()")->fetch_row()[0];
$month_revenue  = $conn->query("SELECT COALESCE(SUM(consultation_fee),0) FROM appointments WHERE status='completed' AND MONTH(appointment_date)=MONTH(CURDATE()) AND YEAR(appointment_date)=YEAR(CURDATE())")->fetch_row()[0];
$total_completed= $conn->query("SELECT COUNT(*) FROM appointments WHERE status='completed'")->fetch_row()[0];

$where = []; $params = []; $types = '';
if ($search)        { $where[] = "(p.full_name LIKE ? OR d.full_name LIKE ? OR a.appointment_no LIKE ?)"; $s="%$search%"; $params[]=$s;$params[]=$s;$params[]=$s; $types.='sss'; }
if ($status_filter) { $where[] = "a.payment_status=?"; $params[]=$status_filter; $types.='s'; }
if ($date_filter)   { $where[] = "DATE(a.appointment_date)=?"; $params[]=$date_filter; $types.='s'; }
$wq = $where ? 'WHERE a.status="completed" AND '.implode(' AND ',$where) : 'WHERE a.status="completed"';

$stmt = $conn->prepare("SELECT a.*, p.full_name as patient_name, p.health_id, d.full_name as doctor_name, s.name as specialization FROM appointments a JOIN patients p ON a.patient_id=p.id JOIN doctors d ON a.doctor_id=d.id LEFT JOIN specializations s ON d.specialization_id=s.id $wq ORDER BY a.appointment_date DESC LIMIT 100");
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$payments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

include 'header.php';
?>
<style>
  .stat-card { border-radius:14px; padding:18px; display:flex; align-items:center; gap:14px; box-shadow:0 4px 20px rgba(11,74,203,.12); transition:transform .2s; position:relative; overflow:hidden; }
  .stat-card:hover { transform:translateY(-3px); }
  .stat-card::after { content:''; position:absolute; right:-20px; top:-20px; width:80px; height:80px; border-radius:50%; background:rgba(255,255,255,.1); }
  .stat-icon { width:46px; height:46px; border-radius:14px; background:rgba(255,255,255,.22); display:grid; place-items:center; flex-shrink:0; font-size:20px; color:#fff; }
  .stat-num { font-size:20px; font-weight:800; color:#fff; line-height:1; }
  .stat-lbl { font-size:11px; color:rgba(255,255,255,.8); margin-top:3px; font-weight:500; }
  @media(max-width:768px) {
    .stat-card { padding:14px 12px; gap:10px; }
    .filter-form { flex-direction:column; }
    .filter-form .form-control, .filter-form .form-select, .filter-form button { width:100% !important; }
    table thead { display:none; }
    table tr { display:block; margin-bottom:10px; border:1px solid #e2e8f0; border-radius:12px; padding:10px; background:#fff; }
    table td { display:flex; justify-content:space-between; align-items:center; padding:5px 8px; border:none; font-size:13px; }
    table td::before { content:attr(data-label); font-weight:700; color:#94a3b8; font-size:11px; text-transform:uppercase; flex-shrink:0; margin-right:8px; }
  }
</style>

<?php displayFlash(); ?>

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-800" style="color:#0f172a;"><i class="fas fa-money-bill-wave me-2 text-primary"></i>Payments</h5>
    <small class="text-muted">Completed consultation payments</small>
  </div>
</div>

<!-- Stats -->
<div class="row g-3 mb-4">
  <?php $cards = [
    ['Total Revenue',  'Rs.'.number_format($total_revenue),  'fa-wallet',       'linear-gradient(135deg,#059669,#10b981)'],
    ['This Month',     'Rs.'.number_format($month_revenue),  'fa-calendar-alt', 'linear-gradient(135deg,#0B4ACB,#3B63E6)'],
    ['Today',          'Rs.'.number_format($today_revenue),  'fa-sun',          'linear-gradient(135deg,#7c3aed,#a855f7)'],
    ['Consultations',  $total_completed,                     'fa-stethoscope',  'linear-gradient(135deg,#0891b2,#06b6d4)'],
  ]; ?>
  <?php foreach ($cards as [$lbl,$val,$icon,$grad]): ?>
  <div class="col-6 col-md-3">
    <div class="stat-card" style="background:<?= $grad ?>;">
      <div class="stat-icon"><i class="fas <?= $icon ?>"></i></div>
      <div><div class="stat-num"><?= $val ?></div><div class="stat-lbl"><?= $lbl ?></div></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Filter -->
<div class="admin-card mb-4 p-3">
  <form method="GET" class="d-flex gap-2 flex-wrap filter-form">
    <input type="text" name="search" class="form-control form-control-sm" placeholder="Search patient, doctor, apt#..." value="<?= htmlspecialchars($search) ?>" style="min-width:180px;">
    <input type="date" name="date" class="form-control form-control-sm" value="<?= htmlspecialchars($date_filter) ?>" style="min-width:140px;">
    <select name="status" class="form-select form-select-sm" style="min-width:130px;">
      <option value="">All Payments</option>
      <option value="paid" <?= $status_filter==='paid'?'selected':'' ?>>Paid</option>
      <option value="pending" <?= $status_filter==='pending'?'selected':'' ?>>Pending</option>
    </select>
    <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search me-1"></i>Filter</button>
    <a href="payments.php" class="btn btn-outline-secondary btn-sm">Clear</a>
  </form>
</div>

<!-- Table -->
<div class="admin-card">
  <div class="p-3 border-bottom">
    <h6 class="mb-0 fw-700"><i class="fas fa-list me-2 text-primary"></i>Payment Transactions <span class="badge bg-secondary ms-1"><?= count($payments) ?></span></h6>
  </div>
  <?php if (empty($payments)): ?>
    <div class="p-5 text-center text-muted">
      <i class="fas fa-credit-card fa-3x mb-3" style="opacity:.2;"></i>
      <h6>No payment records found</h6>
    </div>
  <?php else: ?>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead class="table-light">
        <tr><th>Apt #</th><th>Patient</th><th>Doctor</th><th>Date</th><th>Method</th><th>Amount</th><th>Status</th></tr>
      </thead>
      <tbody>
        <?php foreach ($payments as $p): ?>
        <tr>
          <td data-label="Apt #"><code style="font-size:11px;"><?= htmlspecialchars($p['appointment_no']) ?></code></td>
          <td data-label="Patient">
            <div style="font-weight:600;font-size:13px;"><?= htmlspecialchars($p['patient_name']) ?></div>
            <div style="font-size:11px;color:#94a3b8;"><?= htmlspecialchars($p['health_id']) ?></div>
          </td>
          <td data-label="Doctor">
            <div style="font-weight:600;font-size:13px;">Dr. <?= htmlspecialchars($p['doctor_name']) ?></div>
            <div style="font-size:11px;color:#94a3b8;"><?= htmlspecialchars($p['specialization'] ?? '') ?></div>
          </td>
          <td data-label="Date" style="font-size:13px;"><?= date('d M Y', strtotime($p['appointment_date'])) ?></td>
          <td data-label="Method"><span class="badge bg-light text-dark"><?= ucfirst($p['payment_method'] ?? 'cash') ?></span></td>
          <td data-label="Amount" style="font-weight:700;color:#059669;font-size:13px;">Rs. <?= number_format($p['consultation_fee']) ?></td>
          <td data-label="Status"><span class="badge bg-<?= $p['payment_status']==='paid'?'success':'warning' ?>"><?= ucfirst($p['payment_status'] ?? 'pending') ?></span></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

<?php include 'footer.php'; ?>
