<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include ('include/header.php');
$page_title = WEB_NAME . " | Manage Withdrawals";

// ── Summary counts ────────────────────────────────────────────────────────
try {
    $pending_count   = $pdo->query("SELECT COUNT(*) FROM withdrawals WHERE status='pending'")->fetchColumn();
    $processing_count= $pdo->query("SELECT COUNT(*) FROM withdrawals WHERE status='processing'")->fetchColumn();
    $completed_count = $pdo->query("SELECT COUNT(*) FROM withdrawals WHERE status='completed'")->fetchColumn();
    $rejected_count  = $pdo->query("SELECT COUNT(*) FROM withdrawals WHERE status='rejected'")->fetchColumn();
    $pending_total   = $pdo->query("SELECT COALESCE(SUM(amount),0) FROM withdrawals WHERE status IN ('pending','processing')")->fetchColumn();
    $completed_total = $pdo->query("SELECT COALESCE(SUM(final_amount),0) FROM withdrawals WHERE status='completed'")->fetchColumn();
} catch (PDOException $e) {
    $pending_count = $processing_count = $completed_count = $rejected_count = 0;
    $pending_total = $completed_total = 0;
}

// ── All withdrawals ───────────────────────────────────────────────────────
try {
    $wd_stmt = $pdo->query(
        "SELECT w.*, u.email, u.referral_balance
         FROM withdrawals w
         JOIN users u ON w.user_id = u.id
         ORDER BY w.created_at DESC"
    );
    $withdrawals = $wd_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $withdrawals = [];
}
?>
<title><?php echo $page_title; ?></title>
<link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<div class="container-fluid" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800"><i class="fas fa-money-bill-transfer mr-2"></i>Manage Withdrawals</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active">Manage Withdrawals</li>
    </ol>
  </div>

  <!-- ── Stats ──────────────────────────────────────────────────────────── -->
  <div class="row mb-4">
    <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
      <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $pending_count; ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-clock fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
      <div class="card border-left-info shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Processing</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $processing_count; ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-spinner fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
      <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Completed</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $completed_count; ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-check-circle fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
      <div class="card border-left-danger shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Rejected</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $rejected_count; ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-times-circle fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
      <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending Value</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">₦<?php echo number_format($pending_total, 2); ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-hourglass fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
      <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Total Paid Out</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">₦<?php echo number_format($completed_total, 2); ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-money-bill-wave fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Withdrawals Table ──────────────────────────────────────────────── -->
  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center"
         style="background:linear-gradient(135deg,#0201FD,#111199);">
      <h6 class="m-0 font-weight-bold text-white"><i class="fas fa-list mr-2"></i>All Withdrawal Requests</h6>
    </div>
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-bordered table-hover" id="withdrawalsTable" width="100%" cellspacing="0">
          <thead class="thead-light">
            <tr>
              <th>#</th>
              <th>User</th>
              <th>Method</th>
              <th>Amount</th>
              <th>Fee</th>
              <th>Receives</th>
              <th>Status</th>
              <th>Date</th>
              <th class="text-center">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($withdrawals as $wd): ?>
            <tr id="row-<?php echo $wd['id']; ?>">
              <td><?php echo $wd['id']; ?></td>
              <td>
                <strong><?php echo htmlspecialchars($wd['username']); ?></strong><br>
                <small class="text-muted"><?php echo htmlspecialchars($wd['email']); ?></small><br>
                <small class="text-info">Ref.Bal: ₦<?php echo number_format($wd['referral_balance'], 2); ?></small>
              </td>
              <td>
                <span class="badge badge-secondary"><?php echo htmlspecialchars($wd['method_name']); ?></span><br>
                <small class="text-muted" style="font-size:10px;word-break:break-word;max-width:180px;display:inline-block;">
                    <?php echo nl2br(htmlspecialchars(substr($wd['wallet_or_account'], 0, 120))); ?>
                    <?php if (strlen($wd['wallet_or_account']) > 120): ?>
                        <a href="#" onclick="showDetails(<?php echo $wd['id']; ?>)" class="text-primary">...more</a>
                    <?php endif; ?>
                </small>
              </td>
              <td class="font-weight-bold">₦<?php echo number_format($wd['amount'], 2); ?></td>
              <td class="text-danger">₦<?php echo number_format($wd['fee_amount'], 2); ?> (<?php echo $wd['fee_percentage']; ?>%)</td>
              <td class="text-success font-weight-bold">₦<?php echo number_format($wd['final_amount'], 2); ?></td>
              <td>
                <?php
                $badge_map = [
                    'pending'    => 'badge-warning text-dark',
                    'processing' => 'badge-info',
                    'completed'  => 'badge-success',
                    'rejected'   => 'badge-danger',
                    'cancelled'  => 'badge-secondary',
                ];
                $badge_class = $badge_map[$wd['status']] ?? 'badge-secondary';
                ?>
                <span class="badge <?php echo $badge_class; ?> status-badge-<?php echo $wd['id']; ?>">
                  <?php echo ucfirst($wd['status']); ?>
                </span>
                <?php if (!empty($wd['admin_note'])): ?>
                <br><small class="text-muted" style="font-size:10px;"><?php echo htmlspecialchars($wd['admin_note']); ?></small>
                <?php endif; ?>
              </td>
              <td><small><?php echo date('M d, Y<br>h:i A', strtotime($wd['created_at'])); ?></small></td>
              <td class="text-center" style="white-space:nowrap;">
                <?php if (in_array($wd['status'], ['pending', 'processing'])): ?>
                  <button class="btn btn-sm btn-success mb-1"
                          onclick="approveWithdrawal(<?php echo $wd['id']; ?>, '<?php echo htmlspecialchars(addslashes($wd['username'])); ?>', <?php echo $wd['final_amount']; ?>)"
                          title="Approve & Complete">
                    <i class="fas fa-check"></i> Approve
                  </button>
                  <button class="btn btn-sm btn-warning mb-1"
                          onclick="markProcessing(<?php echo $wd['id']; ?>)"
                          title="Mark as Processing" <?php echo $wd['status']==='processing'?'disabled':''; ?>>
                    <i class="fas fa-spinner"></i> Processing
                  </button>
                  <button class="btn btn-sm btn-danger mb-1"
                          onclick="rejectWithdrawal(<?php echo $wd['id']; ?>, '<?php echo htmlspecialchars(addslashes($wd['username'])); ?>', <?php echo $wd['amount']; ?>)"
                          title="Reject & Refund">
                    <i class="fas fa-times"></i> Reject
                  </button>
                <?php endif; ?>
                <button class="btn btn-sm btn-info mb-1"
                        onclick="viewDetails(<?php echo $wd['id']; ?>, <?php echo htmlspecialchars(json_encode($wd)); ?>)"
                        title="View Full Details">
                  <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger mb-1"
                        onclick="deleteWithdrawal(<?php echo $wd['id']; ?>, '<?php echo htmlspecialchars(addslashes($wd['username'])); ?>', '<?php echo $wd['status']; ?>')"
                        title="Delete Record">
                  <i class="fas fa-trash"></i>
                </button>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- ── View Details Modal ─────────────────────────────────────────────── -->
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header" style="background:linear-gradient(135deg,#0201FD,#111199);">
        <h5 class="modal-title text-white font-weight-bold">
          <i class="fas fa-eye mr-2"></i>Withdrawal Details
        </h5>
        <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body" id="detailsModalBody"></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- ── Reject Modal ───────────────────────────────────────────────────── -->
<div class="modal fade" id="rejectModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title font-weight-bold"><i class="fas fa-times-circle mr-2"></i>Reject Withdrawal</h5>
        <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="reject_id">
        <p id="rejectSummary" class="text-muted small mb-3"></p>
        <div class="form-group">
          <label><strong>Rejection Reason / Note to User</strong></label>
          <textarea class="form-control" id="reject_note" rows="4"
                    placeholder="e.g. Invalid account details provided. Please update and resubmit."></textarea>
          <small class="text-muted">This note will be visible to the user. The amount will be refunded to their referral balance.</small>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger font-weight-bold" id="submitReject">
          <i class="fas fa-times mr-1"></i> Reject & Refund
        </button>
      </div>
    </div>
  </div>
</div>

<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
    if ($.fn.DataTable) {
        $('#withdrawalsTable').DataTable({ order: [[7, 'desc']], pageLength: 25 });
    }
});

var currentRejectId = 0;
var currentRejectAmount = 0;

// ── Approve ───────────────────────────────────────────────────────────────
function approveWithdrawal(id, username, finalAmt) {
    Swal.fire({
        title: 'Approve Withdrawal?',
        html: 'Mark withdrawal for <strong>' + username + '</strong> of <strong>₦' + parseFloat(finalAmt).toLocaleString('en-NG', {minimumFractionDigits:2}) + '</strong> as completed?<br><small class="text-danger">This confirms you have sent the funds.</small>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#1cc88a',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, Mark Completed',
        cancelButtonText: 'Cancel'
    }).then(function(result) {
        if (!result.isConfirmed) return;
        Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: function() { Swal.showLoading(); } });
        ajaxAction({ action: 'approve', id: id }, function(data) {
            if (data.status == '1') {
                updateRowStatus(id, 'completed', 'badge-success', data.msg);
                Swal.fire({ icon: 'success', title: 'Approved!', text: data.msg, timer: 2000, showConfirmButton: false });
            } else {
                Swal.fire('Error!', data.msg, 'error');
            }
        });
    });
}

// ── Mark Processing ───────────────────────────────────────────────────────
function markProcessing(id) {
    Swal.fire({
        title: 'Mark as Processing?',
        text: 'This will notify the user that their withdrawal is being processed.',
        icon: 'info',
        showCancelButton: true,
        confirmButtonColor: '#36b9cc',
        confirmButtonText: 'Yes, Mark Processing'
    }).then(function(result) {
        if (!result.isConfirmed) return;
        ajaxAction({ action: 'processing', id: id }, function(data) {
            if (data.status == '1') {
                updateRowStatus(id, 'processing', 'badge-info', null);
                Swal.fire({ icon: 'success', title: 'Updated!', text: data.msg, timer: 1500, showConfirmButton: false });
            } else {
                Swal.fire('Error!', data.msg, 'error');
            }
        });
    });
}

// ── Reject ────────────────────────────────────────────────────────────────
function rejectWithdrawal(id, username, amount) {
    currentRejectId = id;
    currentRejectAmount = amount;
    document.getElementById('reject_id').value = id;
    document.getElementById('reject_note').value = '';
    document.getElementById('rejectSummary').innerHTML =
        'Rejecting withdrawal for <strong>' + username + '</strong> (₦' +
        parseFloat(amount).toLocaleString('en-NG', {minimumFractionDigits:2}) + ').<br>' +
        'The full amount will be refunded to the user\'s referral balance.';
    $('#rejectModal').modal('show');
}

$('#submitReject').on('click', function() {
    var id   = document.getElementById('reject_id').value;
    var note = document.getElementById('reject_note').value.trim();
    if (!note) { Swal.fire('Required', 'Please provide a rejection reason.', 'warning'); return; }

    $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Processing...');
    ajaxAction({ action: 'reject', id: id, admin_note: note }, function(data) {
        $('#submitReject').prop('disabled', false).html('<i class="fas fa-times mr-1"></i> Reject & Refund');
        if (data.status == '1') {
            $('#rejectModal').modal('hide');
            updateRowStatus(id, 'rejected', 'badge-danger', note);
            Swal.fire({ icon: 'success', title: 'Rejected & Refunded!', text: data.msg, timer: 2500, showConfirmButton: false });
        } else {
            Swal.fire('Error!', data.msg, 'error');
        }
    });
});

// ── Delete ────────────────────────────────────────────────────────────────
function deleteWithdrawal(id, username, status) {
    var extra = (status === 'pending' || status === 'processing')
        ? '<br><strong class="text-danger">⚠ This is still ' + status + '! Amount will NOT be refunded.</strong>'
        : '';
    Swal.fire({
        title: 'Delete Record?',
        html: 'Delete withdrawal record #' + id + ' for <strong>' + username + '</strong>?' + extra,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        confirmButtonText: 'Yes, Delete',
        focusCancel: true
    }).then(function(result) {
        if (!result.isConfirmed) return;
        Swal.fire({ title: 'Deleting...', allowOutsideClick: false, didOpen: function() { Swal.showLoading(); } });
        ajaxAction({ action: 'delete', id: id }, function(data) {
            Swal.close();
            if (data.status == '1') {
                $('#row-' + id).fadeOut(400, function() { $(this).remove(); });
                Swal.fire({ icon: 'success', title: 'Deleted!', text: data.msg, timer: 1500, showConfirmButton: false });
            } else {
                Swal.fire('Error!', data.msg, 'error');
            }
        });
    });
}

// ── View Details ──────────────────────────────────────────────────────────
function viewDetails(id, data) {
    var html = '<div class="table-responsive"><table class="table table-sm table-bordered">';
    html += '<tr><th width="140">Field</th><th>Value</th></tr>';
    var fields = {
        'ID': data.id, 'Username': data.username, 'Email': data.email,
        'Method': data.method_name, 'Amount Requested': '₦' + parseFloat(data.amount).toLocaleString('en-NG',{minimumFractionDigits:2}),
        'Fee ('+data.fee_percentage+'%)': '₦' + parseFloat(data.fee_amount).toLocaleString('en-NG',{minimumFractionDigits:2}),
        'Amount to Receive': '₦' + parseFloat(data.final_amount).toLocaleString('en-NG',{minimumFractionDigits:2}),
        'Status': data.status,
        'Admin Note': data.admin_note || 'N/A',
        'IP Address': data.ip_address || 'N/A',
        'Created': data.created_at,
    };
    for (var k in fields) {
        html += '<tr><td class="font-weight-bold">' + k + '</td><td>' + (fields[k] || '—') + '</td></tr>';
    }
    html += '</table>';
    html += '<div class="mt-3"><strong>Account / Wallet Details:</strong><pre class="bg-light p-2 border rounded mt-1" style="font-size:12px;white-space:pre-wrap;">' + escHtml(data.wallet_or_account) + '</pre></div>';
    html += '</div>';
    document.getElementById('detailsModalBody').innerHTML = html;
    $('#detailsModal').modal('show');
}

// ── Helpers ───────────────────────────────────────────────────────────────
function updateRowStatus(id, status, badgeClass, note) {
    var badge = $('.status-badge-' + id);
    badge.attr('class', 'badge ' + badgeClass + ' status-badge-' + id).text(status.charAt(0).toUpperCase() + status.slice(1));
    // Disable action buttons for this row
    var row = $('#row-' + id);
    row.find('.btn-success, .btn-warning, .btn-danger:not(.btn-outline-danger)').prop('disabled', true).hide();
    if (note) {
        var existing = row.find('small.text-muted').last();
        if (existing.length) existing.text(note);
    }
}

function ajaxAction(data, callback) {
    $.ajax({
        url: 'ajax/withdrawal_handler.php',
        type: 'POST',
        data: data,
        dataType: 'json',
        success: callback,
        error: function() {
            Swal.fire('Error!', 'A network error occurred. Please try again.', 'error');
        }
    });
}

function escHtml(str) {
    if (!str) return '';
    return String(str)
        .replace(/&/g, '&amp;').replace(/</g, '&lt;')
        .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
</script>

<?php include ('include/footer.php'); ?>