<?php
require 'element/connection.php';
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check user authentication
$user_id = $_SESSION['user_id'] ?? 0;
if (!$user_id) {
    header("Location: ../index.php");
    exit();
}

// Fetch user details
$user_query = mysqli_query($conn, "SELECT * FROM users WHERE user_id = '$user_id'");
$user_data = mysqli_fetch_assoc($user_query);
$my_id = $user_id;

// Handle PIN generation
if (isset($_POST['generate_pins'])) {
    $count = intval($_POST['pin_count']);
    $prefix = mysqli_real_escape_string($conn, $_POST['pin_prefix']);
    $notes = mysqli_real_escape_string($conn, $_POST['pin_notes']);
    $product_id = intval($_POST['product_id']);
    
    if ($count > 0 && $count <= 100) {
        $generated = 0;
        for ($i = 0; $i < $count; $i++) {
            $pin = $prefix . rand(100000, 999999) . rand(1000, 9999);
            $check = mysqli_query($conn, "SELECT * FROM pin WHERE pin_value = '$pin'");
            if (mysqli_num_rows($check) == 0) {
                mysqli_query($conn, "INSERT INTO pin (pin_value, allcote_user, status, notes, product_id, created_at) 
                                    VALUES ('$pin', '$my_id', '0', '$notes', '$product_id', NOW())");
                $generated++;
            }
        }
        $message = "$generated PINs generated successfully!";
        $message_type = "success";
    }
}

// Handle PIN transfer
if (isset($_POST['transfer_pin'])) {
    $pin_id = intval($_POST['pin_id']);
    $to_user = mysqli_real_escape_string($conn, $_POST['to_user']);
    $transfer_notes = mysqli_real_escape_string($conn, $_POST['transfer_notes']);
    
    // Check if user exists
    $user_check = mysqli_query($conn, "SELECT * FROM users WHERE user_id = '$to_user' OR name = '$to_user'");
    if (mysqli_num_rows($user_check) > 0) {
        $target_user = mysqli_fetch_assoc($user_check);
        mysqli_query($conn, "UPDATE pin SET allcote_user = '".$target_user['user_id']."', 
                            transfer_notes = '$transfer_notes', 
                            transferred_at = NOW() 
                            WHERE id = '$pin_id' AND allcote_user = '$my_id'");
        $message = "PIN transferred successfully!";
        $message_type = "success";
    } else {
        $message = "Target user not found!";
        $message_type = "danger";
    }
}

// Handle PIN deletion
if (isset($_POST['delete_pin'])) {
    $pin_id = intval($_POST['pin_id']);
    mysqli_query($conn, "DELETE FROM pin WHERE id = '$pin_id' AND allcote_user = '$my_id' AND status = '0'");
    $message = "PIN deleted successfully!";
    $message_type = "success";
}

// Fetch all user's pins
$pins_query = mysqli_query($conn, "SELECT * FROM pin WHERE allcote_user = '$my_id' ORDER BY 
                                   CASE WHEN status = '0' THEN 0 ELSE 1 END, 
                                   created_at DESC");
$pins = [];
while ($row = mysqli_fetch_assoc($pins_query)) {
    $pins[] = $row;
}

// Get stats
$total_pins = count($pins);
$available_pins = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM pin WHERE allcote_user = '$my_id' AND status = '0'"));
$used_pins = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM pin WHERE allcote_user = '$my_id' AND status = '1'"));
$transferred_pins = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM pin WHERE allcote_user != '$my_id'"));
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title><?php echo htmlspecialchars($user_data['name']); ?> || E-PIN Management</title>
    <meta content="" name="description">
    <meta content="" name="keywords">

    <!-- Favicons -->
    <link href="../img/logo/logo22222.png" rel="icon">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" 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/quill/quill.snow.css" rel="stylesheet">
    <link href="assets/vendor/quill/quill.bubble.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">

    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --warning-gradient: linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%);
            --danger-gradient: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
            --dark-gradient: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
            --primary-color: #667eea;
            --secondary-color: #764ba2;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
        }

        /* Modern Card Design */
        .modern-card {
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            border: none;
            transition: all 0.3s ease;
            overflow: hidden;
            margin-bottom: 25px;
        }

        .modern-card:hover {
            box-shadow: 0 30px 60px rgba(102, 126, 234, 0.15);
        }

        .card-header-modern {
            padding: 25px 30px;
            background: var(--primary-gradient);
            color: white;
            border-bottom: none;
        }

        .card-header-modern h5 {
            margin: 0;
            font-weight: 700;
            font-size: 1.3rem;
            letter-spacing: 0.5px;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 25px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            border: 1px solid rgba(102, 126, 234, 0.1);
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.15);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
            font-size: 24px;
        }

        .stat-icon.available { background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%); }
        .stat-icon.used { background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%); }
        .stat-icon.transferred { background: linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%); }
        .stat-icon.total { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }

        .stat-value {
            font-size: 2.5rem;
            font-weight: 800;
            margin-bottom: 5px;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .stat-label {
            color: #64748b;
            font-weight: 600;
            font-size: 0.95rem;
            letter-spacing: 0.5px;
        }

        /* Table Styles */
        .pin-table-container {
            overflow-x: auto;
            border-radius: 16px;
        }

        .pin-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 10px;
        }

        .pin-table thead th {
            background: #f8fafc;
            color: #334155;
            font-weight: 700;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            padding: 15px 20px;
            border: none;
        }

        .pin-table tbody tr {
            background: white;
            border-radius: 16px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.03);
            transition: all 0.3s ease;
        }

        .pin-table tbody tr:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
        }

        .pin-table tbody td {
            padding: 20px;
            vertical-align: middle;
            border: none;
        }

        .pin-table tbody td:first-child {
            border-radius: 16px 0 0 16px;
        }

        .pin-table tbody td:last-child {
            border-radius: 0 16px 16px 0;
        }

        .pin-code {
            font-family: 'Courier New', monospace;
            font-weight: 700;
            font-size: 1.2rem;
            letter-spacing: 1px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .product-badge {
            padding: 6px 15px;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .product-kit1 {
            background: #dbeafe;
            color: #1e40af;
        }

        .product-kit2 {
            background: #dcfce7;
            color: #166534;
        }

        .status-badge {
            padding: 6px 15px;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .status-available {
            background: #dcfce7;
            color: #166534;
        }

        .status-used {
            background: #fee2e2;
            color: #991b1b;
        }

        .status-transferred {
            background: #dbeafe;
            color: #1e40af;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 8px 12px;
            border: none;
            border-radius: 10px;
            font-size: 0.85rem;
            font-weight: 600;
            transition: all 0.3s ease;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .btn-action:hover {
            transform: translateY(-2px);
        }

        .btn-copy { background: #e2e8f0; color: #334155; }
        .btn-copy:hover { background: #cbd5e1; }

        .btn-share { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-share:hover { opacity: 0.9; }

        .btn-transfer { background: #dbeafe; color: #1e40af; }
        .btn-transfer:hover { background: #bfdbfe; }

        .btn-delete { background: #fee2e2; color: #991b1b; }
        .btn-delete:hover { background: #fecaca; }

        /* Form Elements */
        .form-control-modern {
            width: 100%;
            padding: 14px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control-modern:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            outline: none;
        }

        .btn-modern {
            padding: 14px 30px;
            border: none;
            border-radius: 16px;
            font-weight: 600;
            font-size: 1rem;
            transition: all 0.3s ease;
            cursor: pointer;
            background: var(--primary-gradient);
            color: white;
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 30px rgba(102, 126, 234, 0.4);
        }

        /* Tabs */
        .modern-tabs {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }

        .modern-tab {
            padding: 12px 25px;
            border-radius: 40px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            color: #64748b;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            border: 1px solid #e2e8f0;
        }

        .modern-tab:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
        }

        .modern-tab.active {
            background: var(--primary-gradient);
            color: white;
            border-color: transparent;
        }

        /* Share Modal */
        .share-options {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin: 25px 0;
        }

        .share-option {
            text-align: center;
            padding: 20px;
            border-radius: 16px;
            background: #f8fafc;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .share-option:hover {
            transform: translateY(-5px);
            background: var(--primary-gradient);
            color: white;
        }

        .share-option i {
            font-size: 32px;
            margin-bottom: 10px;
        }

        .share-link-box {
            background: #f1f5f9;
            padding: 15px 20px;
            border-radius: 16px;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .share-link-box input {
            flex: 1;
            border: none;
            background: transparent;
            font-size: 0.95rem;
            color: #334155;
        }

        .share-link-box button {
            padding: 10px 20px;
            border: none;
            border-radius: 12px;
            background: var(--primary-gradient);
            color: white;
            font-weight: 600;
            cursor: pointer;
        }

        /* Animations */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .animate-slide {
            animation: slideIn 0.5s ease forwards;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .pin-table tbody td {
                padding: 15px;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .btn-action {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>

<body>

    <!-- Header & Sidebar -->
    <?php include 'element/header.php'; ?>
    <?php include 'element/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>E-PIN Management</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">E-PIN Management</li>
                </ol>
            </nav>
        </div>

        <!-- Alert Messages -->
        <?php if (isset($message)): ?>
            <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show animate-slide" role="alert">
                <i class="bi bi-<?php echo $message_type == 'success' ? 'check-circle' : 'exclamation-circle'; ?> me-2"></i>
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon available">
                    <i class="fas fa-ticket-alt" style="color: #166534;"></i>
                </div>
                <div class="stat-value"><?php echo $available_pins; ?></div>
                <div class="stat-label">Available E-PINs</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon used">
                    <i class="fas fa-check-circle" style="color: #991b1b;"></i>
                </div>
                <div class="stat-value"><?php echo $used_pins; ?></div>
                <div class="stat-label">Used E-PINs</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon transferred">
                    <i class="fas fa-exchange-alt" style="color: #1e40af;"></i>
                </div>
                <div class="stat-value"><?php echo $transferred_pins; ?></div>
                <div class="stat-label">Transferred</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon total">
                    <i class="fas fa-layer-group" style="color: white;"></i>
                </div>
                <div class="stat-value"><?php echo $total_pins; ?></div>
                <div class="stat-label">Total E-PINs</div>
            </div>
        </div>

        <!-- Modern Tabs -->
        <div class="modern-tabs">
            <div class="modern-tab active" onclick="showTab('all')">All E-PINs</div>
            <div class="modern-tab" onclick="showTab('available')">Available</div>
            <div class="modern-tab" onclick="showTab('used')">Used</div>
            <div class="modern-tab" onclick="showTab('transferred')">Transferred</div>
            <div class="modern-tab" onclick="showTab('generate')">Generate New</div>
        </div>

        <!-- Generate PIN Form (Hidden by default) -->
        <div id="generate-tab" style="display: none;">
            <div class="modern-card">
                <div class="card-header-modern">
                    <h5><i class="fas fa-plus-circle me-2"></i> Generate New E-PINs</h5>
                </div>
                <div class="card-body p-4">
                    <form method="POST" class="row g-4">
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Number of PINs</label>
                            <input type="number" name="pin_count" class="form-control-modern" 
                                   min="1" max="100" value="5" required>
                            <small class="text-muted">Max 100 at a time</small>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold">PIN Prefix (Optional)</label>
                            <input type="text" name="pin_prefix" class="form-control-modern" 
                                   placeholder="e.g., HLM" maxlength="10">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Product</label>
                            <select name="product_id" class="form-control-modern" required>
                                <option value="1">Kit ONE (Product ID: 1)</option>
                                <option value="2">Kit TWO (Product ID: 2)</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Notes</label>
                            <input type="text" name="pin_notes" class="form-control-modern" 
                                   placeholder="Any remarks">
                        </div>
                        <div class="col-12">
                            <button type="submit" name="generate_pins" class="btn-modern">
                                <i class="fas fa-magic me-2"></i> Generate E-PINs
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- PINs Table -->
        <div class="modern-card">
            <div class="card-header-modern">
                <h5><i class="fas fa-list me-2"></i> Your E-PINs</h5>
            </div>
            <div class="card-body p-4">
                <?php if (empty($pins)): ?>
                    <div class="text-center py-5">
                        <img src="assets/img/empty.svg" alt="No PINs" style="max-width: 200px; opacity: 0.5;">
                        <h4 class="mt-4 text-muted">No E-PINs Found</h4>
                        <p class="text-muted">Generate new E-PINs to get started</p>
                        <button class="btn-modern" onclick="showTab('generate')">
                            <i class="fas fa-plus-circle me-2"></i> Generate Now
                        </button>
                    </div>
                <?php else: ?>
                    <div class="pin-table-container">
                        <table class="pin-table" id="pin-table">
                            <thead>
                                <tr>
                                    <th>PIN Code</th>
                                    <th>Product</th>
                                    <th>Status</th>
                                    <th>Created Date</th>
                                    <th>Notes</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="pin-table-body">
                                <?php foreach ($pins as $pin): 
                                    $status_class = $pin['status'] == 0 ? 'available' : ($pin['status'] == 1 ? 'used' : 'transferred');
                                    $product_name = $pin['product_id'] == 1 ? 'Kit ONE' : 'Kit TWO';
                                    $product_class = $pin['product_id'] == 1 ? 'product-kit1' : 'product-kit2';
                                ?>
                                    <tr data-status="<?php echo $status_class; ?>" data-product="<?php echo $pin['product_id']; ?>">
                                        <td>
                                            <span class="pin-code"><?php echo chunk_split($pin['pin_value'], 4, ' '); ?></span>
                                        </td>
                                        <td>
                                            <span class="product-badge <?php echo $product_class; ?>">
                                                <i class="fas <?php echo $pin['product_id'] == 1 ? 'fa-box' : 'fa-boxes'; ?>"></i>
                                                <?php echo $product_name; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="status-badge status-<?php echo $status_class; ?>">
                                                <i class="fas fa-<?php echo $status_class == 'available' ? 'check-circle' : ($status_class == 'used' ? 'times-circle' : 'exchange-alt'); ?>"></i>
                                                <?php echo ucfirst($status_class); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <i class="fas fa-calendar-alt me-2 text-muted"></i>
                                            <?php echo date('d M Y', strtotime($pin['created_at'])); ?>
                                        </td>
                                        <td>
                                            <?php if (!empty($pin['notes'])): ?>
                                                <span class="text-muted">
                                                    <i class="fas fa-sticky-note me-1"></i>
                                                    <?php echo htmlspecialchars($pin['notes']); ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="btn-action btn-copy" onclick="copyPIN('<?php echo $pin['pin_value']; ?>')">
                                                    <i class="fas fa-copy"></i> Copy
                                                </button>
                                                
                                                <?php if ($pin['status'] == 0): ?>
                                                    <button class="btn-action btn-share" onclick="sharePIN('<?php echo $pin['pin_value']; ?>', <?php echo $pin['product_id']; ?>)">
                                                        <i class="fas fa-share-alt"></i> Share
                                                    </button>
                                                    
                                                    <button class="btn-action btn-transfer" onclick="transferPIN(<?php echo $pin['id']; ?>)">
                                                        <i class="fas fa-exchange-alt"></i> Transfer
                                                    </button>
                                                    
                                                <?php endif; ?>
                                            </div>
                                            
                                            <?php if (!empty($pin['transfer_notes'])): ?>
                                                <div class="mt-2 small text-muted">
                                                    <i class="fas fa-info-circle me-1 text-info"></i>
                                                    <?php echo htmlspecialchars($pin['transfer_notes']); ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <a href="#" class="back-to-top d-flex align-items-center justify-content-center">
        <i class="bi bi-arrow-up-short"></i>
    </a>

    <!-- Share Modal -->
    <div class="modal fade" id="shareModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content" style="border-radius: 24px;">
                <div class="modal-header border-0" style="background: var(--primary-gradient); color: white; border-radius: 24px 24px 0 0;">
                    <h5 class="modal-title"><i class="fas fa-share-alt me-2"></i> Share E-PIN</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="text-center mb-4">
                        <div class="pin-code" id="sharePinValue" style="font-size: 1.8rem;"></div>
                        <div class="mt-2" id="shareProductInfo"></div>
                    </div>
                    
                    <!-- Share Options -->
                    <div class="share-options">
                        <div class="share-option" onclick="shareVia('whatsapp')">
                            <i class="fab fa-whatsapp" style="color: #25D366;"></i>
                            <div>WhatsApp</div>
                        </div>
                        <div class="share-option" onclick="shareVia('telegram')">
                            <i class="fab fa-telegram" style="color: #0088cc;"></i>
                            <div>Telegram</div>
                        </div>
                        <div class="share-option" onclick="shareVia('facebook')">
                            <i class="fab fa-facebook" style="color: #1877f2;"></i>
                            <div>Facebook</div>
                        </div>
                        <div class="share-option" onclick="shareVia('email')">
                            <i class="fas fa-envelope" style="color: #EA4335;"></i>
                            <div>Email</div>
                        </div>
                    </div>
                    
                    <!-- Registration Link -->
                    <div class="mt-4">
                        <label class="form-label fw-bold">Registration Link with PIN</label>
                        <div class="share-link-box">
                            <input type="text" id="registrationLink" readonly value="">
                            <button onclick="copyRegistrationLink()">
                                <i class="fas fa-copy"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- QR Code -->
                    <div class="text-center mt-4">
                        <div class="qr-container" id="qrContainer" style="display: inline-block; background: white; padding: 15px; border-radius: 16px; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
                            <div id="qrCode"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Transfer Modal -->
    <div class="modal fade" id="transferModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content" style="border-radius: 24px;">
                <div class="modal-header border-0" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; border-radius: 24px 24px 0 0;">
                    <h5 class="modal-title"><i class="fas fa-exchange-alt me-2"></i> Transfer E-PIN</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <form method="POST" id="transferForm">
                        <input type="hidden" name="pin_id" id="transferPinId">
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Transfer to (User ID/Username)</label>
                            <input type="text" name="to_user" class="form-control-modern" 
                                   placeholder="Enter user ID or username" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Notes (Optional)</label>
                            <textarea name="transfer_notes" class="form-control-modern" 
                                      rows="2" placeholder="Add transfer notes"></textarea>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            This PIN will be transferred to the specified user. They will be able to use it for registration.
                        </div>
                        
                        <button type="submit" name="transfer_pin" class="btn-modern w-100">
                            <i class="fas fa-exchange-alt me-2"></i> Transfer PIN
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content" style="border-radius: 24px;">
                <div class="modal-header border-0" style="background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%); color: white; border-radius: 24px 24px 0 0;">
                    <h5 class="modal-title"><i class="fas fa-trash me-2"></i> Delete E-PIN</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4 text-center">
                    <i class="fas fa-exclamation-triangle fa-4x text-warning mb-3"></i>
                    <h4>Are you sure?</h4>
                    <p class="text-muted">This action cannot be undone. The PIN will be permanently deleted.</p>
                    
                    <form method="POST" id="deleteForm">
                        <input type="hidden" name="pin_id" id="deletePinId">
                        <div class="d-flex gap-3 justify-content-center">
                            <button type="button" class="btn-modern-outline" data-bs-dismiss="modal">
                                <i class="fas fa-times me-2"></i> Cancel
                            </button>
                            <button type="submit" name="delete_pin" class="btn-modern" style="background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);">
                                <i class="fas fa-trash me-2"></i> Delete
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/jquery/jquery-3.6.0.min.js"></script>
    <script src="assets/js/main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>

    <script>
        let currentPin = '';
        let currentProduct = 1;
        let shareModal = new bootstrap.Modal(document.getElementById('shareModal'));
        let transferModal = new bootstrap.Modal(document.getElementById('transferModal'));
        let deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

        // Tab switching
        function showTab(tab) {
            // Update tab buttons
            document.querySelectorAll('.modern-tab').forEach(t => {
                t.classList.remove('active');
            });
            event.target.classList.add('active');
            
            // Show/hide generate tab
            if (tab === 'generate') {
                document.getElementById('generate-tab').style.display = 'block';
            } else {
                document.getElementById('generate-tab').style.display = 'none';
                filterPins(tab);
            }
        }
        
        // Filter PINs
        function filterPins(status) {
            const rows = document.querySelectorAll('#pin-table-body tr');
            rows.forEach(row => {
                if (status === 'all') {
                    row.style.display = 'table-row';
                } else {
                    if (row.dataset.status === status) {
                        row.style.display = 'table-row';
                    } else {
                        row.style.display = 'none';
                    }
                }
            });
        }
        
        // Copy PIN
        function copyPIN(pin) {
            navigator.clipboard.writeText(pin).then(() => {
                showNotification('PIN copied to clipboard!', 'success');
            });
        }
        
        // Share PIN
        // Share PIN - FIXED with sponsor ID, E-PIN, and package
function sharePIN(pin, productId) {
    currentPin = pin;
    currentProduct = productId;
    
    document.getElementById('sharePinValue').textContent = pin.match(/.{1,4}/g).join(' ');
    
    const productName = productId == 1 ? '2500' : '3500';
    const sponsorId = '<?php echo $my_id; ?>'; // Current user's ID is the sponsor
    
    document.getElementById('shareProductInfo').innerHTML = `
        <span class="product-badge ${productId == 1 ? 'product-kit1' : 'product-kit2'}">
            <i class="fas ${productId == 1 ? 'fa-box' : 'fa-boxes'}"></i>
            ₹${productName} Package
        </span>
        <div class="mt-2">
            <small>Sponsor ID: ${sponsorId}</small>
        </div>
    `;
    
    // FIXED: Create registration link with sponsor ID, E-PIN, and package
    // sponsor= is the referrer's user ID (who is sharing)
    // epin= is the actual E-PIN value
    // package= is the package ID
    const baseUrl = window.location.origin + '/sdb-innovation/register.php';
    const regLink = baseUrl + '?sponsor=' + sponsorId + '&epin=' + pin + '&package=' + productId;
    document.getElementById('registrationLink').value = regLink;
    
    // Generate QR code
    document.getElementById('qrCode').innerHTML = '';
    new QRCode(document.getElementById('qrCode'), {
        text: regLink,
        width: 200,
        height: 200,
        colorDark: "#667eea",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });
    
    shareModal.show();
}
        
        // Share via social media
        function shareVia(platform) {
            const link = document.getElementById('registrationLink').value;
            const productName = currentProduct == 1 ? 'Kit ONE' : 'Kit TWO';
            const text = `Join using my E-PIN for ${productName}: ${currentPin}`;
            let url = '';
            
            switch(platform) {
                case 'whatsapp':
                    url = `https://wa.me/?text=${encodeURIComponent(text + ' ' + link)}`;
                    break;
                case 'telegram':
                    url = `https://t.me/share/url?url=${encodeURIComponent(link)}&text=${encodeURIComponent(text)}`;
                    break;
                case 'facebook':
                    url = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(link)}`;
                    break;
                case 'email':
                    url = `mailto:?subject=${encodeURIComponent('Registration E-PIN for ' + productName)}&body=${encodeURIComponent(text + '\n\n' + link)}`;
                    break;
            }
            
            if (url) window.open(url, '_blank');
        }
        
        // Copy registration link
        function copyRegistrationLink() {
            const link = document.getElementById('registrationLink');
            link.select();
            navigator.clipboard.writeText(link.value).then(() => {
                showNotification('Registration link copied!', 'success');
            });
        }
        
        // Transfer PIN
        function transferPIN(pinId) {
            document.getElementById('transferPinId').value = pinId;
            transferModal.show();
        }
        
        // Delete PIN
        function deletePIN(pinId) {
            document.getElementById('deletePinId').value = pinId;
            deleteModal.show();
        }
        
        // Show notification
        function showNotification(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3 animate-slide`;
            alertDiv.style.zIndex = '9999';
            alertDiv.innerHTML = `
                <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => alertDiv.remove(), 3000);
        }
        
        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            // Show all PINs initially
            filterPins('all');
        });
    </script>

    <!-- Add DataTables for enhanced table features (optional) -->
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        // Optional: Initialize DataTable for advanced features
        $(document).ready(function() {
            if ($('#pin-table tbody tr').length > 10) {
                $('#pin-table').DataTable({
                    pageLength: 25,
                    responsive: true,
                    language: {
                        search: "Search PINs:",
                        lengthMenu: "Show _MENU_ PINs per page",
                        info: "Showing _START_ to _END_ of _TOTAL_ PINs"
                    }
                });
            }
        });
    </script>

</body>
</html>