<?php
session_start();
require_once 'config/config.php';
require_once 'auth/check_auth.php';

// Check if user is logged in and has appropriate permissions
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'ID Cards Management';
$currentPage = 'id-cards';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- AdminLTE CSS -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap4.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <style>
        .id-card-preview {
            width: 320px;
            height: 200px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            padding: 20px;
            color: white;
            position: relative;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            margin: 20px auto;
        }
        
        .id-card-preview .card-header {
            text-align: center;
            font-size: 12px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .id-card-preview .member-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .id-card-preview .member-photo {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: #667eea;
        }
        
        .id-card-preview .member-details {
            flex: 1;
        }
        
        .id-card-preview .member-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .id-card-preview .member-id {
            font-size: 12px;
            opacity: 0.9;
        }
        
        .id-card-preview .card-footer {
            position: absolute;
            bottom: 10px;
            right: 15px;
            font-size: 10px;
            opacity: 0.8;
        }
        
        .id-card-preview .qr-code {
            position: absolute;
            bottom: 10px;
            left: 15px;
            width: 30px;
            height: 30px;
            background: white;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #333;
        }
        
        .card-stats {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 15px;
        }
        
        .stat-icon {
            font-size: 2rem;
            margin-bottom: 10px;
        }
        
        .filter-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .id-card-item {
            transition: all 0.3s ease;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .id-card-item:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .status-badge {
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: bold;
        }
        
        .status-active {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            color: #155724;
        }
        
        .status-expired {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c2c7 100%);
            color: #721c24;
        }
        
        .status-cancelled {
            background: linear-gradient(135deg, #f0f0f0 0%, #e0e0e0 100%);
            color: #666;
        }
        
        .bulk-actions {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
        }
        
        .generate-preview {
            max-width: 600px;
            margin: 0 auto;
        }
        
        .template-selection {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .template-option {
            border: 2px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .template-option:hover {
            border-color: #007bff;
            box-shadow: 0 2px 8px rgba(0,123,255,0.25);
        }
        
        .template-option.active {
            border-color: #007bff;
            background: rgba(0,123,255,0.1);
        }
        
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-id-card text-primary"></i> ID Cards Management
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">ID Cards</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- ID Card Statistics -->
                <div class="card-stats">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-primary">
                                    <i class="fas fa-id-card"></i>
                                </div>
                                <h3 class="mb-1" id="totalCards">0</h3>
                                <p class="mb-0">Total ID Cards</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-success">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <h3 class="mb-1" id="activeCards">0</h3>
                                <p class="mb-0">Active Cards</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-warning">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <h3 class="mb-1" id="expiringCards">0</h3>
                                <p class="mb-0">Expiring Soon</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-danger">
                                    <i class="fas fa-times-circle"></i>
                                </div>
                                <h3 class="mb-1" id="expiredCards">0</h3>
                                <p class="mb-0">Expired Cards</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-plus"></i> Generate ID Cards
                                </h3>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">Generate ID cards for members who don't have one yet.</p>
                                <button class="btn btn-primary btn-block" data-toggle="modal" data-target="#generateModal">
                                    <i class="fas fa-magic"></i> Generate ID Cards
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-download"></i> Bulk Download
                                </h3>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">Download multiple ID cards as a ZIP file.</p>
                                <button class="btn btn-success btn-block" onclick="bulkDownload()">
                                    <i class="fas fa-download"></i> Download Selected
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- ID Card Preview -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-eye"></i> ID Card Preview
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="id-card-preview">
                            <div class="card-header">
                                KUKI STUDENTS' ORGANISATION<br>
                                CHANDIGARH
                            </div>
                            <div class="member-info">
                                <div class="member-photo">
                                    <i class="fas fa-user"></i>
                                </div>
                                <div class="member-details">
                                    <div class="member-name">Sample Member</div>
                                    <div class="member-id">ID: KSOCHD001</div>
                                    <div class="member-id">Session: 2024-25</div>
                                </div>
                            </div>
                            <div class="qr-code">
                                <i class="fas fa-qrcode"></i>
                            </div>
                            <div class="card-footer">
                                Valid Until: Dec 2025
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters -->
                <div class="filter-section">
                    <h5 class="mb-3"><i class="fas fa-filter"></i> Filter ID Cards</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <select class="form-control" id="statusFilter">
                                <option value="">All Status</option>
                                <option value="active">Active</option>
                                <option value="expired">Expired</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-control" id="typeFilter">
                                <option value="">All Types</option>
                                <option value="individual">Individual</option>
                                <option value="family_head">Family Head</option>
                                <option value="dependent">Dependent</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchFilter" placeholder="Search by member name or ID...">
                                <div class="input-group-append">
                                    <button class="btn btn-primary" type="button" onclick="filterCards()">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-secondary btn-block" onclick="clearFilters()">
                                <i class="fas fa-times"></i> Clear
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Bulk Actions -->
                <div class="bulk-actions" id="bulkActions" style="display: none;">
                    <div class="row">
                        <div class="col-md-6">
                            <span class="text-muted">
                                <span id="selectedCount">0</span> cards selected
                            </span>
                        </div>
                        <div class="col-md-6 text-right">
                            <button class="btn btn-primary btn-sm" onclick="bulkGenerate()">
                                <i class="fas fa-magic"></i> Generate Selected
                            </button>
                            <button class="btn btn-success btn-sm" onclick="bulkDownload()">
                                <i class="fas fa-download"></i> Download Selected
                            </button>
                            <button class="btn btn-danger btn-sm" onclick="bulkCancel()">
                                <i class="fas fa-times"></i> Cancel Selected
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Loading Spinner -->
                <div class="loading-spinner" id="loadingSpinner">
                    <i class="fas fa-spinner fa-spin fa-2x"></i>
                    <p>Loading ID cards...</p>
                </div>

                <!-- ID Cards Table -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list"></i> ID Cards List
                        </h3>
                        <div class="card-tools">
                            <button class="btn btn-primary btn-sm" onclick="refreshCards()">
                                <i class="fas fa-sync"></i> Refresh
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="idCardsTable">
                                <thead>
                                    <tr>
                                        <th>
                                            <input type="checkbox" id="selectAll">
                                        </th>
                                        <th>Member</th>
                                        <th>Card Number</th>
                                        <th>Type</th>
                                        <th>Status</th>
                                        <th>Issue Date</th>
                                        <th>Expiry Date</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="idCardsTableBody">
                                    <!-- Data will be loaded here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Empty State -->
                <div class="empty-state" id="emptyState" style="display: none;">
                    <i class="fas fa-id-card"></i>
                    <h4>No ID cards found</h4>
                    <p>Generate your first ID card to get started.</p>
                    <button class="btn btn-primary" data-toggle="modal" data-target="#generateModal">
                        <i class="fas fa-plus"></i> Generate ID Card
                    </button>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Generate ID Cards Modal -->
<div class="modal fade" id="generateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-magic"></i> Generate ID Cards
                </h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="generate-preview">
                    <h6>Select Template</h6>
                    <div class="template-selection">
                        <div class="template-option active" data-template="standard">
                            <i class="fas fa-id-card fa-2x mb-2"></i>
                            <div>Standard</div>
                        </div>
                        <div class="template-option" data-template="premium">
                            <i class="fas fa-id-card fa-2x mb-2"></i>
                            <div>Premium</div>
                        </div>
                        <div class="template-option" data-template="modern">
                            <i class="fas fa-id-card fa-2x mb-2"></i>
                            <div>Modern</div>
                        </div>
                    </div>
                    
                    <h6>Select Members</h6>
                    <div class="form-group">
                        <select class="form-control" id="memberSelect" multiple>
                            <option value="all">All Members Without ID Cards</option>
                            <!-- Members will be populated via JavaScript -->
                        </select>
                    </div>
                    
                    <h6>Card Settings</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Issue Date</label>
                                <input type="date" class="form-control" id="issueDate" value="<?php echo date('Y-m-d'); ?>">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Expiry Date</label>
                                <input type="date" class="form-control" id="expiryDate" value="<?php echo date('Y-m-d', strtotime('+1 year')); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="includeQR" checked>
                            <label class="custom-control-label" for="includeQR">Include QR Code</label>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="generateIDCards()">
                    <i class="fas fa-magic"></i> Generate Cards
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Custom JavaScript -->
<script src="dist/js/preloader.js"></script>
<script src="dist/js/theme-manager.js"></script>
<script src="dist/js/toast.js"></script>
<script src="dist/js/breadcrumbs.js"></script>

<script>
// Industrial-Level ID Cards Management System
$(document).ready(function() {
    // Initialize the page
    loadIDCards();
    loadStatistics();
    loadMembersWithoutCards();
    setupTemplateSelection();
    setupBulkActions();
    setupFilters();
});

let selectedCards = [];
let isLoading = false;

function loadIDCards() {
    if (isLoading) return;
    
    isLoading = true;
    $('#loadingSpinner').show();
    $('#idCardsTableBody').empty();
    
    const filters = {
        status: $('#statusFilter').val(),
        type: $('#typeFilter').val(),
        search: $('#searchFilter').val()
    };
    
    $.ajax({
        url: 'api/id-cards/fetch.php',
        method: 'GET',
        data: filters,
        success: function(response) {
            if (response.success) {
                if (response.cards && response.cards.length > 0) {
                    response.cards.forEach(function(card) {
                        $('#idCardsTableBody').append(createCardRow(card));
                    });
                    $('#emptyState').hide();
                    $('#idCardsTable').show();
                } else {
                    $('#idCardsTable').hide();
                    $('#emptyState').show();
                }
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error loading ID cards: ' + response.message);
                }
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Error loading ID cards');
            }
        },
        complete: function() {
            isLoading = false;
            $('#loadingSpinner').hide();
        }
    });
}

function createCardRow(card) {
    const statusClass = getStatusClass(card.status);
    const statusText = getStatusText(card.status);
    
    return `
        <tr>
            <td>
                <input type="checkbox" class="card-checkbox" value="${card.id}">
            </td>
            <td>
                <div class="d-flex align-items-center">
                    <div class="mr-3">
                        <i class="fas fa-user fa-2x text-primary"></i>
                    </div>
                    <div>
                        <div class="font-weight-bold">${card.member_name}</div>
                        <div class="text-muted small">${card.member_id}</div>
                    </div>
                </div>
            </td>
            <td>${card.card_number}</td>
            <td>
                <span class="badge badge-info">${card.card_type}</span>
            </td>
            <td>
                <span class="status-badge ${statusClass}">${statusText}</span>
            </td>
            <td>${formatDate(card.issue_date)}</td>
            <td>${formatDate(card.expiry_date)}</td>
            <td>
                <div class="btn-group">
                    <button class="btn btn-sm btn-primary" onclick="viewCard(${card.id})" title="View Card">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-success" onclick="downloadCard(${card.id})" title="Download">
                        <i class="fas fa-download"></i>
                    </button>
                    <button class="btn btn-sm btn-warning" onclick="regenerateCard(${card.id})" title="Regenerate">
                        <i class="fas fa-redo"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="cancelCard(${card.id})" title="Cancel">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </td>
        </tr>
    `;
}

function getStatusClass(status) {
    switch(status) {
        case 'active': return 'status-active';
        case 'expired': return 'status-expired';
        case 'cancelled': return 'status-cancelled';
        default: return 'status-active';
    }
}

function getStatusText(status) {
    switch(status) {
        case 'active': return 'Active';
        case 'expired': return 'Expired';
        case 'cancelled': return 'Cancelled';
        default: return 'Active';
    }
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}

function loadStatistics() {
    $.ajax({
        url: 'api/id-cards/stats.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalCards').text(response.stats.total);
                $('#activeCards').text(response.stats.active);
                $('#expiringCards').text(response.stats.expiring);
                $('#expiredCards').text(response.stats.expired);
            }
        },
        error: function() {
            // Set default values on error
            $('#totalCards').text('0');
            $('#activeCards').text('0');
            $('#expiringCards').text('0');
            $('#expiredCards').text('0');
        }
    });
}

function loadMembersWithoutCards() {
    $.ajax({
        url: 'api/id-cards/members-without-cards.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const select = $('#memberSelect');
                select.empty();
                select.append('<option value="all">All Members Without ID Cards</option>');
                
                response.members.forEach(function(member) {
                    select.append(`<option value="${member.id}">${member.name} (${member.kso_id})</option>`);
                });
            }
        }
    });
}

function setupTemplateSelection() {
    $('.template-option').on('click', function() {
        $('.template-option').removeClass('active');
        $(this).addClass('active');
    });
}

function setupBulkActions() {
    // Select all checkbox
    $('#selectAll').on('change', function() {
        $('.card-checkbox').prop('checked', this.checked);
        updateSelectedCards();
    });
    
    // Individual checkboxes
    $(document).on('change', '.card-checkbox', function() {
        updateSelectedCards();
    });
}

function updateSelectedCards() {
    selectedCards = [];
    $('.card-checkbox:checked').each(function() {
        selectedCards.push($(this).val());
    });
    
    $('#selectedCount').text(selectedCards.length);
    $('#bulkActions').toggle(selectedCards.length > 0);
}

function setupFilters() {
    $('#statusFilter, #typeFilter').on('change', function() {
        loadIDCards();
    });
    
    $('#searchFilter').on('keyup', function() {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(function() {
            loadIDCards();
        }, 500);
    });
}

function filterCards() {
    loadIDCards();
}

function clearFilters() {
    $('#statusFilter, #typeFilter, #searchFilter').val('');
    loadIDCards();
}

function refreshCards() {
    loadIDCards();
    loadStatistics();
}

function generateIDCards() {
    const template = $('.template-option.active').data('template');
    const members = $('#memberSelect').val();
    const issueDate = $('#issueDate').val();
    const expiryDate = $('#expiryDate').val();
    const includeQR = $('#includeQR').prop('checked');
    
    if (!members || members.length === 0) {
        if (window.ksoToast) {
            window.ksoToast.error('Please select at least one member');
        }
        return;
    }
    
    const btn = $('#generateModal').find('.btn-primary');
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Generating...');
    
    $.ajax({
        url: 'api/id-cards/generate.php',
        method: 'POST',
        data: {
            template: template,
            members: members,
            issue_date: issueDate,
            expiry_date: expiryDate,
            include_qr: includeQR
        },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('ID cards generated successfully!');
                }
                $('#generateModal').modal('hide');
                loadIDCards();
                loadStatistics();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Generation failed: ' + response.message);
                }
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Generation failed');
            }
        },
        complete: function() {
            btn.prop('disabled', false).html('<i class="fas fa-magic"></i> Generate Cards');
        }
    });
}

function viewCard(id) {
    window.open('api/id-cards/view.php?id=' + id, '_blank');
}

function downloadCard(id) {
    window.open('api/id-cards/download.php?id=' + id, '_blank');
}

function regenerateCard(id) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Regenerate ID Card?',
            text: 'This will create a new version of the ID card.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, regenerate!'
        }).then((result) => {
            if (result.isConfirmed) {
                performRegenerate(id);
            }
        });
    } else {
        if (confirm('Are you sure you want to regenerate this ID card?')) {
            performRegenerate(id);
        }
    }
}

function performRegenerate(id) {
    $.ajax({
        url: 'api/id-cards/regenerate.php',
        method: 'POST',
        data: { id: id },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('ID card regenerated successfully!');
                }
                loadIDCards();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Regeneration failed: ' + response.message);
                }
            }
        }
    });
}

function cancelCard(id) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Cancel ID Card?',
            text: 'This will mark the ID card as cancelled.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, cancel it!'
        }).then((result) => {
            if (result.isConfirmed) {
                performCancel(id);
            }
        });
    } else {
        if (confirm('Are you sure you want to cancel this ID card?')) {
            performCancel(id);
        }
    }
}

function performCancel(id) {
    $.ajax({
        url: 'api/id-cards/cancel.php',
        method: 'POST',
        data: { id: id },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('ID card cancelled successfully!');
                }
                loadIDCards();
                loadStatistics();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Cancellation failed: ' + response.message);
                }
            }
        }
    });
}

function bulkGenerate() {
    if (selectedCards.length === 0) {
        if (window.ksoToast) {
            window.ksoToast.error('Please select cards to generate');
        }
        return;
    }
    
    // Open generate modal with selected cards
    $('#generateModal').modal('show');
}

function bulkDownload() {
    if (selectedCards.length === 0) {
        if (window.ksoToast) {
            window.ksoToast.error('Please select cards to download');
        }
        return;
    }
    
    window.open('api/id-cards/bulk-download.php?ids=' + selectedCards.join(','), '_blank');
}

function bulkCancel() {
    if (selectedCards.length === 0) {
        if (window.ksoToast) {
            window.ksoToast.error('Please select cards to cancel');
        }
        return;
    }
    
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Cancel Selected Cards?',
            text: `This will cancel ${selectedCards.length} selected ID cards.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, cancel them!'
        }).then((result) => {
            if (result.isConfirmed) {
                performBulkCancel();
            }
        });
    } else {
        if (confirm(`Are you sure you want to cancel ${selectedCards.length} selected ID cards?`)) {
            performBulkCancel();
        }
    }
}

function performBulkCancel() {
    $.ajax({
        url: 'api/id-cards/bulk-cancel.php',
        method: 'POST',
        data: { ids: selectedCards },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Selected ID cards cancelled successfully!');
                }
                loadIDCards();
                loadStatistics();
                selectedCards = [];
                $('#bulkActions').hide();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Bulk cancellation failed: ' + response.message);
                }
            }
        }
    });
}
</script>

</body>
</html>
