<?php
require_once 'config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$success = '';
$error = '';

// Handle withdrawal approval
if (isset($_POST['approve_withdrawal'])) {
    $withdrawal_id = intval($_POST['withdrawal_id']);
    $user_id = intval($_POST['user_id']);
    $amount = floatval($_POST['amount']);
    
    mysqli_begin_transaction($conn);
    
    try {
        // Check if user has sufficient balance
        $stmt = mysqli_prepare($conn, "SELECT wallet FROM users WHERE user_id = ?");
        mysqli_stmt_bind_param($stmt, "i", $user_id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $user = mysqli_fetch_assoc($result);
        
        if ($user['wallet'] >= $amount) {
            // Update withdrawal status
            $stmt = mysqli_prepare($conn, "UPDATE witdrawl SET status = 1, processed_at = NOW(), processed_by = ? WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "si", $_SESSION['admin_user'], $withdrawal_id);
            mysqli_stmt_execute($stmt);
            
            // Deduct from wallet
            $stmt = mysqli_prepare($conn, "UPDATE users SET wallet = wallet - ? WHERE user_id = ?");
            mysqli_stmt_bind_param($stmt, "di", $amount, $user_id);
            mysqli_stmt_execute($stmt);
            
            // Add to income history as debit
            $stmt = mysqli_prepare($conn, "INSERT INTO income_history (user_id, amount, description, credit_debit, income_type, transaction_id) VALUES (?, ?, 'Withdrawal Approved', 0, 'withdrawal', ?)");
            $trans_id = 'WDR' . time() . rand(100, 999);
            mysqli_stmt_bind_param($stmt, "ids", $user_id, $amount, $trans_id);
            mysqli_stmt_execute($stmt);
            
            mysqli_commit($conn);
            $success = "Withdrawal approved successfully!";
        } else {
            throw new Exception("Insufficient balance!");
        }
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error = "Error: " . $e->getMessage();
    }
}

// Handle withdrawal rejection
if (isset($_POST['reject_withdrawal'])) {
    $withdrawal_id = intval($_POST['withdrawal_id']);
    
    $stmt = mysqli_prepare($conn, "UPDATE witdrawl SET status = 2, remarks = ? WHERE id = ?");
    $remarks = sanitize($conn, $_POST['remarks']);
    mysqli_stmt_bind_param($stmt, "si", $remarks, $withdrawal_id);
    
    if (mysqli_stmt_execute($stmt)) {
        $success = "Withdrawal rejected successfully!";
    } else {
        $error = "Error rejecting withdrawal!";
    }
}

// Get pending withdrawals with user details
$withdrawals = mysqli_query($conn, "SELECT w.*, u.name, u.mobile, u.wallet 
                                    FROM witdrawl w 
                                    LEFT JOIN users u ON w.user_id = u.user_id 
                                    WHERE w.status = 0 
                                    ORDER BY w.request_date DESC");

// Get processed withdrawals
$processed = mysqli_query($conn, "SELECT w.*, u.name, u.mobile 
                                  FROM witdrawl w 
                                  LEFT JOIN users u ON w.user_id = u.user_id 
                                  WHERE w.status IN (1, 2) 
                                  ORDER BY w.processed_at DESC 
                                  LIMIT 50");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Withdrawal Management - MLM System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.gstatic.com" rel="preconnect">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <?php include 'includes/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>Withdrawal Management</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item active">Withdrawals</li>
                </ol>
            </nav>
        </div>

        <section class="section">
            <div class="row">
                <div class="col-lg-12">
                    <?php if ($success): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $success; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Pending Withdrawals -->
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Pending Withdrawal Requests</h5>
                            
                            <?php if (mysqli_num_rows($withdrawals) > 0): ?>
                            <table class="table table-striped datatable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>User ID</th>
                                        <th>Name</th>
                                        <th>Mobile</th>
                                        <th>Amount</th>
                                        <th>Wallet Balance</th>
                                        <th>Request Date</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row = mysqli_fetch_assoc($withdrawals)): ?>
                                    <tr>
                                        <td><?php echo $row['id']; ?></td>
                                        <td><?php echo $row['user_id']; ?></td>
                                        <td><?php echo htmlspecialchars($row['name']); ?></td>
                                        <td><?php echo $row['mobile']; ?></td>
                                        <td>₹<?php echo number_format($row['amt']); ?></td>
                                        <td>₹<?php echo number_format($row['wallet'], 2); ?></td>
                                        <td><?php echo date('d M Y', strtotime($row['request_date'])); ?></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#approveModal<?php echo $row['id']; ?>" <?php echo ($row['wallet'] < $row['amt']) ? 'disabled' : ''; ?>>
                                                <i class="bi bi-check-circle"></i> Approve
                                            </button>
                                            
                                            <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#rejectModal<?php echo $row['id']; ?>">
                                                <i class="bi bi-x-circle"></i> Reject
                                            </button>
                                            
                                            <!-- Approve Modal -->
                                            <div class="modal fade" id="approveModal<?php echo $row['id']; ?>" tabindex="-1">
                                                <div class="modal-dialog">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title">Approve Withdrawal</h5>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                        </div>
                                                        <form method="POST">
                                                            <div class="modal-body">
                                                                <p>You are about to approve a withdrawal request for:</p>
                                                                <ul>
                                                                    <li><strong>User:</strong> <?php echo $row['user_id']; ?> (<?php echo htmlspecialchars($row['name']); ?>)</li>
                                                                    <li><strong>Amount:</strong> ₹<?php echo number_format($row['amt']); ?></li>
                                                                    <li><strong>Current Balance:</strong> ₹<?php echo number_format($row['wallet'], 2); ?></li>
                                                                    <li><strong>Balance After:</strong> ₹<?php echo number_format($row['wallet'] - $row['amt'], 2); ?></li>
                                                                </ul>
                                                                <p class="text-warning">This action cannot be undone!</p>
                                                                <input type="hidden" name="withdrawal_id" value="<?php echo $row['id']; ?>">
                                                                <input type="hidden" name="user_id" value="<?php echo $row['user_id']; ?>">
                                                                <input type="hidden" name="amount" value="<?php echo $row['amt']; ?>">
                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                <button type="submit" name="approve_withdrawal" class="btn btn-success">Approve Withdrawal</button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Reject Modal -->
                                            <div class="modal fade" id="rejectModal<?php echo $row['id']; ?>" tabindex="-1">
                                                <div class="modal-dialog">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <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">
                                                                <p>Are you sure you want to reject this withdrawal request?</p>
                                                                <div class="mb-3">
                                                                    <label for="remarks" class="form-label">Remarks (Optional)</label>
                                                                    <textarea class="form-control" id="remarks" name="remarks" rows="2"></textarea>
                                                                </div>
                                                                <input type="hidden" name="withdrawal_id" value="<?php echo $row['id']; ?>">
                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                <button type="submit" name="reject_withdrawal" class="btn btn-danger">Reject Request</button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                            <?php else: ?>
                                <div class="alert alert-info">No pending withdrawal requests.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Processed Withdrawals -->
                    <div class="card mt-4">
                        <div class="card-body">
                            <h5 class="card-title">Recent Processed Withdrawals</h5>
                            
                            <?php if (mysqli_num_rows($processed) > 0): ?>
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>User ID</th>
                                        <th>Name</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Processed By</th>
                                        <th>Processed At</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row = mysqli_fetch_assoc($processed)): ?>
                                    <tr>
                                        <td><?php echo $row['id']; ?></td>
                                        <td><?php echo $row['user_id']; ?></td>
                                        <td><?php echo htmlspecialchars($row['name']); ?></td>
                                        <td>₹<?php echo number_format($row['amt']); ?></td>
                                        <td>
                                            <?php if ($row['status'] == 1): ?>
                                                <span class="badge bg-success">Approved</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">Rejected</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo $row['processed_by'] ?: 'System'; ?></td>
                                        <td><?php echo date('d M Y H:i', strtotime($row['processed_at'])); ?></td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                            <?php else: ?>
                                <div class="alert alert-info">No processed withdrawals yet.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <?php include 'includes/footer.php'; ?>

    <!-- Vendor JS Files -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
    <script src="assets/js/main.js"></script>
    
    <script>
    document.getElementById('amount')?.addEventListener('input', function(e) {
    const amount = parseFloat(this.value) || 0;
    const maxAmount = <?php echo $withdrawal_amount; ?>;
    const submitBtn = document.getElementById('submitBtn');
    const errorDiv = document.getElementById('amount-error') || createErrorElement();
    
    if (amount < 100) {
        showError(errorDiv, 'Minimum withdrawal amount is ₹100');
        submitBtn.disabled = true;
    } else if (amount % 100 !== 0) {
        showError(errorDiv, 'Amount must be in multiples of ₹100');
        submitBtn.disabled = true;
    } else if (amount > maxAmount) {
        showError(errorDiv, `Insufficient balance. Maximum available: ₹${maxAmount.toLocaleString('en-IN')}`);
        submitBtn.disabled = true;
    } else {
        hideError(errorDiv);
        submitBtn.disabled = false;
    }
});

function createErrorElement() {
    const amountInput = document.getElementById('amount');
    const errorDiv = document.createElement('div');
    errorDiv.id = 'amount-error';
    errorDiv.className = 'text-danger mt-2';
    errorDiv.style.fontSize = '0.9rem';
    amountInput.parentNode.appendChild(errorDiv);
    return errorDiv;
}

function showError(element, message) {
    element.innerHTML = `<i class="fas fa-exclamation-circle me-2"></i>${message}`;
    element.style.display = 'block';
}

function hideError(element) {
    element.style.display = 'none';
}

// Form submission with enhanced validation
document.getElementById('withdrawForm')?.addEventListener('submit', function(e) {
    <?php if (!$can_withdraw): ?>
        e.preventDefault();
        alert('Please complete your profile (PAN, Aadhaar, and Bank Details) before withdrawing.');
        return;
    <?php endif; ?>

    const amount = parseFloat(document.getElementById('amount').value);
    const maxAmount = <?php echo $withdrawal_amount; ?>;
    
    if (isNaN(amount) || amount < 100) {
        e.preventDefault();
        alert('Please enter a valid amount (minimum ₹100)');
        return;
    }
    
    if (amount % 100 !== 0) {
        e.preventDefault();
        alert('Amount must be in multiples of ₹100');
        return;
    }
    
    if (amount > maxAmount) {
        e.preventDefault();
        alert('You cannot withdraw more than your available balance of ₹' + maxAmount.toLocaleString('en-IN'));
        return;
    }
    
    <?php if (!$withdrawal_time_active): ?>
        if (!confirm('Note: You are withdrawing outside recommended hours (6 AM - 6 PM). Processing may take longer. Do you still want to proceed?')) {
            e.preventDefault();
            return;
        }
    <?php endif; ?>
    
    if (!confirm('Are you sure you want to withdraw ₹' + amount.toLocaleString('en-IN') + '?\n\nDeductions:\n- TDS (5%): ₹' + (amount * 0.05).toFixed(2) + '\n- Admin (10%): ₹' + (amount * 0.1).toFixed(2) + '\n\nNet Amount: ₹' + (amount * 0.85).toFixed(2))) {
        e.preventDefault();
    } else {
        const submitBtn = document.getElementById('submitBtn');
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';
        submitBtn.disabled = true;
    }
});

// DataTable initialization
$(document).ready(function() {
    if ($('.withdrawal-table tbody tr').length > 1) {
        $('.withdrawal-table').DataTable({
            pageLength: 5,
            order: [[0, 'desc']],
            language: {
                search: "<i class='fas fa-search'></i>",
                searchPlaceholder: "Search...",
                lengthMenu: "Show _MENU_ entries",
                info: "Showing _START_ to _END_ of _TOTAL_ entries",
                infoEmpty: "No entries found",
                infoFiltered: "(filtered from _MAX_ total entries)"
            }
        });
    }
});
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>