<?php
// admin/withdraw.php — Final Version with Pagination Fix, PDF Export, TopPay & Nekpay Payout Buttons

session_start();
// Check Path
if (file_exists("includes/config.php")) {
    require_once "includes/config.php";
} else {
    require_once "../includes/config.php";
}

// Admin Check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

// ---------------------------------------------------
// 🔍 CAPTURE CURRENT FILTERS (To maintain state)
// ---------------------------------------------------
$filter_params = $_GET;
unset($filter_params['action']); 
unset($filter_params['id']);
unset($filter_params['page']); // ✅ FIX: Prevents pagination double URL issues
unset($filter_params['export']); // Remove export flag from normal links

$current_params = http_build_query($filter_params);
$redirect_url = "withdraw.php" . ($current_params ? "?" . $current_params : "");

// ---------------------------------------------------
// 🟢 ACTION LOGIC (Approve/Reject/Login)
// ---------------------------------------------------
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $action = $_GET['action'];

    // 1. LOGIN AS USER LOGIC
    if ($action == 'login_as') {
        date_default_timezone_set('Asia/Kolkata');

        $stmt = $conn->prepare("SELECT user_id FROM withdrawals WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $res = $stmt->get_result();
        
        if ($row = $res->fetch_assoc()) {
            $target_user_id = $row['user_id'];
            
            // Generate Token
            $token = bin2hex(random_bytes(32)); 
            $expires_at = date("Y-m-d H:i:s", strtotime("+10 minutes"));

            // Insert Token
            $stmt2 = $conn->prepare("INSERT INTO admin_login_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
            $stmt2->bind_param("iss", $target_user_id, $token, $expires_at);
            
            if($stmt2->execute()){
                // 🔥 Ensure this URL is correct for your user panel
               $user_site_url = "https://jkm70x.long-term-application.com/user_login_handler";
                    header("Location: " . $user_site_url . "?token=" . $token); 
                    exit();
            } else {
                echo "<script>alert('Error generating login token'); window.location.href='$redirect_url';</script>";
            }
        }
    }

    // 2. APPROVE / REJECT LOGIC
    $stmt = $conn->prepare("SELECT user_id, amount, status FROM withdrawals WHERE id=? LIMIT 1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($row && $row['status'] == 'pending') {
        $user_id = $row['user_id'];
        $amount = $row['amount'];

        if ($action == 'approve') {
            $conn->query("UPDATE withdrawals SET status='successful' WHERE id=$id AND status='pending'");
            if($conn->affected_rows > 0) {
                echo "<script>alert('✅ Marked as Successful!'); window.location.href='$redirect_url';</script>";
            } else {
                echo "<script>alert('⚠️ This request is already processed!'); window.location.href='$redirect_url';</script>";
            }
        } 
        elseif ($action == 'reject') {
            $refund_amount = round($amount / 0.9, 2);
            $conn->begin_transaction();
            try {
                $stmt1 = $conn->prepare("UPDATE withdrawals SET status='rejected' WHERE id=? AND status='pending'");
                $stmt1->bind_param("i", $id);
                $stmt1->execute();
                
                if ($stmt1->affected_rows > 0) {
                    $stmt2 = $conn->prepare("UPDATE users SET income_balance = income_balance + ? WHERE id=?");
                    $stmt2->bind_param("di", $refund_amount, $user_id);
                    $stmt2->execute();
                    $stmt2->close();
                    
                    $conn->commit();
                    echo "<script>alert('❌ Rejected & Refunded Full Amount: ₹$refund_amount!'); window.location.href='$redirect_url';</script>";
                } else {
                    $conn->rollback();
                    echo "<script>alert('⚠️ This request is already processed!'); window.location.href='$redirect_url';</script>";
                }
                $stmt1->close();
            } catch (Exception $e) {
                $conn->rollback();
                echo "<script>alert('Error rejecting request!'); window.location.href='$redirect_url';</script>";
            }
        }
    } else {
        if($action !== 'login_as') {
             header("Location: " . $redirect_url);
             exit();
        }
    }
}

// ---------------------------------------------------
// 🔍 FILTER QUERY BUILDING
// ---------------------------------------------------
$search = trim($_GET['search'] ?? '');
$status = trim($_GET['status'] ?? '');
$vip_filter = trim($_GET['vip_filter'] ?? '');
$from = trim($_GET['from'] ?? '');
$to = trim($_GET['to'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));

$where = "1=1";
$params = [];
$types = "";

if ($search !== "") {
    $where .= " AND (u.mobile LIKE ? OR w.amount LIKE ?)";
    $s = "%$search%";
    $params[] = $s; $params[] = $s;
    $types .= "ss";
}
if ($status !== "") {
    $where .= " AND w.status=?";
    $params[] = $status;
    $types .= "s";
}
if ($vip_filter !== "") {
    if ($vip_filter == 'vip9') {
        $where .= " AND u.bonus_balance > 0";
    } else {
        $where .= " AND u.bonus_balance = 0";
    }
}
if ($from !== "" && $to !== "") {
    $where .= " AND DATE(w.created_at) BETWEEN ? AND ?";
    $params[] = $from;
    $params[] = $to;
    $types .= "ss";
}

// ---------------------------------------------------
// 📄 PDF EXPORT LOGIC (Only runs if Export is clicked)
// ---------------------------------------------------
if (isset($_GET['export']) && $_GET['export'] == 'pdf') {
    $sql_pdf = "SELECT w.*, u.mobile, u.bonus_balance 
                FROM withdrawals w 
                JOIN users u ON w.user_id=u.id 
                WHERE $where 
                ORDER BY w.id DESC"; // ✅ No Limit! Fetch all filtered data
    $stmt_pdf = $conn->prepare($sql_pdf);
    if ($types) $stmt_pdf->bind_param($types, ...$params);
    $stmt_pdf->execute();
    $pdf_data = $stmt_pdf->get_result();
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Withdrawal_Report_<?=date('Ymd')?></title>
        <style>
            body { font-family: Arial, sans-serif; background: #fff; padding: 20px; color: #000; }
            .report-header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 10px; }
            .report-header h2 { margin: 0; font-size: 24px; text-transform: uppercase; }
            .report-header p { margin: 5px 0 0 0; font-size: 12px; color: #555; }
            table { width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 12px; }
            th, td { border: 1px solid #000; padding: 8px; text-align: left; }
            th { background-color: #f2f2f2; font-weight: bold; }
            .amount { font-weight: bold; }
            @media print {
                @page { margin: 10mm; }
                body { -webkit-print-color-adjust: exact; }
                button { display: none; }
            }
        </style>
    </head>
    <body onload="window.print();">
        <div class="report-header">
            <h2>Withdrawal Report</h2>
            <p>Generated on: <?=date('d-M-Y H:i:s')?></p>
            <p>Filters Applied: <?=($status?:'All Status')?> | <?=($search?"Search: $search":'')?> | <?=($from && $to ? "Date: $from to $to" : '')?></p>
        </div>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>User / UID</th>
                    <th>Amount</th>
                    <th>Bank Details</th>
                    <th>Status</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
                <?php while($row = $pdf_data->fetch_assoc()): ?>
                <tr>
                    <td>#<?=$row['id']?></td>
                    <td><b><?=$row['mobile']?></b><br>UID: <?=$row['user_id']?></td>
                    <td class="amount">Rs. <?=number_format($row['amount'],2)?></td>
                    <td>
                        Bank: <?=$row['ifsc']?><br>
                        Acc: <?=$row['account_number']?><br>
                        Name: <?=$row['account_holder']?>
                    </td>
                    <td style="text-transform:uppercase;"><b><?=$row['status']?></b></td>
                    <td><?=date('d-M H:i', strtotime($row['created_at']))?></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
        <br>
        <button onclick="window.print();" style="padding:10px 20px; background:#000; color:#fff; cursor:pointer;">Print / Save as PDF</button>
        <button onclick="window.history.back();" style="padding:10px 20px; margin-left:10px; cursor:pointer;">Back to Panel</button>
    </body>
    </html>
    <?php
    exit(); // ✅ Stop loading the rest of the page for PDF!
}


// ---------------------------------------------------
// 📄 PAGINATION (Regular View)
// ---------------------------------------------------
$limit = 15;
$offset = ($page - 1) * $limit;

// Count
$sqlCount = "SELECT COUNT(*) as total FROM withdrawals w JOIN users u ON w.user_id=u.id WHERE $where";
$stmt = $conn->prepare($sqlCount);
if ($types) $stmt->bind_param($types, ...$params);
$stmt->execute();
$total = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();
$total_pages = ceil($total / $limit);

// Fetch Data
$sql = "SELECT w.*, u.mobile, u.bonus_balance 
        FROM withdrawals w 
        JOIN users u ON w.user_id=u.id 
        WHERE $where 
        ORDER BY w.id DESC 
        LIMIT $limit OFFSET $offset";

$stmt = $conn->prepare($sql);
if ($types) $stmt->bind_param($types, ...$params);
$stmt->execute();
$rows = $stmt->get_result();
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Withdraw Requests</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <style>
    body{font-family:'Segoe UI', sans-serif; background:#f4f6f9; margin:0; padding:15px;}
    
    .header{background:#0047ab; color:#fff; padding:15px; font-size:18px; font-weight:bold; border-radius:8px; display:flex; justify-content:space-between; align-items:center;}
    .header a {color:#fff; text-decoration:none;}

    /* Filters */
    .filter-box{background:#fff; padding:15px; margin:15px 0; border-radius:8px; box-shadow:0 2px 5px rgba(0,0,0,0.05); display:flex; flex-wrap:wrap; gap:10px; align-items:center;}
    input, select{padding:10px; border:1px solid #ddd; border-radius:5px; font-size:14px;}
    button.filter-btn{padding:10px 20px; background:#0047ab; color:#fff; border:none; border-radius:5px; cursor:pointer; font-weight:bold;}
    
    /* PDF Button */
    .btn-pdf { padding:10px 20px; background:#e74c3c; color:#fff; border:none; border-radius:5px; cursor:pointer; text-decoration:none; font-weight:bold; display:inline-flex; align-items:center; gap:5px; transition:0.3s;}
    .btn-pdf:hover { background:#c0392b; }

    /* Table */
    .table-responsive { overflow-x: auto; }
    table{width:100%; border-collapse:collapse; background:#fff; margin-top:10px; box-shadow:0 2px 5px rgba(0,0,0,0.05); border-radius:8px; overflow:hidden; min-width: 950px;}
    th, td{padding:14px; text-align:left; border-bottom:1px solid #eee; font-size:14px;}
    th{background:#eee; color:#333;}
    
    /* Badges */
    .badge {padding:5px 10px; border-radius:4px; font-size:11px; font-weight:bold; text-transform:uppercase;}
    .status-pending{background:#fff3e0; color:#ef6c00;}
    .status-approved, .status-successful{background:#e8f5e9; color:#2e7d32;} 
    .status-rejected{background:#ffebee; color:#c62828;}
    .status-processing{background:#e3f2fd; color:#0277bd;}

    .vip-tag { background: linear-gradient(90deg, #F59E0B, #D97706); color: #fff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: bold; margin-left: 5px; }

    /* ACTION BUTTONS */
    .action-group { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
    .btn { padding: 8px 14px; border-radius: 6px; text-decoration: none; font-size: 13px; color:#fff; border:none; cursor:pointer; display: inline-flex; align-items: center; justify-content: center; transition: 0.2s; font-weight: 600; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
    .btn i { margin-right: 6px; }

    .btn-approve { background:#28a745; }
    .btn-reject { background:#dc3545; }
    .btn-gateway { background:#007bff; }
    .btn-tp { background:#ff8c00; } /* TP Button color */
    .btn-nk { background:#17a2b8; } /* NEW: NK Button color */
    .btn-login { background: #8e44ad; }
    .btn:hover { opacity: 0.9; transform: translateY(-1px); }

    .pagination{margin-top:20px; text-align:center;}
    .pagination a{padding:10px 15px; background:#ddd; text-decoration:none; color:#333; margin:2px; border-radius:4px;}
    .pagination a.active{background:#0047ab; color:#fff; font-weight:bold;}

    .bank-details {font-size:13px; color:#555; line-height: 1.5;}
    .bank-details b {color:#000;}
  </style>
</head>
<body>

<div class="header">
    <span>Withdraw Requests</span>
    <a href="dashboard.php">Home</a>
</div>

<form method="get" class="filter-box">
    <input type="text" name="search" placeholder="Mobile / Amount" value="<?=htmlspecialchars($search)?>">
    
    <select name="status">
        <option value="">All Status</option>
        <option value="pending" <?=$status=='pending'?'selected':''?>>Pending</option>
        <option value="processing" <?=$status=='processing'?'selected':''?>>Processing</option> 
        <option value="successful" <?=$status=='successful'?'selected':''?>>Successful</option>
        <option value="rejected" <?=$status=='rejected'?'selected':''?>>Rejected</option>
    </select>

    <select name="vip_filter">
        <option value="">All Users</option>
        <option value="vip9" <?=$vip_filter=='vip9'?'selected':''?>>👑 VIP 9 Only</option>
        <option value="normal" <?=$vip_filter=='normal'?'selected':''?>>Normal Members</option>
    </select>

    <input type="date" name="from" value="<?=$from?>">
    <input type="date" name="to" value="<?=$to?>">
    <button type="submit" class="filter-btn"><i class="fa-solid fa-filter"></i> Filter</button>
    <a href="withdraw.php" style="color:gray; text-decoration:none; font-weight:bold; margin-left:5px;">Reset</a>
    
    <a href="?export=pdf&<?=$current_params?>" target="_blank" class="btn-pdf" style="margin-left:auto;">
        <i class="fa-solid fa-file-pdf"></i> Download PDF
    </a>
</form>

<div class="table-responsive">
<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>User</th>
            <th>Amount</th>
            <th>Bank Details</th>
            <th>Status</th>
            <th>Date</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php if ($rows->num_rows > 0): ?>
            <?php while($row = $rows->fetch_assoc()): ?>
            <tr>
                <td>#<?=$row['id']?></td>
                <td>
                    <b><?=$row['mobile']?></b>
                    <?php if($row['bonus_balance'] > 0): ?>
                        <span class="vip-tag">VIP 9</span>
                    <?php endif; ?>
                    <br>
                    <small>UID: <?=$row['user_id']?></small>
                </td>
                <td style="font-weight:bold; color:#0047ab;">₹<?=number_format($row['amount'],2)?></td>
                
                <td>
                    <div class="bank-details">
                        <b>Bank:</b> <?=$row['ifsc']?><br>
                        <b>Acc:</b> <?=$row['account_number']?><br>
                        <b>Name:</b> <?=$row['account_holder']?>
                    </div>
                </td>

                <td>
                    <span class="badge status-<?=$row['status']?>"><?=$row['status']?></span>
                    <?php if(!empty($row['mch_transfer_id'])): ?>
                        <br><small style="font-size:10px;color:#666; word-break:break-all;">Ref: <?=$row['mch_transfer_id']?></small>
                    <?php endif; ?>
                </td>
                
                <td><?=date('d-M H:i', strtotime($row['created_at']))?></td>
                
                <td style="min-width:320px;">
                    <div class="action-group">
                        
                        <a href="?action=login_as&id=<?=$row['id']?>&<?=$current_params?>&page=<?=$page?>" target="_blank" class="btn btn-login" title="Login as User">
                            <i class="fa-solid fa-right-to-bracket"></i> Login
                        </a>

                        <?php if($row['status'] == 'pending'): ?>
                            <button class="btn btn-gateway" onclick="payViaGateway(<?=$row['id']?>)">
                                <i class="fa-solid fa-bolt"></i> Pay
                            </button>

                            <button class="btn btn-tp" onclick="payViaTP(<?=$row['id']?>)">
                                <i class="fa-solid fa-money-bill-transfer"></i> TP
                            </button>

                            <button class="btn btn-nk" onclick="payViaNK(<?=$row['id']?>)">
                                <i class="fa-solid fa-building-columns"></i> NK
                            </button>
                            
                            <a href="?action=approve&id=<?=$row['id']?>&<?=$current_params?>&page=<?=$page?>" class="btn btn-approve" onclick="return confirm('Mark as Success manually?')">
                                <i class="fa-solid fa-check"></i>
                            </a>
                            
                            <a href="?action=reject&id=<?=$row['id']?>&<?=$current_params?>&page=<?=$page?>" class="btn btn-reject" onclick="return confirm('Reject and Refund amount?')">
                                <i class="fa-solid fa-xmark"></i>
                            </a>

                        <?php elseif($row['status'] == 'processing'): ?>
                            <span class="badge status-processing">
                                <i class="fa-solid fa-spinner fa-spin"></i> Processing...
                            </span>

                        <?php else: ?>
                            <span style="color:#999; font-size:12px; font-weight:bold;">Completed</span>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="7" style="text-align:center; padding:30px; font-size:16px; color:#666;">No requests found.</td></tr>
        <?php endif; ?>
    </tbody>
</table>
</div>

<div class="pagination">
    <?php for($i=1;$i<=$total_pages;$i++): 
        $page_url = "?page=$i" . ($current_params ? "&" . $current_params : "");
    ?>
        <a href="<?=$page_url?>" class="<?=$i==$page?'active':''?>"><?=$i?></a>
    <?php endfor; ?>
</div>

<script>
function payViaGateway(id) {
    if(confirm("Are you sure you want to pay via watchpay?")) {
        window.location.href = "admin_payout.php?id=" + id;
    }
}

function payViaTP(id) {
    if(confirm("Are you sure you want to process this payout via TopPay (TP)?")) {
        window.location.href = "adminpayout2.php?id=" + id;
    }
}

// NEW: NK Function
function payViaNK(id) {
    if(confirm("Are you sure you want to process this payout via Nekpay (NK)?")) {
        window.location.href = "adminpayout3.php?id=" + id;
    }
}
</script>

</body>
</html>