<?php
session_start();
require_once 'db.php';

// ✅ Hakikisha mtu ame-login
if (!isset($_SESSION['user_id'])) {
    die("Access denied");
}

// ================== APPROVE / REJECT ==================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['withdraw_id'], $_POST['action'])) {
    $id = intval($_POST['withdraw_id']);
    $action = $_POST['action'];

    $status = ($action === 'approve') ? 'approved' : 'rejected';
    $approved_at = ($status === 'approved') ? date("Y-m-d H:i:s") : null;

    // Pata withdrawal details
    $stmt = $conn->prepare("SELECT user_id, amount FROM withdrawals WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($user_id, $amount);
        $stmt->fetch();

        // Update withdrawal status
        if ($status === 'approved') {
            $update = $conn->prepare("UPDATE withdrawals SET status = ?, approved_at = ? WHERE id = ?");
            $update->bind_param("ssi", $status, $approved_at, $id);
        } else {
            $update = $conn->prepare("UPDATE withdrawals SET status = ? WHERE id = ?");
            $update->bind_param("si", $status, $id);

            // ✅ Refund kama rejected
            $refund = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $refund->bind_param("di", $amount, $user_id);
            $refund->execute();
        }
        $update->execute();
    }
}

// ================== PATA WITHDRAWALS ZOTE ==================
$results = $conn->query("SELECT w.id, w.user_id, u.phone, w.amount, w.status, w.requested_at, 
                                w.approved_at, w.mpesa_number, w.mpesa_name
                         FROM withdrawals w
                         JOIN users u ON w.user_id = u.id
                         ORDER BY w.requested_at DESC");
?>

<!DOCTYPE html>
<html>
<head>
  <title>Admin - Withdrawals</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 20px; background: #f9f9f9; }
    h2 { text-align: center; margin-bottom: 20px; }
    .withdraw-box {
      background: #fff;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      box-shadow: 0 0 10px rgba(0,0,0,0.05);
    }
    .withdraw-box p { margin: 6px 0; }
    form { margin-top: 12px; }
    button {
      padding: 8px 14px;
      margin-right: 10px;
      border: none;
      border-radius: 5px;
      color: #fff;
      cursor: pointer;
    }
    .approve { background: #28a745; }
    .reject { background: #dc3545; }
    .status { font-weight: bold; }
    .approved { color: green; }
    .rejected { color: red; }
    .pending { color: orange; }
    .empty { text-align:center; color:#555; margin-top:40px; }
  </style>
</head>
<body>

<h2>All Withdrawals</h2>

<?php if ($results->num_rows > 0): ?>
  <?php while ($row = $results->fetch_assoc()): ?>
    <div class="withdraw-box">
      <p><strong>User ID:</strong> <?= $row['user_id'] ?> (<?= htmlspecialchars($row['phone']) ?>)</p>
      <p><strong>Amount:</strong> KES <?= number_format($row['amount'], 2) ?></p>
      <p><strong>M-PESA Number:</strong> <?= htmlspecialchars($row['mpesa_number']) ?></p>
      <p><strong>M-PESA Name:</strong> <?= htmlspecialchars($row['mpesa_name']) ?></p>
      <p><strong>Requested At:</strong> <?= $row['requested_at'] ?></p>
      <p><strong>Status:</strong> 
        <span class="status <?= $row['status'] ?>"><?= ucfirst($row['status']) ?></span>
        <?php if ($row['approved_at']): ?>
          (<?= $row['approved_at'] ?>)
        <?php endif; ?>
      </p>

      <?php if ($row['status'] === 'pending'): ?>
        <form method="post">
          <input type="hidden" name="withdraw_id" value="<?= $row['id'] ?>">
          <button type="submit" name="action" value="approve" class="approve">Approve</button>
          <button type="submit" name="action" value="reject" class="reject">Reject</button>
        </form>
      <?php endif; ?>
    </div>
  <?php endwhile; ?>
<?php else: ?>
  <p class="empty">No withdrawals found.</p>
<?php endif; ?>

</body>
</html>
