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

$conn = getConnection();
$message = '';
$message_type = '';

// Handle PIN transfer
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    if ($_POST['action'] === 'transfer_pin') {
        $pin_id = intval($_POST['pin_id']);
        $from_user_id = intval($_POST['from_user_id']);
        $to_user_id = intval($_POST['to_user_id']);
        $notify_user = isset($_POST['notify_user']) ? 1 : 0;
        $transfer_notes = sanitize($conn, $_POST['transfer_notes'] ?? '');
        
        // Validate users exist
        $check_from = mysqli_query($conn, "SELECT user_id, name FROM users WHERE user_id = $from_user_id");
        $check_to = mysqli_query($conn, "SELECT user_id, name, email, mobile FROM users WHERE user_id = $to_user_id");
        
        if (mysqli_num_rows($check_from) == 0) {
            $_SESSION['flash_message'] = "Source user not found!";
            $_SESSION['flash_type'] = "danger";
        } elseif (mysqli_num_rows($check_to) == 0) {
            $_SESSION['flash_message'] = "Destination user not found!";
            $_SESSION['flash_type'] = "danger";
        } else {
            $from_user = mysqli_fetch_assoc($check_from);
            $to_user = mysqli_fetch_assoc($check_to);
            
            // Start transaction
            mysqli_begin_transaction($conn);
            
            try {
                // Check if pin exists and belongs to from_user and is unused
                $check_pin = mysqli_query($conn, "SELECT * FROM pin WHERE id = $pin_id AND allcote_user = $from_user_id AND status = 0");
                
                if (mysqli_num_rows($check_pin) == 0) {
                    throw new Exception("PIN not found, already used, or doesn't belong to source user!");
                }
                
                $pin_data = mysqli_fetch_assoc($check_pin);
                
                // Update PIN ownership
                $transferred_at = date('Y-m-d H:i:s');
                $stmt = mysqli_prepare($conn, "UPDATE pin SET allcote_user = ?, transferred_at = ?, transfer_notes = ? WHERE id = ?");
                mysqli_stmt_bind_param($stmt, "issi", $to_user_id, $transferred_at, $transfer_notes, $pin_id);
                
                if (!mysqli_stmt_execute($stmt)) {
                    throw new Exception("Failed to transfer PIN: " . mysqli_error($conn));
                }
                mysqli_stmt_close($stmt);
                
                // Log the transfer in income history
                $description = "PIN Transfer: PIN {$pin_data['pin_value']} transferred from User $from_user_id to User $to_user_id";
                $trans_id = 'TRF' . time() . rand(100, 999);
                $credit_debit = 0;
                $amount = 0;
                $income_type = 'pin_transfer';
                
                $stmt = mysqli_prepare($conn, "INSERT INTO income_history 
                    (user_id, amount, description, credit_debit, income_type, transaction_id, created_at, from_user_id, to_user_id, pin_value) 
                    VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?)");
                
                mysqli_stmt_bind_param($stmt, "iisissiii", $from_user_id, $amount, $description, $credit_debit, $income_type, $trans_id, $from_user_id, $to_user_id, $pin_data['pin_value']);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
                
                mysqli_commit($conn);
                
                $_SESSION['flash_message'] = "PIN #{$pin_data['pin_value']} transferred successfully from User $from_user_id to User $to_user_id!";
                $_SESSION['flash_type'] = "success";
                
            } catch (Exception $e) {
                mysqli_rollback($conn);
                $_SESSION['flash_message'] = "Error: " . $e->getMessage();
                $_SESSION['flash_type'] = "danger";
            }
        }
        
        header("Location: pin-list.php");
        exit();
    }
    
    elseif ($_POST['action'] === 'bulk_transfer') {
        $from_user_id = intval($_POST['from_user_id']);
        $to_user_id = intval($_POST['to_user_id']);
        $package_filter = isset($_POST['package_filter']) ? intval($_POST['package_filter']) : 0;
        $transfer_all = isset($_POST['transfer_all']) ? 1 : 0;
        $selected_pins = isset($_POST['selected_pins']) ? $_POST['selected_pins'] : [];
        $notify_user = isset($_POST['notify_user']) ? 1 : 0;
        $transfer_notes = sanitize($conn, $_POST['transfer_notes'] ?? '');
        
        if (empty($from_user_id) || empty($to_user_id)) {
            $_SESSION['flash_message'] = "Please select both source and destination users!";
            $_SESSION['flash_type'] = "danger";
            header("Location: pin-list.php");
            exit();
        }
        
        // Build query for pins to transfer
        $pin_condition = "allcote_user = $from_user_id AND status = 0";
        if (!$transfer_all && !empty($selected_pins)) {
            $pin_ids = implode(',', array_map('intval', $selected_pins));
            $pin_condition .= " AND id IN ($pin_ids)";
        } elseif ($package_filter > 0) {
            $pin_condition .= " AND package_id = $package_filter";
        }
        
        // Get pins to transfer
        $pins_to_transfer = mysqli_query($conn, "SELECT * FROM pin WHERE $pin_condition");
        $pin_count = mysqli_num_rows($pins_to_transfer);
        
        if ($pin_count == 0) {
            $_SESSION['flash_message'] = "No pins found to transfer!";
            $_SESSION['flash_type'] = "warning";
            header("Location: pin-list.php");
            exit();
        }
        
        // Start transaction
        mysqli_begin_transaction($conn);
        
        try {
            $transferred_at = date('Y-m-d H:i:s');
            $success_count = 0;
            $pin_values = [];
            
            while ($pin = mysqli_fetch_assoc($pins_to_transfer)) {
                $stmt = mysqli_prepare($conn, "UPDATE pin SET allcote_user = ?, transferred_at = ?, transfer_notes = ? WHERE id = ?");
                mysqli_stmt_bind_param($stmt, "issi", $to_user_id, $transferred_at, $transfer_notes, $pin['id']);
                
                if (mysqli_stmt_execute($stmt)) {
                    $success_count++;
                    $pin_values[] = $pin['pin_value'];
                }
                mysqli_stmt_close($stmt);
            }
            
            // Log bulk transfer
            $description = "Bulk PIN Transfer: " . $success_count . " PIN(s) transferred from User $from_user_id to User $to_user_id";
            if (!empty($pin_values)) {
                $description .= " - PINs: " . implode(', ', array_slice($pin_values, 0, 10)) . (count($pin_values) > 10 ? "..." : "");
            }
            
            $trans_id = 'BTRF' . time() . rand(100, 999);
            $credit_debit = 0;
            $amount = 0;
            $income_type = 'bulk_pin_transfer';
            
            $stmt = mysqli_prepare($conn, "INSERT INTO income_history 
                (user_id, amount, description, credit_debit, income_type, transaction_id, created_at, from_user_id, to_user_id) 
                VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?)");
            
            mysqli_stmt_bind_param($stmt, "iisissii", $from_user_id, $amount, $description, $credit_debit, $income_type, $trans_id, $from_user_id, $to_user_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
            
            mysqli_commit($conn);
            
            $_SESSION['flash_message'] = "$success_count PIN(s) transferred successfully from User $from_user_id to User $to_user_id!";
            $_SESSION['flash_type'] = "success";
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $_SESSION['flash_message'] = "Error during bulk transfer: " . $e->getMessage();
            $_SESSION['flash_type'] = "danger";
        }
        
        header("Location: pin-list.php");
        exit();
    }
    
    // Handle bulk PIN generation
    elseif ($_POST['action'] === 'bulk_generate') {
        $user_id = intval($_POST['user_id']);
        $package_2500_qty = intval($_POST['package_2500_qty'] ?? 0);
        $package_3500_qty = intval($_POST['package_3500_qty'] ?? 0);
        $total_pins = $package_2500_qty + $package_3500_qty;
        
        if ($total_pins == 0) {
            $_SESSION['flash_message'] = "Please enter quantity for at least one package!";
            $_SESSION['flash_type'] = "warning";
            header("Location: pin-list.php");
            exit();
        }
        
        // Validate user exists
        $check_user = mysqli_query($conn, "SELECT user_id FROM users WHERE user_id = $user_id");
        if (mysqli_num_rows($check_user) == 0) {
            $_SESSION['flash_message'] = "Invalid user selected!";
            $_SESSION['flash_type'] = "danger";
            header("Location: pin-list.php");
            exit();
        }
        
        // Start transaction
        mysqli_begin_transaction($conn);
        
        try {
            $created_at = date('Y-m-d H:i:s');
            $transferred_at = date('Y-m-d H:i:s');
            $generated_pins = [];
            $status = 0; // Default status (unused)
            
            // Generate ₹2500 PINs
            $package_2500 = 2500;
            for ($i = 0; $i < $package_2500_qty; $i++) {
                // Generate unique 5-digit PIN
                do {
                    $pin_value = rand(10000, 99999);
                    $check = mysqli_query($conn, "SELECT id FROM pin WHERE pin_value = $pin_value");
                } while (mysqli_num_rows($check) > 0);
                
                $stmt = mysqli_prepare($conn, "INSERT INTO pin (pin_value, allcote_user, status, created_at, package_id, transferred_at) VALUES (?, ?, ?, ?, ?, ?)");
                mysqli_stmt_bind_param($stmt, "iiissi", $pin_value, $user_id, $status, $created_at, $package_2500, $transferred_at);
                
                if (!mysqli_stmt_execute($stmt)) {
                    throw new Exception("Failed to generate ₹2500 PIN: " . mysqli_error($conn));
                }
                mysqli_stmt_close($stmt);
                
                $generated_pins[] = "₹2500: " . $pin_value;
            }
            
            // Generate ₹3500 PINs
            $package_3500 = 3500;
            for ($i = 0; $i < $package_3500_qty; $i++) {
                do {
                    $pin_value = rand(10000, 99999);
                    $check = mysqli_query($conn, "SELECT id FROM pin WHERE pin_value = $pin_value");
                } while (mysqli_num_rows($check) > 0);
                
                $stmt = mysqli_prepare($conn, "INSERT INTO pin (pin_value, allcote_user, status, created_at, package_id, transferred_at) VALUES (?, ?, ?, ?, ?, ?)");
                mysqli_stmt_bind_param($stmt, "iiissi", $pin_value, $user_id, $status, $created_at, $package_3500, $transferred_at);
                
                if (!mysqli_stmt_execute($stmt)) {
                    throw new Exception("Failed to generate ₹3500 PIN: " . mysqli_error($conn));
                }
                mysqli_stmt_close($stmt);
                
                $generated_pins[] = "₹3500: " . $pin_value;
            }
            
            // Log the generation in income_history
            $description = "Bulk PIN Generation: Generated $total_pins PIN(s) for User $user_id";
            $trans_id = 'GEN' . time() . rand(100, 999);
            $credit_debit = 0;
            $amount = 0;
            $income_type = 'pin_generation';
            
            $log_stmt = mysqli_prepare($conn, "INSERT INTO income_history 
                (user_id, amount, description, credit_debit, income_type, transaction_id, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, NOW())");
            
            mysqli_stmt_bind_param($log_stmt, "iisiss", $user_id, $amount, $description, $credit_debit, $income_type, $trans_id);
            
            if (!mysqli_stmt_execute($log_stmt)) {
                throw new Exception("Failed to log generation: " . mysqli_error($conn));
            }
            mysqli_stmt_close($log_stmt);
            
            mysqli_commit($conn);
            
            $_SESSION['flash_message'] = "Successfully generated $total_pins PIN(s) for User $user_id!<br><small>" . implode('<br>', array_slice($generated_pins, 0, 20)) . (count($generated_pins) > 20 ? "<br>... and " . (count($generated_pins) - 20) . " more" : "") . "</small>";
            $_SESSION['flash_type'] = "success";
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $_SESSION['flash_message'] = "Error generating PINs: " . $e->getMessage();
            $_SESSION['flash_type'] = "danger";
        }
        
        header("Location: pin-list.php");
        exit();
    }
    
    // Handle custom PIN generation
    elseif ($_POST['action'] === 'custom_generate') {
        $user_id = intval($_POST['user_id']);
        $package_id = intval($_POST['package_id']);
        $pin_values_input = trim($_POST['pin_values']);
        $status = 0; // Default status (unused)
        
        // Split by comma, newline, or space
        $pin_values = preg_split('/[\s,]+/', $pin_values_input);
        $pin_values = array_filter($pin_values); // Remove empty values
        
        if (empty($pin_values)) {
            $_SESSION['flash_message'] = "Please enter at least one PIN value!";
            $_SESSION['flash_type'] = "warning";
            header("Location: pin-list.php");
            exit();
        }
        
        if (!in_array($package_id, [2500, 3500])) {
            $_SESSION['flash_message'] = "Invalid package ID!";
            $_SESSION['flash_type'] = "danger";
            header("Location: pin-list.php");
            exit();
        }
        
        // Validate user exists
        $check_user = mysqli_query($conn, "SELECT user_id FROM users WHERE user_id = $user_id");
        if (mysqli_num_rows($check_user) == 0) {
            $_SESSION['flash_message'] = "Invalid user selected!";
            $_SESSION['flash_type'] = "danger";
            header("Location: pin-list.php");
            exit();
        }
        
        // Start transaction
        mysqli_begin_transaction($conn);
        
        try {
            $created_at = date('Y-m-d H:i:s');
            $transferred_at = date('Y-m-d H:i:s');
            $successful_pins = [];
            $failed_pins = [];
            
            foreach ($pin_values as $pin_value) {
                $pin_value = trim($pin_value);
                
                // Validate PIN is numeric and proper length
                if (!is_numeric($pin_value) || strlen($pin_value) < 4 || strlen($pin_value) > 10) {
                    $failed_pins[] = $pin_value . " (invalid format)";
                    continue;
                }
                
                // Check if PIN already exists
                $check = mysqli_query($conn, "SELECT id FROM pin WHERE pin_value = '$pin_value'");
                
                if (mysqli_num_rows($check) > 0) {
                    $failed_pins[] = $pin_value . " (already exists)";
                    continue;
                }
                
                $stmt = mysqli_prepare($conn, "INSERT INTO pin (pin_value, allcote_user, status, created_at, package_id, transferred_at) VALUES (?, ?, ?, ?, ?, ?)");
                mysqli_stmt_bind_param($stmt, "iiissi", $pin_value, $user_id, $status, $created_at, $package_id, $transferred_at);
                
                if (mysqli_stmt_execute($stmt)) {
                    $successful_pins[] = $pin_value;
                } else {
                    $failed_pins[] = $pin_value . " (insert failed)";
                }
                mysqli_stmt_close($stmt);
            }
            
            if (!empty($successful_pins)) {
                $description = "Custom PIN Generation: Generated " . count($successful_pins) . " PIN(s) for User $user_id";
                $trans_id = 'CUST' . time() . rand(100, 999);
                $credit_debit = 0;
                $amount = 0;
                $income_type = 'custom_pin_generation';
                
                $log_stmt = mysqli_prepare($conn, "INSERT INTO income_history 
                    (user_id, amount, description, credit_debit, income_type, transaction_id, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, NOW())");
                
                mysqli_stmt_bind_param($log_stmt, "iisiss", $user_id, $amount, $description, $credit_debit, $income_type, $trans_id);
                
                if (!mysqli_stmt_execute($log_stmt)) {
                    throw new Exception("Failed to log generation: " . mysqli_error($conn));
                }
                mysqli_stmt_close($log_stmt);
            }
            
            mysqli_commit($conn);
            
            $message_text = "Generated " . count($successful_pins) . " custom PIN(s) successfully!";
            if (!empty($failed_pins)) {
                $message_text .= " Failed: " . implode(', ', array_slice($failed_pins, 0, 10)) . (count($failed_pins) > 10 ? " and " . (count($failed_pins) - 10) . " more" : "");
            }
            
            $_SESSION['flash_message'] = $message_text;
            $_SESSION['flash_type'] = empty($failed_pins) ? "success" : "warning";
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $_SESSION['flash_message'] = "Error generating custom PINs: " . $e->getMessage();
            $_SESSION['flash_type'] = "danger";
        }
        
        header("Location: pin-list.php");
        exit();
    }
}

// Check for flash messages
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $message_type = $_SESSION['flash_type'];
    unset($_SESSION['flash_message']);
    unset($_SESSION['flash_type']);
}

// Get filter parameters
$status_filter = isset($_GET['status']) ? intval($_GET['status']) : -1;
$user_filter = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$package_filter = isset($_GET['package']) ? intval($_GET['package']) : 0;
$search = isset($_GET['search']) ? sanitize($conn, $_GET['search']) : '';

// Build WHERE clause
$where = [];
if ($status_filter >= 0) {
    $where[] = "p.status = $status_filter";
}
if ($user_filter > 0) {
    $where[] = "p.allcote_user = $user_filter";
}
if ($package_filter > 0) {
    $where[] = "p.package_id = $package_filter";
}
if (!empty($search)) {
    $where[] = "(p.pin_value LIKE '%$search%' OR u.name LIKE '%$search%' OR u.user_id LIKE '%$search%' OR u.mobile LIKE '%$search%')";
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// Pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

// Get total count
$total_result = mysqli_query($conn, "SELECT COUNT(*) as total FROM pin p LEFT JOIN users u ON p.allcote_user = u.user_id $where_clause");
$total = mysqli_fetch_assoc($total_result)['total'];
$total_pages = ceil($total / $limit);

// Get pins with user details
$pins = mysqli_query($conn, "SELECT p.*, u.name as user_name, u.mobile, u.email 
                              FROM pin p 
                              LEFT JOIN users u ON p.allcote_user = u.user_id 
                              $where_clause 
                              ORDER BY p.id DESC 
                              LIMIT $offset, $limit");

// Get all users for dropdowns
$users = mysqli_query($conn, "SELECT user_id, name, mobile FROM users ORDER BY name LIMIT 1000");

// Get statistics
$stats = [];
$result = mysqli_query($conn, "SELECT status, COUNT(*) as count FROM pin GROUP BY status");
while ($row = mysqli_fetch_assoc($result)) {
    $stats[$row['status']] = $row['count'];
}
$stats[0] = $stats[0] ?? 0;
$stats[1] = $stats[1] ?? 0;

// Get package stats
$package_stats = [];
$result = mysqli_query($conn, "SELECT package_id, COUNT(*) as count FROM pin WHERE package_id IN (2500, 3500) GROUP BY package_id");
while ($row = mysqli_fetch_assoc($result)) {
    $package_stats[$row['package_id']] = $row['count'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>PIN List & 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">
    
    <!-- Select2 for better dropdowns -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <style>
        .pin-card {
            transition: all 0.3s;
            border-left: 4px solid transparent;
        }
        .pin-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .pin-unused { border-left-color: #28a745; }
        .pin-used { border-left-color: #dc3545; }
        .stats-card {
            border-left: 4px solid;
            transition: all 0.3s;
        }
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .stats-total { border-left-color: #17a2b8; }
        .stats-unused { border-left-color: #28a745; }
        .stats-used { border-left-color: #dc3545; }
        .stats-2500 { border-left-color: #ffc107; }
        .stats-3500 { border-left-color: #6f42c1; }
        .generation-panel {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .transfer-panel {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .custom-panel {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .select2-container--bootstrap-5 .select2-selection {
            min-height: 38px;
        }
        .pin-value {
            font-family: monospace;
            font-size: 1.1em;
            font-weight: bold;
        }
        .nav-tabs .nav-link {
            color: #495057;
            font-weight: 500;
        }
        .nav-tabs .nav-link.active {
            color: #007bff;
            font-weight: 600;
        }
        .tab-pane {
            padding: 20px 0;
        }
        .quantity-input {
            width: 120px;
            display: inline-block;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <?php include 'includes/sidebar.php'; ?>

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

        <section class="section">
            <!-- Statistics Cards -->
            <div class="row">
                <div class="col-lg-3 col-md-6">
                    <div class="card stats-card stats-total mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-key fs-1 text-info"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h5 class="card-title mb-0">Total PINs</h5>
                                    <h2 class="mb-0"><?php echo number_format($stats[0] + $stats[1]); ?></h2>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-3 col-md-6">
                    <div class="card stats-card stats-unused mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-key-fill fs-1 text-success"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h5 class="card-title mb-0">Unused PINs</h5>
                                    <h2 class="mb-0"><?php echo number_format($stats[0]); ?></h2>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-3 col-md-6">
                    <div class="card stats-card stats-used mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-key fs-1 text-danger"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h5 class="card-title mb-0">Used PINs</h5>
                                    <h2 class="mb-0"><?php echo number_format($stats[1]); ?></h2>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-3 col-md-6">
                    <div class="card stats-card stats-2500 mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-coin fs-1 text-warning"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h5 class="card-title mb-0">₹2500 PINs</h5>
                                    <h2 class="mb-0"><?php echo number_format($package_stats[2500] ?? 0); ?></h2>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- PIN Generation & Management Tabs -->
            <div class="row">
                <div class="col-12">
                    <ul class="nav nav-tabs" id="pinManagementTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="bulk-gen-tab" data-bs-toggle="tab" data-bs-target="#bulk-gen" type="button" role="tab">
                                <i class="bi bi-plus-circle"></i> Bulk Generate PINs
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="custom-gen-tab" data-bs-toggle="tab" data-bs-target="#custom-gen" type="button" role="tab">
                                <i class="bi bi-pencil-square"></i> Custom PINs
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="transfer-tab" data-bs-toggle="tab" data-bs-target="#transfer" type="button" role="tab">
                                <i class="bi bi-arrow-left-right"></i> Transfer PINs
                            </button>
                        </li>
                    </ul>
                    
                    <div class="tab-content" id="pinManagementTabContent">
                        <!-- Bulk Generation Tab -->
                        <div class="tab-pane fade show active" id="bulk-gen" role="tabpanel">
                            <div class="generation-panel">
                                <h4><i class="bi bi-plus-circle"></i> Bulk PIN Generation</h4>
                                <p>Generate multiple PINs at once with adjustable quantities per package.</p>
                                
                                <form method="POST" class="row g-3">
                                    <input type="hidden" name="action" value="bulk_generate">
                                    
                                    <div class="col-md-6">
                                        <label class="form-label text-white">Assign to User</label>
                                        <select name="user_id" class="form-control user-select-bulk" required>
                                            <option value="">Select user</option>
                                            <?php 
                                            mysqli_data_seek($users, 0);
                                            while ($user = mysqli_fetch_assoc($users)): 
                                            ?>
                                                <option value="<?php echo $user['user_id']; ?>">
                                                    <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?> (<?php echo $user['mobile']; ?>)
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-3">
                                        <label class="form-label text-white">₹2500 PINs Quantity</label>
                                        <div class="input-group">
                                            <input type="number" name="package_2500_qty" class="form-control" min="0" max="1000" value="0" id="qty2500" onchange="updateTotal2500()">
                                            <span class="input-group-text">Total: ₹<span id="total2500">0</span></span>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-3">
                                        <label class="form-label text-white">₹3500 PINs Quantity</label>
                                        <div class="input-group">
                                            <input type="number" name="package_3500_qty" class="form-control" min="0" max="1000" value="0" id="qty3500" onchange="updateTotal3500()">
                                            <span class="input-group-text">Total: ₹<span id="total3500">0</span></span>
                                        </div>
                                    </div>
                                    
                                    <div class="col-12">
                                        <div class="alert alert-light">
                                            <strong>Grand Total:</strong> <span id="grandTotalQty">0</span> PINs | 
                                            <strong>Total Value:</strong> ₹<span id="grandTotalValue">0</span>
                                        </div>
                                    </div>
                                    
                                    <div class="col-12">
                                        <button type="submit" class="btn btn-light" onclick="return confirm('Generate PINs with these quantities?')">
                                            <i class="bi bi-lightning"></i> Generate PINs
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <!-- Custom Generation Tab -->
                        <div class="tab-pane fade" id="custom-gen" role="tabpanel">
                            <div class="custom-panel">
                                <h4><i class="bi bi-pencil-square"></i> Custom PIN Generation</h4>
                                <p>Enter specific PIN values (one per line or comma-separated)</p>
                                
                                <form method="POST" class="row g-3">
                                    <input type="hidden" name="action" value="custom_generate">
                                    
                                    <div class="col-md-4">
                                        <label class="form-label text-white">Assign to User</label>
                                        <select name="user_id" class="form-control user-select-bulk" required>
                                            <option value="">Select user</option>
                                            <?php 
                                            mysqli_data_seek($users, 0);
                                            while ($user = mysqli_fetch_assoc($users)): 
                                            ?>
                                                <option value="<?php echo $user['user_id']; ?>">
                                                    <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-2">
                                        <label class="form-label text-white">Package</label>
                                        <select name="package_id" class="form-control" required>
                                            <option value="">Select</option>
                                            <option value="2500">₹2500 Package</option>
                                            <option value="3500">₹3500 Package</option>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label text-white">PIN Values (one per line or comma-separated)</label>
                                        <textarea name="pin_values" class="form-control" rows="4" required placeholder="e.g.&#10;12345&#10;67890&#10;54321"></textarea>
                                    </div>
                                    
                                    <div class="col-12">
                                        <button type="submit" class="btn btn-light" onclick="return confirm('Generate these custom PINs?')">
                                            <i class="bi bi-save"></i> Generate Custom PINs
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <!-- Transfer Tab -->
                        <div class="tab-pane fade" id="transfer" role="tabpanel">
                            <div class="transfer-panel">
                                <h4><i class="bi bi-arrow-left-right"></i> PIN Transfer</h4>
                                
                                <!-- Quick Transfer -->
                                <div class="row mb-3">
                                    <div class="col-md-5">
                                        <label class="form-label text-white">From User</label>
                                        <select class="form-control user-select" id="transferFromUser">
                                            <option value="">Select source user</option>
                                            <?php 
                                            mysqli_data_seek($users, 0);
                                            while ($user = mysqli_fetch_assoc($users)): 
                                            ?>
                                                <option value="<?php echo $user['user_id']; ?>">
                                                    <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-5">
                                        <label class="form-label text-white">To User</label>
                                        <select class="form-control user-select" id="transferToUser">
                                            <option value="">Select destination user</option>
                                            <?php 
                                            mysqli_data_seek($users, 0);
                                            while ($user = mysqli_fetch_assoc($users)): 
                                            ?>
                                                <option value="<?php echo $user['user_id']; ?>">
                                                    <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2 d-flex align-items-end">
                                        <button class="btn btn-light w-100" onclick="loadUserPins()">
                                            <i class="bi bi-search"></i> Load PINs
                                        </button>
                                    </div>
                                </div>
                                
                                <!-- User PINs Display -->
                                <div id="userPinsContainer" style="display: none;">
                                    <h6 class="text-white" id="userPinsTitle"></h6>
                                    <div class="row bg-white p-3 rounded" id="userPinsList"></div>
                                </div>
                                
                                <!-- Bulk Transfer -->
                                <hr class="bg-white">
                                <h5 class="text-white">Bulk Transfer</h5>
                                
                                <form method="POST" id="bulkTransferForm">
                                    <input type="hidden" name="action" value="bulk_transfer">
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-5">
                                            <label class="form-label text-white">From User</label>
                                            <select name="from_user_id" class="form-control user-select-bulk" id="bulkFromUser" required>
                                                <option value="">Select source user</option>
                                                <?php 
                                                mysqli_data_seek($users, 0);
                                                while ($user = mysqli_fetch_assoc($users)): 
                                                ?>
                                                    <option value="<?php echo $user['user_id']; ?>">
                                                        <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-5">
                                            <label class="form-label text-white">To User</label>
                                            <select name="to_user_id" class="form-control user-select-bulk" required>
                                                <option value="">Select destination user</option>
                                                <?php 
                                                mysqli_data_seek($users, 0);
                                                while ($user = mysqli_fetch_assoc($users)): 
                                                ?>
                                                    <option value="<?php echo $user['user_id']; ?>">
                                                        <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-2 d-flex align-items-end">
                                            <button type="button" class="btn btn-light w-100" onclick="loadBulkUserPins()">
                                                <i class="bi bi-eye"></i> View PINs
                                            </button>
                                        </div>
                                    </div>
                                    
                                    <div id="bulkUserPinsContainer" style="display: none;" class="mb-3">
                                        <div class="alert alert-light">
                                            <h6>Available PINs for Transfer:</h6>
                                            <div id="bulkUserPinsList" class="row"></div>
                                        </div>
                                    </div>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label text-white">Filter by Package</label>
                                            <select name="package_filter" class="form-select">
                                                <option value="0">All Packages</option>
                                                <option value="2500">₹2500 Only</option>
                                                <option value="3500">₹3500 Only</option>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-8">
                                            <label class="form-label text-white">Options</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="transfer_all" id="transferAll" value="1">
                                                <label class="form-check-label text-white" for="transferAll">
                                                    Transfer ALL unused PINs
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="notify_user" id="notifyUserBulk" value="1">
                                                <label class="form-check-label text-white" for="notifyUserBulk">
                                                    Notify users
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label text-white">Transfer Notes</label>
                                        <textarea name="transfer_notes" class="form-control" rows="2"></textarea>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-light" onclick="return confirm('Execute bulk transfer?')">
                                        <i class="bi bi-arrow-left-right"></i> Execute Transfer
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Filters and PIN List -->
            <div class="row mt-4">
                <div class="col-12">
                    <?php if ($message): ?>
                        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                            <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Filters Card -->
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Filter PINs</h5>
                            
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">Status</label>
                                    <select name="status" class="form-select">
                                        <option value="-1" <?php echo $status_filter == -1 ? 'selected' : ''; ?>>All PINs</option>
                                        <option value="0" <?php echo $status_filter == 0 ? 'selected' : ''; ?>>Unused Only</option>
                                        <option value="1" <?php echo $status_filter == 1 ? 'selected' : ''; ?>>Used Only</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-3">
                                    <label class="form-label">Package</label>
                                    <select name="package" class="form-select">
                                        <option value="0">All Packages</option>
                                        <option value="2500" <?php echo $package_filter == 2500 ? 'selected' : ''; ?>>₹2500 Package</option>
                                        <option value="3500" <?php echo $package_filter == 3500 ? 'selected' : ''; ?>>₹3500 Package</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4">
                                    <label class="form-label">User</label>
                                    <select name="user_id" class="form-select user-select-single">
                                        <option value="0">All Users</option>
                                        <?php 
                                        mysqli_data_seek($users, 0);
                                        while ($user = mysqli_fetch_assoc($users)): 
                                        ?>
                                            <option value="<?php echo $user['user_id']; ?>" <?php echo $user_filter == $user['user_id'] ? 'selected' : ''; ?>>
                                                <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label class="form-label">Search</label>
                                    <input type="text" name="search" class="form-control" placeholder="PIN, Name, ID..." value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                
                                <div class="col-12 text-end">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-filter"></i> Apply Filters
                                    </button>
                                    <a href="pin-list.php" class="btn btn-secondary">
                                        <i class="bi bi-arrow-counterclockwise"></i> Reset
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- PIN List Table -->
                    <div class="card mt-3">
                        <div class="card-body">
                            <h5 class="card-title">PIN List</h5>
                            
                            <?php if (mysqli_num_rows($pins) > 0): ?>
                            <div class="table-responsive">
                                <table class="table table-striped datatable">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>PIN Value</th>
                                            <th>Package</th>
                                            <th>Owner</th>
                                            <th>Status</th>
                                            <th>Created</th>
                                            <th>Used/Transferred</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($pin = mysqli_fetch_assoc($pins)): ?>
                                        <tr>
                                            <td><?php echo $pin['id']; ?></td>
                                            <td class="pin-value"><?php echo $pin['pin_value']; ?></td>
                                            <td>
                                                <?php if ($pin['package_id'] == 2500): ?>
                                                    <span class="badge bg-warning">₹2500</span>
                                                <?php elseif ($pin['package_id'] == 3500): ?>
                                                    <span class="badge bg-purple" style="background-color: #6f42c1;">₹3500</span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">N/A</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($pin['allcote_user']): ?>
                                                    <strong><?php echo $pin['allcote_user']; ?></strong>
                                                    <?php if ($pin['user_name']): ?>
                                                        <br><small><?php echo htmlspecialchars($pin['user_name']); ?></small>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span class="text-muted">Unallocated</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($pin['status'] == 0): ?>
                                                    <span class="badge bg-success">Unused</span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger">Used</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo date('d M Y', strtotime($pin['created_at'])); ?></td>
                                            <td>
                                                <?php if ($pin['used_by']): ?>
                                                    Used by: <?php echo $pin['used_by']; ?><br>
                                                    <small><?php echo date('d M Y', strtotime($pin['used_at'])); ?></small>
                                                <?php elseif ($pin['transferred_at'] && $pin['transferred_at'] != '0000-00-00 00:00:00'): ?>
                                                    Transferred: <?php echo date('d M Y', strtotime($pin['transferred_at'])); ?>
                                                <?php else: ?>
                                                    -
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($pin['status'] == 0): ?>
                                                    <button type="button" class="btn btn-sm btn-warning" 
                                                            onclick="openTransferModal(<?php echo $pin['id']; ?>, <?php echo $pin['pin_value']; ?>, <?php echo $pin['allcote_user'] ?: 0; ?>, '<?php echo addslashes($pin['user_name']); ?>', <?php echo $pin['package_id']; ?>)">
                                                        <i class="bi bi-arrow-left-right"></i> Transfer
                                                    </button>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Pagination -->
                            <?php if ($total_pages > 1): ?>
                            <nav>
                                <ul class="pagination justify-content-center">
                                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $page-1; ?>&status=<?php echo $status_filter; ?>&user_id=<?php echo $user_filter; ?>&package=<?php echo $package_filter; ?>&search=<?php echo urlencode($search); ?>">Previous</a>
                                    </li>
                                    
                                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>&user_id=<?php echo $user_filter; ?>&package=<?php echo $package_filter; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $page+1; ?>&status=<?php echo $status_filter; ?>&user_id=<?php echo $user_filter; ?>&package=<?php echo $package_filter; ?>&search=<?php echo urlencode($search); ?>">Next</a>
                                    </li>
                                </ul>
                            </nav>
                            <?php endif; ?>
                            
                            <?php else: ?>
                                <div class="alert alert-info">No PINs found matching your criteria.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>
    
    <!-- Transfer Modal -->
    <div class="modal fade" id="transferPinModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title">Transfer PIN</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="transfer_pin">
                    <input type="hidden" name="pin_id" id="modalPinId">
                    <input type="hidden" name="from_user_id" id="modalFromUserId">
                    
                    <div class="modal-body">
                        <div class="alert alert-info" id="modalPinInfo"></div>
                        
                        <div class="mb-3">
                            <label class="form-label">Transfer To User</label>
                            <select name="to_user_id" class="form-control user-select-modal" id="modalToUser" required>
                                <option value="">Select destination user</option>
                                <?php 
                                mysqli_data_seek($users, 0);
                                while ($user = mysqli_fetch_assoc($users)): 
                                ?>
                                    <option value="<?php echo $user['user_id']; ?>">
                                        <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="notify_user" id="modalNotifyUser" value="1">
                                <label class="form-check-label" for="modalNotifyUser">
                                    Notify users about this transfer
                                </label>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Transfer Notes</label>
                            <textarea name="transfer_notes" class="form-control" rows="2"></textarea>
                        </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-warning" onclick="return confirm('Transfer this PIN?')">
                            Transfer PIN
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

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

    <!-- Scripts -->
    <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 src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
    // Initialize Select2
    $(document).ready(function() {
        $('.user-select, .user-select-bulk, .user-select-single').select2({
            theme: 'bootstrap-5',
            placeholder: 'Search for a user...',
            allowClear: true,
            width: '100%'
        });
        
        $('.user-select-modal').select2({
            theme: 'bootstrap-5',
            placeholder: 'Search for a user...',
            allowClear: true,
            width: '100%',
            dropdownParent: $('#transferPinModal')
        });
    });
    
    // Update total calculations for bulk generation
    function updateTotal2500() {
        var qty = parseInt(document.getElementById('qty2500').value) || 0;
        var total = qty * 2500;
        document.getElementById('total2500').innerText = total.toLocaleString();
        updateGrandTotal();
    }
    
    function updateTotal3500() {
        var qty = parseInt(document.getElementById('qty3500').value) || 0;
        var total = qty * 3500;
        document.getElementById('total3500').innerText = total.toLocaleString();
        updateGrandTotal();
    }
    
    function updateGrandTotal() {
        var qty2500 = parseInt(document.getElementById('qty2500').value) || 0;
        var qty3500 = parseInt(document.getElementById('qty3500').value) || 0;
        var totalQty = qty2500 + qty3500;
        var totalValue = (qty2500 * 2500) + (qty3500 * 3500);
        
        document.getElementById('grandTotalQty').innerText = totalQty;
        document.getElementById('grandTotalValue').innerText = totalValue.toLocaleString();
    }
    
    // Load user's PINs for quick transfer
    function loadUserPins() {
        var fromUser = document.getElementById('transferFromUser').value;
        var toUser = document.getElementById('transferToUser').value;
        
        if (!fromUser || !toUser) {
            alert('Please select both source and destination users!');
            return;
        }
        
        fetch('ajax/get_user_pins.php?user_id=' + fromUser)
            .then(response => response.json())
            .then(data => {
                var container = document.getElementById('userPinsContainer');
                var list = document.getElementById('userPinsList');
                var title = document.getElementById('userPinsTitle');
                
                if (data.success && data.pins.length > 0) {
                    title.innerHTML = 'PINs owned by User ' + fromUser + ' (Click to transfer)';
                    list.innerHTML = '';
                    
                    data.pins.forEach(pin => {
                        var pinCard = `
                            <div class="col-md-3 mb-2">
                                <div class="card pin-card pin-unused" onclick="quickTransferPin(${pin.id}, ${pin.pin_value}, ${fromUser}, ${toUser})" style="cursor: pointer;">
                                    <div class="card-body p-2">
                                        <h6 class="pin-value mb-1">${pin.pin_value}</h6>
                                        <small>Package: ₹${pin.package_id}</small>
                                    </div>
                                </div>
                            </div>
                        `;
                        list.innerHTML += pinCard;
                    });
                    
                    container.style.display = 'block';
                } else {
                    title.innerHTML = 'No unused PINs found for User ' + fromUser;
                    list.innerHTML = '<div class="col-12"><div class="alert alert-warning">No unused PINs available.</div></div>';
                    container.style.display = 'block';
                }
            });
    }
    
    // Quick transfer function
    function quickTransferPin(pinId, pinValue, fromUser, toUser) {
        if (confirm('Transfer PIN ' + pinValue + ' from User ' + fromUser + ' to User ' + toUser + '?')) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = 'pin-list.php';
            
            var inputs = {
                'action': 'transfer_pin',
                'pin_id': pinId,
                'from_user_id': fromUser,
                'to_user_id': toUser
            };
            
            for (var key in inputs) {
                var input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = inputs[key];
                form.appendChild(input);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
    }
    
    // Load bulk transfer user pins
    function loadBulkUserPins() {
        var fromUser = document.getElementById('bulkFromUser').value;
        
        if (!fromUser) {
            alert('Please select a source user!');
            return;
        }
        
        fetch('ajax/get_user_pins.php?user_id=' + fromUser)
            .then(response => response.json())
            .then(data => {
                var container = document.getElementById('bulkUserPinsContainer');
                var list = document.getElementById('bulkUserPinsList');
                
                if (data.success && data.pins.length > 0) {
                    list.innerHTML = '';
                    
                    data.pins.forEach(pin => {
                        var pinCheckbox = `
                            <div class="col-md-4 mb-2">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="selected_pins[]" value="${pin.id}" id="pin_${pin.id}">
                                    <label class="form-check-label" for="pin_${pin.id}">
                                        <strong>${pin.pin_value}</strong> (₹${pin.package_id})
                                    </label>
                                </div>
                            </div>
                        `;
                        list.innerHTML += pinCheckbox;
                    });
                    
                    container.style.display = 'block';
                } else {
                    list.innerHTML = '<div class="col-12">No unused PINs available for this user.</div>';
                    container.style.display = 'block';
                }
            });
    }
    
    // Open transfer modal
    function openTransferModal(pinId, pinValue, fromUserId, fromUserName, packageId) {
        document.getElementById('modalPinId').value = pinId;
        document.getElementById('modalFromUserId').value = fromUserId;
        document.getElementById('modalPinInfo').innerHTML = 
            '<strong>PIN:</strong> ' + pinValue + '<br>' +
            '<strong>Package:</strong> ₹' + packageId + '<br>' +
            '<strong>Current Owner:</strong> ' + (fromUserId ? fromUserId + ' (' + (fromUserName || 'Unknown') + ')' : 'Unallocated');
        
        var modal = new bootstrap.Modal(document.getElementById('transferPinModal'));
        modal.show();
    }
    
    // Handle Transfer All checkbox
    document.addEventListener('DOMContentLoaded', function() {
        var transferAllCheckbox = document.getElementById('transferAll');
        if (transferAllCheckbox) {
            transferAllCheckbox.addEventListener('change', function() {
                var checkboxes = document.querySelectorAll('input[name="selected_pins[]"]');
                checkboxes.forEach(cb => cb.disabled = this.checked);
            });
        }
    });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>