<?php
$active = 'withdrawals';
$pageTitle = 'Withdrawal Requests';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$status = $_GET['status'] ?? '';
$action = $_POST['action'] ?? '';
$id = (int)($_POST['id'] ?? $_GET['id'] ?? 0);
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'update_status') {
  $newStatus = $_POST['status'] ?? '';
  $paymentStatus = $_POST['payment_status'] ?? 'unpaid';
  $adminNotes = trim($_POST['admin_notes'] ?? '');
  if (in_array($newStatus, ['approved','rejected']) && $id) {
    $stmt = $pdo->prepare("SELECT * FROM withdrawal_requests WHERE id=? AND status='pending'");
    $stmt->execute([$id]);
    $req = $stmt->fetch();
    if ($req) {
      $pdo->beginTransaction();
      try {
        $rejectNotes = '';
        if ($newStatus === 'rejected') {
          // Refund vendor wallet - amount added back (visible in vendor app)
          $stmt = $pdo->prepare("UPDATE vendors SET wallet_balance = wallet_balance + ? WHERE id=?");
          $stmt->execute([(int)$req['amount'], (int)$req['vendor_id']]);
          $rejectNotes = 'Admin rejected' . ($adminNotes ? ': ' . $adminNotes : '');
          $stmt = $pdo->prepare("INSERT INTO wallet_transactions (vendor_id, type, amount, description, ref_type, ref_id) VALUES (?, 'credit', ?, ?, 'withdrawal', ?)");
          $stmt->execute([(int)$req['vendor_id'], (int)$req['amount'], 'Withdrawal rejected - amount refunded. ' . $rejectNotes, $id]);
        }
        $notesToSave = ($newStatus === 'rejected') ? $rejectNotes : ($req['notes'] ?? null);
        $stmt = $pdo->prepare("UPDATE withdrawal_requests SET status=?, payment_status=?, notes=? WHERE id=?");
        $stmt->execute([$newStatus, $newStatus === 'approved' ? ($paymentStatus ?: 'paid') : 'unpaid', $notesToSave, $id]);
        $pdo->commit();
        $msg = "<div class='alert alert-success'>Withdrawal " . ($newStatus === 'approved' ? 'marked as paid.' : 'rejected. Amount refunded to vendor wallet.') . "</div>";
      } catch (Exception $e) {
        $pdo->rollBack();
        $msg = "<div class='alert alert-danger'>Error: " . htmlspecialchars($e->getMessage()) . "</div>";
      }
    }
  }
}

$where = [];
$params = [];
if ($status !== '') { $where[] = "w.status=?"; $params[] = $status; }

$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";
if ($where) $sql .= " WHERE " . implode(" AND ", $where);
$sql .= " ORDER BY w.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$withdrawals = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pendingTotal = (int)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM withdrawal_requests WHERE status='pending'")->fetchColumn();
$pendingCount = (int)$pdo->query("SELECT COUNT(*) FROM withdrawal_requests WHERE status='pending'")->fetchColumn();
?>
<div class="page-header d-flex justify-content-between align-items-center">
  <div>
    <h1>Withdrawal Requests</h1>
    <p class="subtitle">Manage vendor payout requests</p>
  </div>
  <div>
    <span class="badge bg-warning fs-6"><?php echo $pendingCount; ?> pending</span>
    <span class="text-muted">₹<?php echo number_format($pendingTotal); ?> total</span>
  </div>
</div>

<?php echo $msg; ?>

<form class="row g-2 mb-3">
  <div class="col-md-3">
    <select class="form-select" name="status">
      <option value="">All Status</option>
      <option value="pending" <?php if ($status==='pending') echo 'selected'; ?>>Pending</option>
      <option value="approved" <?php if ($status==='approved') echo 'selected'; ?>>Approved</option>
      <option value="rejected" <?php if ($status==='rejected') echo 'selected'; ?>>Rejected</option>
    </select>
  </div>
  <div class="col-auto"><button class="btn btn-dark" type="submit">Filter</button></div>
</form>

<div class="card">
  <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>Notes</th>
            <th>Created</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:180px;"><?php echo htmlspecialchars($w['notes'] ?? '-'); ?></td>
            <td class="small"><?php echo date('M d, H:i', strtotime($w['created_at'])); ?></td>
            <td class="text-end">
              <?php if ($w['status'] === 'pending'): ?>
              <form method="post" class="d-inline">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" name="id" value="<?php echo $w['id']; ?>">
                <input type="hidden" name="status" value="approved">
                <input type="hidden" name="payment_status" value="paid">
                <button type="submit" class="btn btn-sm btn-success">Accept / Mark Paid</button>
              </form>
              <button type="button" class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#rejectModal<?php echo $w['id']; ?>">Reject</button>
              <div class="modal fade" id="rejectModal<?php echo $w['id']; ?>" tabindex="-1">
                <div class="modal-dialog">
                  <div class="modal-content">
                    <div class="modal-header"><h5 class="modal-title">Reject Withdrawal #<?php echo $w['id']; ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                    <form method="post">
                      <div class="modal-body">
                        <input type="hidden" name="action" value="update_status">
                        <input type="hidden" name="id" value="<?php echo $w['id']; ?>">
                        <input type="hidden" name="status" value="rejected">
                        <p class="text-muted small">Amount ₹<?php echo number_format($w['amount']); ?> will be refunded to vendor wallet. Vendor will see this note in their app.</p>
                        <label class="form-label">Reason / Notes (optional)</label>
                        <textarea name="admin_notes" class="form-control" rows="3" placeholder="e.g. Invalid UPI, Please verify bank details..."></textarea>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Reject & Refund</button>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($withdrawals)): ?>
          <tr><td colspan="10" class="text-muted text-center py-4">No withdrawal requests found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
