<?php
$reportActive = 'withdrawal_report';
$pageTitle = 'Withdrawal Report';
require_once __DIR__ . '/../partials/top.php';

$pdo = db();
$dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-90 days'));
$dateTo = $_GET['date_to'] ?? date('Y-m-d');
$status = $_GET['status'] ?? '';
$vendor_id = (int)($_GET['vendor_id'] ?? 0);
$dtFrom = $dateFrom . ' 00:00:00';
$dtTo = $dateTo . ' 23:59:59';

$where = ["w.created_at BETWEEN ? AND ?"];
$params = [$dtFrom, $dtTo];
if ($status && in_array($status, ['pending','approved','rejected'])) { $where[] = "w.status=?"; $params[] = $status; }
if ($vendor_id) { $where[] = "w.vendor_id=?"; $params[] = $vendor_id; }

$sql = "SELECT w.*, v.vendor_code, v.name vendor_name, v.phone
        FROM withdrawal_requests w
        JOIN vendors v ON v.id=w.vendor_id
        WHERE " . implode(" AND ", $where) . "
        ORDER BY w.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$withdrawals = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Summary
$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM withdrawal_requests WHERE status='pending' AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$totalPending = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM withdrawal_requests WHERE status='approved' AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$totalApproved = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM withdrawal_requests WHERE status='rejected' AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$totalRejected = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM withdrawal_requests WHERE created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$totalCount = (int)$stmt->fetchColumn();
?>
<div class="page-header d-flex justify-content-between align-items-center flex-wrap gap-2">
  <div>
    <h1>Withdrawal Report</h1>
    <p class="subtitle">Full withdrawal history with accept/reject</p>
  </div>
  <a href="withdrawals.php" class="btn btn-dark">Manage Withdrawals</a>
</div>

<div class="report-filters">
  <form method="get" class="row g-3 align-items-end">
    <div class="col-md-2"><label class="form-label">From</label><input type="date" name="date_from" class="form-control" value="<?php echo htmlspecialchars($dateFrom); ?>"></div>
    <div class="col-md-2"><label class="form-label">To</label><input type="date" name="date_to" class="form-control" value="<?php echo htmlspecialchars($dateTo); ?>"></div>
    <div class="col-md-2"><label class="form-label">Status</label><select name="status" class="form-select"><option value="">All</option><option value="pending" <?php echo $status==='pending'?'selected':''; ?>>Pending</option><option value="approved" <?php echo $status==='approved'?'selected':''; ?>>Approved</option><option value="rejected" <?php echo $status==='rejected'?'selected':''; ?>>Rejected</option></select></div>
    <div class="col-md-2"><label class="form-label">Vendor ID</label><input type="number" name="vendor_id" class="form-control" value="<?php echo $vendor_id ?: ''; ?>" placeholder="All"></div>
    <div class="col-md-2"><button type="submit" class="btn btn-dark">Apply</button></div>
  </form>
</div>

<div class="report-summary">
  <div class="summary-item"><div class="label">Total Requests</div><div class="value"><?php echo $totalCount; ?></div></div>
  <div class="summary-item"><div class="label">Pending</div><div class="value text-warning">₹<?php echo number_format($totalPending); ?></div></div>
  <div class="summary-item"><div class="label">Approved / Paid</div><div class="value text-success">₹<?php echo number_format($totalApproved); ?></div></div>
  <div class="summary-item"><div class="label">Rejected (Refunded)</div><div class="value text-danger">₹<?php echo number_format($totalRejected); ?></div></div>
</div>

<div class="card">
  <div class="card-header">Withdrawal History</div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>ID</th><th>Vendor</th><th>Amount</th><th>Mode</th><th>UPI/Bank</th><th>Status</th><th>Payment</th><th>Admin Notes</th><th>Created</th><th>Updated</th><th class="text-end">Actions</th></tr></thead>
        <tbody>
          <?php foreach ($withdrawals as $w): ?>
          <tr>
            <td>#<?php echo $w['id']; ?></td>
            <td><strong><?php echo htmlspecialchars($w['vendor_code']); ?></strong><div class="small text-muted"><?php echo htmlspecialchars($w['vendor_name']); ?></div></td>
            <td class="fw-semibold">₹<?php echo number_format($w['amount']); ?></td>
            <td><?php echo ucfirst($w['payment_mode'] ?? '-'); ?></td>
            <td class="small"><?php echo htmlspecialchars($w['upi_id'] ?? ($w['bank_details'] ? 'Bank' : '-')); ?></td>
            <td><span class="badge bg-<?php echo $w['status']==='approved'?'success':($w['status']==='rejected'?'danger':'warning'); ?>"><?php echo $w['status']; ?></span></td>
            <td><span class="badge bg-<?php echo $w['payment_status']==='paid'?'success':'secondary'; ?>"><?php echo $w['payment_status']; ?></span></td>
            <td class="small" style="max-width:200px;" title="<?php echo htmlspecialchars($w['notes'] ?? ''); ?>"><?php echo htmlspecialchars($w['notes'] ?? '-'); ?></td>
            <td class="small"><?php echo date('M d, H:i', strtotime($w['created_at'])); ?></td>
            <td class="small"><?php echo $w['updated_at'] ? date('M d, H:i', strtotime($w['updated_at'])) : '-'; ?></td>
            <td class="text-end">
              <?php if ($w['status'] === 'pending'): ?>
              <a href="withdrawals.php" class="btn btn-sm btn-success">Accept / Reject</a>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($withdrawals)): ?><tr><td colspan="11" class="text-muted text-center py-4">No withdrawals in period</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="mt-4 card p-4">
  <h6 class="fw-bold">Flow</h6>
  <ul class="mb-0 small text-muted">
    <li><strong>Accept:</strong> Mark as paid — admin processes payout manually.</li>
    <li><strong>Reject:</strong> Amount refunded to vendor wallet. Vendor sees "Admin rejected" + your notes in their app withdrawal history.</li>
  </ul>
</div>
<?php require_once __DIR__ . '/../partials/bottom.php'; ?>
