<?php
/**
 * ADMIN WITHDRAWALS MANAGEMENT PAGE - FIXED
 * File: admin/withdrawals.php
 * Manage withdrawal requests from withdrawal_requests table
 */

require_once '../app/Core/init.php';

// Require admin authentication
Auth::requireAdmin();

// Initialize models
$db = Database::getInstance();
$notification = new NotificationService();

// Get filter parameters
$status_filter = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = ADMIN_ITEMS_PER_PAGE ?? 20;

// Build WHERE clause
$where_conditions = ["1=1"];
$params = [];

if ($status_filter !== 'all') {
    $where_conditions[] = "wr.status = ?";
    $params[] = $status_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(u.email LIKE ? OR wr.reference LIKE ? OR wr.bank_name LIKE ? OR wr.account_number LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

// Get total count
$count_sql = "SELECT COUNT(*) as total 
              FROM withdrawal_requests wr
              LEFT JOIN users u ON wr.user_id = u.id
              $where_clause";
$count_result = $db->fetch($count_sql, $params);
$total_withdrawals = $count_result['total'] ?? 0;
$total_pages = ceil($total_withdrawals / $per_page);
$offset = ($page - 1) * $per_page;

// Get withdrawals
$sql = "SELECT wr.*, 
        u.email as user_email,
        u.user_type,
        CASE 
            WHEN u.user_type = 'vendor' THEN v.business_name
            WHEN u.user_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
            ELSE 'Admin'
        END as display_name
        FROM withdrawal_requests wr
        LEFT JOIN users u ON wr.user_id = u.id
        LEFT JOIN vendors v ON u.id = v.user_id
        LEFT JOIN customers c ON u.id = c.user_id
        $where_clause
        ORDER BY wr.created_at DESC
        LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$withdrawals = $db->fetchAll($sql, $params);

// Get statistics
$stats_sql = "SELECT 
              COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
              COALESCE(SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END), 0) as pending_amount,
              COUNT(CASE WHEN status = 'approved' THEN 1 END) as completed_count,
              COALESCE(SUM(CASE WHEN status = 'approved' THEN amount ELSE 0 END), 0) as completed_amount,
              COUNT(CASE WHEN status = 'rejected' THEN 1 END) as rejected_count,
              COALESCE(SUM(CASE WHEN status = 'rejected' THEN amount ELSE 0 END), 0) as rejected_amount
              FROM withdrawal_requests";
$stats = $db->fetch($stats_sql);

// Ensure stats is an array with default values
if (!$stats) {
    $stats = [
        'pending_count' => 0,
        'pending_amount' => 0,
        'completed_count' => 0,
        'completed_amount' => 0,
        'rejected_count' => 0,
        'rejected_amount' => 0
    ];
}


// Handle withdrawal action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    $withdrawal_id = (int)$_POST['withdrawal_id'];
    $action = $_POST['action'];
    
    // Get withdrawal details
    $withdrawal = $db->fetch("
        SELECT wr.*, u.id as user_id 
        FROM withdrawal_requests wr
        LEFT JOIN users u ON wr.user_id = u.id
        WHERE wr.id = ? AND wr.status = 'pending'
    ", [$withdrawal_id]);
    
    if (!$withdrawal) {
        flash('error', 'Withdrawal request not found or already processed', 'danger');
        redirect($_SERVER['PHP_SELF']);
    }
    
    if ($action === 'approve') {
        $db->beginTransaction();
        
        try {
            // 1. Update withdrawal status to 'approved'
            $db->execute("
                UPDATE withdrawal_requests 
                SET status = 'approved', 
                    processed_at = NOW(),
                    processed_by = ?,
                    wallet_balance_after = wallet_balance_before - ?
                WHERE id = ?
            ", [Auth::id(), $withdrawal['amount'], $withdrawal_id]);
            
            // 2. Deduct from wallet balance NOW (when approved)
            $db->execute("
                UPDATE wallets 
                SET balance = balance - ?,
                    total_withdrawn = total_withdrawn + ?,
                    updated_at = NOW()
                WHERE id = ?
            ", [$withdrawal['amount'], $withdrawal['amount'], $withdrawal['wallet_id']]);
            
            // 3. Create wallet transaction as 'completed' (DEBIT)
            $reference = 'W-APPROVED-' . $withdrawal_id . '-' . time();
            
            $db->execute("
                INSERT INTO wallet_transactions 
                (user_id, wallet_id, transaction_type, category, amount, 
                 balance_before, balance_after, description, reference, status, created_at)
                VALUES (?, ?, 'withdrawal', 'debit', ?, ?, ?, ?, ?, 'completed', NOW())
            ", [
                $withdrawal['user_id'],
                $withdrawal['wallet_id'],
                $withdrawal['amount'],
                $withdrawal['wallet_balance_before'],
                $withdrawal['wallet_balance_before'] - $withdrawal['amount'],
                'Withdrawal approved - Ref: ' . ($withdrawal['reference'] ?? 'N/A'),
                $reference
            ]);
            
            $db->commit();
            
            // 4. Send email notification
            try {
                // Get user details for email
                $user_details = $db->fetch("
                    SELECT u.email, u.user_type,
                    CASE 
                        WHEN u.user_type = 'vendor' THEN v.business_name
                        WHEN u.user_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                        ELSE 'User'
                    END as display_name
                    FROM users u
                    LEFT JOIN vendors v ON u.id = v.user_id
                    LEFT JOIN customers c ON u.id = c.user_id
                    WHERE u.id = ?
                ", [$withdrawal['user_id']]);
                
                if ($user_details) {
                    $mailer = new Mailer();
                    $mailer->sendWithdrawalApproved([
                        'user_email'      => $user_details['email'],
                        'user_name'       => $user_details['display_name'],
                        'user_type'       => $user_details['user_type'],
                        'amount'          => $withdrawal['amount'],
                        'reference'       => $withdrawal['reference'],
                        'bank_name'       => $withdrawal['bank_name'],
                        'account_number'  => $withdrawal['account_number'],
                        'account_name'    => $withdrawal['account_name'],
                        'processed_at'    => date('Y-m-d H:i:s')
                    ]);
                }
            } catch (Exception $e) {
                // Log email error but don't fail the approval
                error_log("Withdrawal approved email failed: " . $e->getMessage());
            }
            
            flash('success', 'Withdrawal approved! Amount deducted from user wallet. Email notification sent.', 'success');
            
        } catch (Exception $e) {
            $db->rollback();
            flash('error', 'Failed to approve withdrawal: ' . $e->getMessage(), 'danger');
        }
        
    } elseif ($action === 'reject') {
        $reason = trim($_POST['reason'] ?? 'Not specified');
        
        $db->beginTransaction();
        
        try {
            // 1. Update withdrawal status to 'rejected'
            $db->execute("
                UPDATE withdrawal_requests 
                SET status = 'rejected', 
                    processed_at = NOW(),
                    processed_by = ?,
                    rejection_reason = ?
                WHERE id = ?
            ", [Auth::id(), $reason, $withdrawal_id]);
            
            // 2. DO NOT CREDIT WALLET - amount was never deducted in the first place!
            // 3. DO NOT CREATE wallet_transaction - no money movement happened
            
            $db->commit();
            
            // 4. Send email notification
            try {
                // Get user details for email
                $user_details = $db->fetch("
                    SELECT u.email, u.user_type,
                    CASE 
                        WHEN u.user_type = 'vendor' THEN v.business_name
                        WHEN u.user_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                        ELSE 'User'
                    END as display_name
                    FROM users u
                    LEFT JOIN vendors v ON u.id = v.user_id
                    LEFT JOIN customers c ON u.id = c.user_id
                    WHERE u.id = ?
                ", [$withdrawal['user_id']]);
                
                if ($user_details) {
                    $mailer = new Mailer();
                    $mailer->sendWithdrawalRejected([
                        'user_email'      => $user_details['email'],
                        'user_name'       => $user_details['display_name'],
                        'user_type'       => $user_details['user_type'],
                        'amount'          => $withdrawal['amount'],
                        'reference'       => $withdrawal['reference'],
                        'reason'          => $reason,
                        'processed_at'    => date('Y-m-d H:i:s')
                    ]);
                }
            } catch (Exception $e) {
                // Log email error but don't fail the rejection
                error_log("Withdrawal rejection email failed: " . $e->getMessage());
            }
            
            flash('success', 'Withdrawal rejected. User has been notified via email.', 'success');
            
        } catch (Exception $e) {
            $db->rollback();
            flash('error', 'Failed to reject withdrawal: ' . $e->getMessage(), 'danger');
        }
    }
    
    redirect($_SERVER['PHP_SELF']);
}

$page_title = "Withdrawal Requests - " . APP_NAME;
$active_menu = "withdrawals";

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-money-bill-wave"></i> Withdrawal Requests</h1>
            <p class="text-muted">Process withdrawal requests</p>
        </div>
    </div>

    <div class="content">
        
        <!-- Statistics Cards -->
        <div class="stats-grid mb-4">
            <div class="stat-card">
                <div class="stat-icon bg-warning">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="stat-details">
                    <h3><?= number_format($stats['pending_count'] ?? 0) ?></h3>
                    <p>Pending Requests</p>
                    <small class="text-muted">₦<?= number_format($stats['pending_amount'] ?? 0, 2) ?></small>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon bg-success">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-details">
                    <h3><?= number_format($stats['completed_count'] ?? 0) ?></h3>
                    <p>Completed</p>
                    <small class="text-muted">₦<?= number_format($stats['completed_amount'] ?? 0, 2) ?></small>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon bg-danger">
                    <i class="fas fa-times-circle"></i>
                </div>
                <div class="stat-details">
                    <h3><?= number_format($stats['rejected_count'] ?? 0) ?></h3>
                    <p>Rejected</p>
                    <small class="text-muted">₦<?= number_format($stats['rejected_amount'] ?? 0, 2) ?></small>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                            <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="approved" <?= $status_filter === 'approved' ? 'selected' : '' ?>>Approved</option>
                            <option value="rejected" <?= $status_filter === 'rejected' ? 'selected' : '' ?>>Rejected</option>
                        </select>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" class="form-control" 
                               placeholder="Email, reference, bank name..." 
                               value="<?= esc($search) ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary flex-fill">
                                <i class="fas fa-search"></i> Search
                            </button>
                            <a href="withdrawals.php" class="btn btn-secondary">
                                <i class="fas fa-redo"></i>
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Withdrawals Table -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-list"></i> Withdrawal Requests
                    <span class="badge bg-secondary"><?= number_format($total_withdrawals ?? 0) ?> requests</span>
                </h5>
            </div>
            <div class="card-body p-0">
                <?php if (empty($withdrawals)): ?>
                    <div class="empty-state py-5">
                        <i class="fas fa-money-bill-wave fa-3x text-muted mb-3"></i>
                        <p class="text-muted">No withdrawal requests found</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>Reference</th>
                                    <th>User</th>
                                    <th>Amount</th>
                                    <th>Bank Details</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($withdrawals as $w): ?>
                                    <tr>
                                        <td>
                                            <strong><?= esc($w['reference']) ?></strong><br>
                                            <small class="text-muted"><?= ucfirst($w['user_type'] ?? 'customer') ?></small>
                                        </td>
                                        <td>
                                            <strong><?= esc($w['display_name']) ?></strong><br>
                                            <small class="text-muted"><?= esc($w['user_email']) ?></small>
                                        </td>
                                        <td>
                                            <strong class="text-success">₦<?= number_format($w['amount'], 2) ?></strong>
                                        </td>
                                        <td>
                                            <strong><?= esc($w['bank_name']) ?></strong><br>
                                            <small><?= esc($w['account_number']) ?></small><br>
                                            <small class="text-muted"><?= esc($w['account_name']) ?></small>
                                        </td>
                                        <td><?= format_status_badge($w['status']) ?></td>
                                        <td>
                                            <?= format_date($w['created_at']) ?><br>
                                            <small class="text-muted"><?= format_time_ago($w['created_at']) ?></small>
                                        </td>
                                        <td>
                                            <?php if ($w['status'] === 'pending'): ?>
                                                <div class="btn-group-vertical btn-group-sm">
                                                    <!-- Approve Button with Loading -->
                                                    <form method="POST" style="display: inline;" onsubmit="return handleApprove(event, this, <?= $w['amount'] ?>)">
                                                        <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                                                        <input type="hidden" name="withdrawal_id" value="<?= $w['id'] ?>">
                                                        <input type="hidden" name="action" value="approve">
                                                        <button type="submit" class="btn btn-success btn-sm approve-btn">
                                                            <i class="fas fa-check"></i> Approve
                                                        </button>
                                                    </form>
                                                    
                                                    <!-- Reject Button -->
                                                    <button type="button" class="btn btn-danger btn-sm" 
                                                            onclick="showRejectModal(<?= $w['id'] ?>, '<?= esc($w['reference']) ?>')">
                                                        <i class="fas fa-times"></i> Reject
                                                    </button>
                                                </div>
                                            <?php else: ?>
                                                <small class="text-muted">
                                                    Processed<br>
                                                    <?= !empty($w['processed_at']) ? format_date($w['processed_at']) : 'N/A' ?>
                                                </small>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <div class="card-footer">
                            <?php 
                            $pagination_params = array_filter([
                                'status' => $status_filter !== 'pending' ? $status_filter : null,
                                'search' => !empty($search) ? $search : null
                            ]);
                            echo render_pagination($page, $total_pages, 'withdrawals.php', $pagination_params); 
                            ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Reject Withdrawal</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                    <input type="hidden" name="withdrawal_id" id="reject_withdrawal_id">
                    <input type="hidden" name="action" value="reject">
                    
                    <p>Reject withdrawal <strong id="reject_reference"></strong>?</p>
                    
                    <div class="mb-3">
                        <label class="form-label">Reason for Rejection <span class="text-danger">*</span></label>
                        <textarea name="reason" class="form-control" rows="3" required
                                  placeholder="Please provide a reason for rejecting this withdrawal..."></textarea>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> The amount will be credited back to the user's wallet.
                    </div>
                </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">
                        <i class="fas fa-times"></i> Reject & Refund
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showRejectModal(withdrawalId, reference) {
    document.getElementById('reject_withdrawal_id').value = withdrawalId;
    document.getElementById('reject_reference').textContent = reference;
    new bootstrap.Modal(document.getElementById('rejectModal')).show();
}
</script>


<script>
function handleApprove(event, form, amount) {
    const button = form.querySelector('.approve-btn');
    const formattedAmount = new Intl.NumberFormat('en-NG', { 
        style: 'currency', 
        currency: 'NGN',
        minimumFractionDigits: 2
    }).format(amount);
    
    if (!confirm('Approve this withdrawal of ' + formattedAmount + '?\n\nThis will deduct funds from the user\'s wallet.')) {
        event.preventDefault();
        return false;
    }
    
    // Disable button and show loading
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    return true;
}

// Also update reject modal submit button
function submitReject() {
    const form = document.getElementById('rejectForm');
    const reason = document.getElementById('rejectReason').value.trim();
    
    if (!reason) {
        alert('Please provide a rejection reason');
        return;
    }
    
    const button = form.querySelector('button[type="submit"]');
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Rejecting...';
    
    form.submit();
}
</script>

<?php include '../templates/layouts/admin/footer.php'; ?>