<?php
require_once __DIR__ . '/includes/admin_auth.php';
requireAdmin();
$db = getDB();

// Mark payment status
if (isset($_GET['set_status']) && isset($_GET['id'])) {
    $s = $_GET['set_status'];
    if (in_array($s, ['pending','completed','failed','refunded'])) {
        $db->prepare("UPDATE payments SET status=? WHERE id=?")->execute([$s,(int)$_GET['id']]);
        setAdminFlash('success','Payment status updated.');
    }
  header('Location: ' . SITE_URL . '/admin/payments.php');
exit;
}

$statusFilter = sanitize($_GET['status'] ?? '');
$search       = sanitize($_GET['q'] ?? '');
$page         = max(1,(int)($_GET['page'] ?? 1));
$pp           = 15;

$where  = ['1=1']; $params = [];
if ($statusFilter) { $where[] = "p.status=?"; $params[] = $statusFilter; }
if ($search)       { $where[] = "(u.name LIKE ? OR l.name LIKE ? OR a.booking_id LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%"; }

$wsql   = implode(' AND ', $where);
$cstmt  = $db->prepare("SELECT COUNT(*) FROM payments p JOIN appointments a ON p.appointment_id=a.id JOIN users u ON p.user_id=u.id JOIN lawyers l ON p.lawyer_id=l.id WHERE $wsql");
$cstmt->execute($params); $total=(int)$cstmt->fetchColumn();
$pages  = max(1,ceil($total/$pp));
$offset = ($page-1)*$pp;

$stmt = $db->prepare("SELECT p.*,u.name AS client_name,l.name AS lawyer_name,a.booking_id,a.consultation_type FROM payments p JOIN appointments a ON p.appointment_id=a.id JOIN users u ON p.user_id=u.id JOIN lawyers l ON p.lawyer_id=l.id WHERE $wsql ORDER BY p.created_at DESC LIMIT $pp OFFSET $offset");
$stmt->execute($params);
$payments = $stmt->fetchAll();

// Summary stats
$totalRev   = $db->query("SELECT COALESCE(SUM(amount),0)        FROM payments WHERE status='completed'")->fetchColumn();
$platformFee= $db->query("SELECT COALESCE(SUM(platform_fee),0)  FROM payments WHERE status='completed'")->fetchColumn();
$lawyerPay  = $db->query("SELECT COALESCE(SUM(lawyer_payout),0) FROM payments WHERE status='completed'")->fetchColumn();
$pending    = $db->query("SELECT COUNT(*)                         FROM payments WHERE status='pending'")->fetchColumn();

adminHead('Payment Management');
adminSidebar('payments');
?>
<div class="adm-main">
<?php adminTopbar('Payment Management'); ?>
<div class="adm-content">
<?php flashHtml(); ?>

<!-- Revenue stats -->
<div class="row g-3 mb-4">
<?php
$pStats=[
    ['fas fa-rupee-sign',    'rgba(40,167,69,.1)',   '#1a7a34',        '₹'.number_format($totalRev,0),    'Total Revenue'],
    ['fas fa-percentage',    'rgba(212,175,55,.14)', 'var(--gold-dark)','₹'.number_format($platformFee,0), 'Platform Earnings'],
    ['fas fa-user-tie',      'rgba(10,35,66,.08)',   'var(--primary)',  '₹'.number_format($lawyerPay,0),   'Lawyer Payouts'],
    ['fas fa-hourglass-half','rgba(255,193,7,.14)',  '#b8860b',        $pending,                           'Pending Payments'],
];
foreach ($pStats as [$ic,$bg,$co,$val,$lbl]): ?>
<div class="col-6 col-md-3">
    <div class="stat-box">
        <div class="stat-icon" style="background:<?= $bg ?>;color:<?= $co ?>;"><i class="<?= $ic ?>"></i></div>
        <div><div class="stat-num" style="font-size:1.3rem;"><?= $val ?></div><div class="stat-lbl"><?= $lbl ?></div></div>
    </div>
</div>
<?php endforeach; ?>
</div>

<!-- Status filter tabs -->
<div style="display:flex;gap:7px;margin-bottom:18px;flex-wrap:wrap;">
<?php foreach([''=> 'All','pending'=>'⏳ Pending','completed'=>'✅ Completed','failed'=>'❌ Failed','refunded'=>'↩ Refunded'] as $s=>$lbl): ?>
<a href="?status=<?= $s ?>" style="white-space:nowrap;padding:7px 16px;border-radius:50px;font-size:.79rem;font-weight:700;text-decoration:none;border:1px solid var(--border);<?= $statusFilter===$s?'background:var(--primary);color:white;border-color:var(--primary);':'background:white;color:#718096;' ?>"><?= $lbl ?></a>
<?php endforeach; ?>
</div>

<!-- Search -->
<div style="background:white;border-radius:12px;padding:14px 18px;border:1px solid var(--border);margin-bottom:18px;">
    <form method="GET" style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap;">
        <?php if ($statusFilter): ?><input type="hidden" name="status" value="<?= $statusFilter ?>"><?php endif; ?>
        <div><label class="lbl" style="font-size:.72rem;">Search</label>
        <input type="text" name="q" class="form-ctrl" style="width:240px;" placeholder="Client, lawyer or booking ID..." value="<?= htmlspecialchars($search) ?>"></div>
        <button type="submit" class="btn-gold">Search</button>
        <?php if ($search||$statusFilter): ?><a href="<?= SITE_URL ?>/admin/payments.php" style="padding:9px 14px;background:var(--off-white);border-radius:8px;font-size:.82rem;color:#718096;text-decoration:none;border:1px solid var(--border);">Reset</a><?php endif; ?>
    </form>
</div>
<div style="font-size:.82rem;color:#718096;margin-bottom:10px;"><?= $total ?> payment<?= $total!=1?'s':'' ?> found</div>

<div class="adm-card">
<div style="overflow-x:auto;">
<table class="table tbl mb-0">
    <thead>
        <tr><th>Booking ID</th><th>Client</th><th>Lawyer</th><th>Amount</th><th>Platform (20%)</th><th>Lawyer (80%)</th><th>Method</th><th>Status</th><th>Date</th><th>Action</th></tr>
    </thead>
    <tbody>
    <?php foreach ($payments as $p): ?>
    <?php
    $sBg = ['pending'=>'rgba(255,193,7,.14)','completed'=>'rgba(40,167,69,.12)','failed'=>'rgba(220,53,69,.1)','refunded'=>'rgba(108,117,125,.1)'];
    $sCo = ['pending'=>'#b8860b','completed'=>'#1a7a34','failed'=>'#c0392b','refunded'=>'#6c757d'];
    $bg  = $sBg[$p['status']] ?? 'rgba(0,0,0,.05)';
    $co  = $sCo[$p['status']] ?? '#555';
    ?>
    <tr>
        <td style="font-size:.74rem;font-weight:700;color:var(--primary);"><?= $p['booking_id'] ?></td>
        <td style="font-size:.83rem;font-weight:600;"><?= htmlspecialchars($p['client_name']) ?></td>
        <td style="font-size:.82rem;color:#718096;"><?= htmlspecialchars($p['lawyer_name']) ?></td>
        <td style="font-weight:800;color:var(--primary);font-size:.88rem;">₹<?= number_format($p['amount'],2) ?></td>
        <td style="font-size:.82rem;color:var(--gold-dark);">₹<?= number_format($p['platform_fee'],2) ?></td>
        <td style="font-size:.82rem;color:#1a7a34;">₹<?= number_format($p['lawyer_payout'],2) ?></td>
        <td style="font-size:.78rem;text-transform:capitalize;"><?= $p['payment_method'] ?></td>
        <td><span style="background:<?= $bg ?>;color:<?= $co ?>;padding:3px 10px;border-radius:50px;font-size:.7rem;font-weight:700;"><?= ucfirst($p['status']) ?></span></td>
        <td style="font-size:.75rem;color:#718096;"><?= date('d M Y', strtotime($p['created_at'])) ?></td>
        <td>
            <?php if ($p['status'] === 'pending'): ?>
          <div style="display:flex;gap:5px;flex-direction:column;">

    <a href="<?= SITE_URL ?>/admin/payments.php?set_status=completed&id=<?= $p['id'] ?>" 
       style="background:rgba(40,167,69,.1);color:#1a7a34;padding:3px 9px;border-radius:6px;font-size:.7rem;font-weight:700;text-decoration:none;" 
       onclick="return confirm('Mark as completed?')">
       Complete
    </a>

    <a href="<?= SITE_URL ?>/admin/payments.php?set_status=failed&id=<?= $p['id'] ?>" 
       style="background:rgba(220,53,69,.08);color:#c0392b;padding:3px 9px;border-radius:6px;font-size:.7rem;font-weight:700;text-decoration:none;" 
       onclick="return confirm('Mark as failed?')">
       Failed
    </a>

</div>
          <?php elseif ($p['status'] === 'completed'): ?>

<span style="
background:rgba(40,167,69,.12);
color:#1a7a34;
padding:3px 9px;
border-radius:6px;
font-size:.7rem;
font-weight:700;
display:inline-block;
">
Completed
</span>
            <?php else: ?>
            <span style="font-size:.74rem;color:#ccc;">—</span>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($payments)): ?>
    <tr><td colspan="10" style="text-align:center;padding:40px;color:#718096;">No payments found.</td></tr>
    <?php endif; ?>
    </tbody>
</table>
</div>
</div>

<?php if ($pages > 1): ?>
<nav style="margin-top:18px;"><ul class="pagination justify-content-center gap-1">
<?php for($p=1;$p<=$pages;$p++): ?>
<li><a href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>" style="display:block;padding:7px 13px;border-radius:8px;<?= $p===$page?'background:var(--primary);color:white;':'border:1px solid var(--border);color:var(--primary);' ?>text-decoration:none;font-size:.82rem;"><?= $p ?></a></li>
<?php endfor; ?>
</ul></nav>
<?php endif; ?>

</div></div>
<?php adminFoot(); ?>