<?php
define('SECURE_ACCESS', true);

$pageTitle = "Payout Approvals";
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();

$currentUser = getCurrentUser();

$error = '';
$success = '';

// Handle Payout Status Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['payout_id'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: payouts");
        exit();
    }

    $action = $_POST['action'];
    $payoutId = (int)$_POST['payout_id'];
    $utr_number = trim($_POST['utr_number'] ?? '');

    try {
        $stmt_get_pay = $pdo->prepare("SELECT user_id, amount FROM payouts WHERE id = ?");
        $stmt_get_pay->execute([$payoutId]);
        $pay_data = $stmt_get_pay->fetch();

        if ($action === 'approve') {
            $stmt = $pdo->prepare("UPDATE payouts SET status = 'paid', utr_number = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$utr_number, $payoutId]);
            $_SESSION['flash_success'] = "Payout request marked as Paid with UTR: " . htmlspecialchars($utr_number) . ".";
            logAuditEvent('admin_approve_payout', 'payout', $payoutId, 'Approved payout of ₹' . number_format($pay_data['amount'], 2) . ' for user #' . $pay_data['user_id']);
            require_once __DIR__ . '/../../includes/notification_helper.php';
            sendMultichannelNotification($pay_data['user_id'], 'payout_status', [
                'amount' => number_format($pay_data['amount'], 2),
                'status' => 'Paid',
                'utr_number' => $utr_number
            ]);
        } elseif ($action === 'reject') {
            $stmt = $pdo->prepare("UPDATE payouts SET status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$payoutId]);
            $_SESSION['flash_success'] = "Payout request rejected.";
            logAuditEvent('admin_reject_payout', 'payout', $payoutId, 'Rejected payout of ₹' . number_format($pay_data['amount'], 2) . ' for user #' . $pay_data['user_id']);
            require_once __DIR__ . '/../../includes/notification_helper.php';
            sendMultichannelNotification($pay_data['user_id'], 'payout_status', [
                'amount' => number_format($pay_data['amount'], 2),
                'status' => 'Rejected'
            ]);
        }
    } catch (PDOException $e) {
        error_log("Admin payout action error: " . $e->getMessage());
        $_SESSION['flash_error'] = "Action failed. Please try again.";
    }
    header("Location: payouts");
    exit();
}

// Handle End of Month Sweep
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'sweep_payouts') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: payouts");
        exit();
    }
    try {
        require_once __DIR__ . '/../../includes/payout_sweep.php';
        $swept_count = runEndOfMonthPayoutSweep($pdo);
        $_SESSION['flash_success'] = "Successfully generated {$swept_count} automated End-of-Month payout requests.";
        logAuditEvent('admin_sweep_payouts', 'system', 0, "Processed End-of-Month automated sweep for {$swept_count} users.");
    } catch (Exception $e) {
        error_log("Sweep Error: " . $e->getMessage());
        $_SESSION['flash_error'] = "Sweep failed: " . $e->getMessage();
    }
    header("Location: payouts");
    exit();
}

// Fetch all payouts
$payout_requests = [];
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$total_records = 0;
$total_pages = 0;

try {
    if ($pdo) {
        $total_records = (int)$pdo->query("SELECT COUNT(*) FROM payouts")->fetchColumn() ?: 0;
        $total_pages = ceil($total_records / $limit);

        $stmt = $pdo->prepare("
            SELECT p.*, u.username, u.email, d.title as designation_title 
            FROM payouts p 
            JOIN users u ON p.user_id = u.id 
            LEFT JOIN designations d ON u.designation_id = d.id 
            ORDER BY p.created_at DESC
            LIMIT ? OFFSET ?
        ");
        $stmt->bindValue(1, $limit, PDO::PARAM_INT);
        $stmt->bindValue(2, $offset, PDO::PARAM_INT);
        $stmt->execute();
        $payout_requests = $stmt->fetchAll();
    }
} catch (PDOException $e) {
    error_log("Admin payouts load error: " . $e->getMessage());
    $error = "Failed to load payout requests. Please try again.";
}

include __DIR__ . '/../../includes/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">Commissions Payout Requests</h1>
        <p class="text-muted mb-0">Approve or reject withdrawal requests from corporate network associates and check bank destinations.</p>
    </div>
    <div>
        <form method="POST" action="payouts" onsubmit="return confirm('Are you sure you want to process the End-of-Month automated payout sweep? This will generate payout requests for ALL users with a remaining balance.');">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>">
            <input type="hidden" name="action" value="sweep_payouts">
            <button type="submit" class="btn btn-warning fw-semibold shadow-sm">
                <i class="bi bi-calendar-check me-2"></i>Process End-of-Month Sweep
            </button>
        </form>
    </div>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-wallet2 me-2 text-primary"></i>Withdrawal Requests Log</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                            <tr>
                                <th class="ps-4">User Details</th>
                                <th>Requested Amount</th>
                                <th>Platform Fee</th>
                                <th>TDS Deducted</th>
                                <th>Net Payout</th>
                                <th>Linked Bank Account</th>
                                <th>Status</th>
                                <th>Requested Date</th>
                                <th class="text-end pe-4">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($payout_requests)): ?>
                                <tr>
                                    <td colspan="11" class="text-center py-5 text-muted">
                                        <i class="bi bi-inbox fs-1 mb-2"></i>
                                        <p class="mb-0">No withdrawal requests found.</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($payout_requests as $pay): ?>
                                    <tr>
                                        <!-- User details -->
                                        <td class="ps-4">
                                            <strong class="text-dark d-block"><?php echo htmlspecialchars($pay['username']); ?></strong>
                                            <span class="text-muted small d-block"><?php echo htmlspecialchars($pay['email']); ?></span>
                                            <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace px-2 py-0.5 mt-1" style="font-size: 0.7rem;">
                                                <?php echo htmlspecialchars($pay['designation_title'] ?? 'No Rank'); ?>
                                            </span>
                                        </td>
                                        
                                        <!-- Amount -->
                                        <td>
                                            <strong class="text-dark fs-6">₹<?php echo number_format($pay['amount'], 2); ?></strong>
                                        </td>

                                        <!-- Platform Fee -->
                                        <td>
                                            <span class="text-secondary small">₹<?php echo number_format($pay['platform_fee'] ?? 0.00, 2); ?></span>
                                        </td>

                                        <!-- TDS -->
                                        <td>
                                            <span class="text-secondary small">₹<?php echo number_format($pay['tds_amount'] ?? 0.00, 2); ?></span>
                                        </td>

                                        <!-- Net Amount -->
                                        <td>
                                            <strong class="text-success fs-6">₹<?php echo number_format($pay['net_amount'] ?? 0.00, 2); ?></strong>
                                        </td>
                                        
                                        <!-- Bank Account -->
                                        <td>
                                            <strong class="text-secondary small d-block"><?php echo htmlspecialchars($pay['bank_name'] ?? 'N/A'); ?></strong>
                                            <span class="text-muted small font-monospace">Acc: *<?php echo htmlspecialchars(substr($pay['account_number'] ?? '0000', -4)); ?></span>
                                            <?php if (!empty($pay['utr_number'])): ?>
                                                <div class="mt-1 small text-muted font-monospace" style="font-size: 0.75rem;">UTR: <?php echo htmlspecialchars($pay['utr_number']); ?></div>
                                            <?php endif; ?>
                                        </td>

                                        <!-- Status Badge -->
                                        <td>
                                            <span class="badge <?php 
                                                if ($pay['status'] === 'paid') echo 'bg-success';
                                                elseif ($pay['status'] === 'rejected') echo 'bg-danger';
                                                else echo 'bg-warning text-dark';
                                            ?> text-uppercase font-monospace"><?php echo $pay['status']; ?></span>
                                        </td>

                                        <!-- Date -->
                                        <td>
                                            <span class="text-muted small"><?php echo date('Y-m-d H:i', strtotime($pay['created_at'])); ?></span>
                                        </td>

                                        <!-- Actions -->
                                        <td class="text-end pe-4">
                                            <?php if ($pay['status'] === 'pending'): ?>
                                                <div class="d-flex justify-content-end gap-2">
                                                    <button type="button" class="btn btn-sm btn-success text-white" onclick="showPayoutModal(<?php echo $pay['id']; ?>, 'approve', '₹<?php echo number_format($pay['amount'], 2); ?>', '₹<?php echo number_format($pay['net_amount'] ?? 0.00, 2); ?>', '<?php echo htmlspecialchars($pay['username']); ?>')">
                                                        <i class="bi bi-check-lg"></i> Mark as Paid
                                                    </button>
                                                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="showPayoutModal(<?php echo $pay['id']; ?>, 'reject', '₹<?php echo number_format($pay['amount'], 2); ?>', '₹0.00', '<?php echo htmlspecialchars($pay['username']); ?>')">
                                                        <i class="bi bi-x-circle"></i> Reject
                                                    </button>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted small font-monospace">Action Logged</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php if ($total_pages > 1): ?>
                <div class="card-footer bg-light border-top py-3 d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
                    <div class="small text-secondary font-monospace">
                        Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> requests
                    </div>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pagination-sm mb-0 align-items-center gap-1">
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => 1])); ?>">First</a>
                            </li>
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                            </li>
                            <li class="page-item disabled mx-1">
                                <span class="text-secondary small fw-bold" style="font-size: 0.75rem;">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
                            </li>
                            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                            </li>
                            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $total_pages])); ?>">Last</a>
                            </li>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Payout Action Confirmation Modal -->
<div class="modal fade" id="payoutConfirmModal" tabindex="-1" aria-labelledby="payoutConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST" action="payouts" class="modal-content">
            <input type="hidden" name="action" id="modal_action" value="">
            <input type="hidden" name="payout_id" id="modal_payout_id" value="">
            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
            
            <div class="modal-header border-bottom-0 pb-0">
                <h5 class="modal-title fw-bold text-dark" id="payoutConfirmModalLabel">Confirm Action</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center py-4">
                <i class="bi bi-question-circle text-warning display-4 mb-3 d-block"></i>
                <p class="lead mb-3 text-secondary" id="modal_message" style="font-size: 1.05rem;"></p>
                <div class="mb-0 text-start px-3 d-none" id="utr_container">
                    <label for="modal_utr_number" class="form-label small fw-bold text-dark mb-1">Bank Transfer UTR No. / Ref No. <span class="text-danger">*</span></label>
                    <input type="text" name="utr_number" id="modal_utr_number" class="form-control form-control-sm font-monospace" placeholder="Enter 12-digit UTR Reference Number" required>
                </div>
            </div>
            <div class="modal-footer bg-light border-top-0">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary px-4" id="modal_submit_btn">Confirm</button>
            </div>
        </form>
    </div>
</div>

<script>
function showPayoutModal(payoutId, action, amount, netAmount, username) {
    const modalEl = document.getElementById('payoutConfirmModal');
    const actionInput = document.getElementById('modal_action');
    const payoutIdInput = document.getElementById('modal_payout_id');
    const messageEl = document.getElementById('modal_message');
    const submitBtn = document.getElementById('modal_submit_btn');
    const titleEl = document.getElementById('payoutConfirmModalLabel');
    const utrContainer = document.getElementById('utr_container');
    const utrInput = document.getElementById('modal_utr_number');

    actionInput.value = action;
    payoutIdInput.value = payoutId;

    if (action === 'approve') {
        titleEl.textContent = 'Approve Payout';
        messageEl.innerHTML = `Are you sure you want to mark the payout of <strong>${amount}</strong> (Net transfer: <strong>${netAmount}</strong>) for <strong>${username}</strong> as <strong>Paid</strong>?`;
        submitBtn.className = 'btn btn-success text-white px-4';
        submitBtn.textContent = 'Mark as Paid';
        utrContainer.classList.remove('d-none');
        utrInput.required = true;
        utrInput.value = '';
    } else {
        titleEl.textContent = 'Reject Payout';
        messageEl.innerHTML = `Are you sure you want to <strong>Reject</strong> the payout of <strong>${amount}</strong> for <strong>${username}</strong>?`;
        submitBtn.className = 'btn btn-danger px-4';
        submitBtn.textContent = 'Reject';
        utrContainer.classList.add('d-none');
        utrInput.required = false;
        utrInput.value = '';
    }

    const myModal = new bootstrap.Modal(modalEl);
    myModal.show();
}
</script>

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