<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';
require_once '../includes/sidebar_layout.php';

// Verify user authentication
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'] ?? 'guest';
$user_name = $_SESSION['user_name'] ?? '';

// Fetch site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$logo_image = $settings['logo_image'] ?? '../assets/images/logo.png';
$site_address = $settings['site_address'] ?? 'বিদ্যা নিকেতন উচ্চ বিদ্যালয়, ঝিনাইদহ';

// Initialize variables for search
$search_session = $_GET['session'] ?? '';
$search_class_id = $_GET['class_id'] ?? '';
$search_group = $_GET['group_name'] ?? ''; // Changed to match student list parameter
$students = [];

// Handle background image upload
$background_image = '../assets/images/id_card_bg.jpg'; // Default background
$background_size = 'cover'; // Default size
$background_opacity = '0.1'; // Default opacity (10%)
$name_font_size = '1.4rem'; // Default name font size
$card_width = '320px'; // Default card width
$card_height = '500px'; // Default card height

// Check if custom background settings exist in site settings
$bg_image_setting = get_setting($pdo, 'id_card_background', '');
if (!empty($bg_image_setting)) {
    $background_image = '../uploads/id_card_backgrounds/' . $bg_image_setting;
}

$bg_size_setting = get_setting($pdo, 'id_card_background_size', '');
if (!empty($bg_size_setting)) {
    $background_size = $bg_size_setting;
}

$bg_opacity_setting = get_setting($pdo, 'id_card_background_opacity', '');
if (!empty($bg_opacity_setting)) {
    $background_opacity = $bg_opacity_setting;
}

$name_size_setting = get_setting($pdo, 'id_card_name_size', '');
if (!empty($name_size_setting)) {
    $name_font_size = $name_size_setting;
}

$card_width_setting = get_setting($pdo, 'id_card_width', '');
if (!empty($card_width_setting)) {
    $card_width = $card_width_setting;
}

$card_height_setting = get_setting($pdo, 'id_card_height', '');
if (!empty($card_height_setting)) {
    $card_height = $card_height_setting;
}

// Handle form submission for background settings
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_background_settings'])) {
    // Handle background image upload
    if (isset($_FILES['background_image']) && $_FILES['background_image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/id_card_backgrounds/';
        $file_name = uniqid() . '_' . basename($_FILES['background_image']['name']);
        $target_file = $upload_dir . $file_name;
        
        // Validate file type
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        
        if (in_array($imageFileType, $allowed_types)) {
            if (move_uploaded_file($_FILES['background_image']['tmp_name'], $target_file)) {
                // Save to settings
                set_setting($pdo, 'id_card_background', $file_name);
                $background_image = $target_file;
            }
        }
    }
    
    // Save background size
    if (isset($_POST['background_size'])) {
        $size = $_POST['background_size'];
        if (in_array($size, ['cover', 'contain', 'auto'])) {
            set_setting($pdo, 'id_card_background_size', $size);
            $background_size = $size;
        }
    }
    
    // Save background opacity
    if (isset($_POST['background_opacity'])) {
        $opacity = floatval($_POST['background_opacity']);
        if ($opacity >= 0 && $opacity <= 1) {
            set_setting($pdo, 'id_card_background_opacity', $opacity);
            $background_opacity = $opacity;
        }
    }
    
    // Save name font size
    if (isset($_POST['name_font_size'])) {
        $size = $_POST['name_font_size'];
        // Validate it ends with rem, px, em, etc.
        if (preg_match('/^[0-9]+(\.[0-9]+)?(rem|px|em|pt)$/', $size)) {
            set_setting($pdo, 'id_card_name_size', $size);
            $name_font_size = $size;
        }
    }
    
    // Save card width
    if (isset($_POST['card_width'])) {
        $width = $_POST['card_width'];
        // Validate it ends with px, rem, em, etc.
        if (preg_match('/^[0-9]+(\.[0-9]+)?(px|rem|em|%)$/', $width)) {
            set_setting($pdo, 'id_card_width', $width);
            $card_width = $width;
        }
    }
    
    // Save card height
    if (isset($_POST['card_height'])) {
        $height = $_POST['card_height'];
        // Validate it ends with px, rem, em, etc.
        if (preg_match('/^[0-9]+(\.[0-9]+)?(px|rem|em|%)$/', $height)) {
            set_setting($pdo, 'id_card_height', $height);
            $card_height = $height;
        }
    }
    
    // Redirect to avoid resubmission
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit();
}

// Fetch sessions, classes, and groups for search filters
$sessions = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC");
    $sessions = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) {
    $sessions = [];
}

$classes = [];
try {
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $classes = [];
}

$groups = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name");
    $groups = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) {
    $groups = [];
}

// Handle search from student list page
if (isset($_GET['search']) && $_GET['search'] == '1') {
    // Build search query based on parameters from student list
    $where_conditions = [];
    $params = [];
    
    // Reconstruct search parameters from GET
    if (!empty($search_session)) {
        $where_conditions[] = "s.session = ?";
        $params[] = $search_session;
    }
    
    if (!empty($search_class_id)) {
        $where_conditions[] = "s.class_id = ?";
        $params[] = $search_class_id;
    }
    
    if (!empty($search_group)) {
        $where_conditions[] = "s.group_name = ?";
        $params[] = $search_group;
    }
    
    // Add other search parameters from student list
    $first_name = $_GET['first_name'] ?? '';
    $last_name = $_GET['last_name'] ?? '';
    $student_id_search = $_GET['student_id'] ?? '';
    $roll_number_search = $_GET['roll_number'] ?? '';
    $status_filter = $_GET['status'] ?? 'active';
    
    if (!empty($first_name)) {
        $where_conditions[] = "s.first_name LIKE ?";
        $params[] = "%$first_name%";
    }
    
    if (!empty($last_name)) {
        $where_conditions[] = "s.last_name LIKE ?";
        $params[] = "%$last_name%";
    }
    
    if (!empty($student_id_search)) {
        $where_conditions[] = "s.student_id LIKE ?";
        $params[] = "%$student_id_search%";
    }
    
    if (!empty($roll_number_search)) {
        $where_conditions[] = "s.roll_number = ?";
        $params[] = $roll_number_search;
    }
    
    // Always filter by status
    $where_conditions[] = "s.status = ?";
    $params[] = $status_filter;
    
    $where_clause = '';
    if (!empty($where_conditions)) {
        $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
    }
    
    // Fetch student data based on search criteria
    $sql = "
        SELECT s.*, c.name as class_name, c.section
        FROM students s
        LEFT JOIN classes c ON s.class_id = c.id
        $where_clause
        ORDER BY s.class_id, s.roll_number
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
} else if (isset($_GET['ids']) && !empty($_GET['ids'])) {
    // Get student IDs from URL (existing functionality)
    $student_ids_str = $_GET['ids'];
    $student_ids = explode(',', $student_ids_str);
    $student_ids = array_map('intval', $student_ids); // Sanitize to integers

    if (!empty($student_ids)) {
        $placeholders = rtrim(str_repeat('?,', count($student_ids)), ',');
        $stmt = $pdo->prepare("
            SELECT s.*, c.name as class_name, c.section
            FROM students s
            LEFT JOIN classes c ON s.class_id = c.id
            WHERE s.id IN ($placeholders)
        ");
        $stmt->execute($student_ids);
        $students = $stmt->fetchAll();
    }
} else {
    // No search or IDs provided
    $students = [];
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bulk ID Card Print</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        @page {
            size: A4 portrait;
            margin: 10mm;
        }
        @media print {
            .no-print, .sidebar-container, .search-section, .background-controls-section {
                display: none !important;
            }
            .id-card {
                page-break-inside: avoid !important;
            }
            /* Preserve web view styling in print */
            body {
                background-color: #f0f2f5 !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            .id-card-grid {
                display: grid !important;
                grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)) !important;
                gap: 20px !important;
                padding: 20px !important;
            }
            .id-card {
                background: #fff !important;
                border-radius: 20px !important;
                box-shadow: 0 10px 30px rgba(0,0,0,0.15) !important;
                border: 1px solid #eee !important;
                page-break-inside: avoid !important;
            }
            .id-card-background {
                opacity: 0.1 !important;
            }
            /* Ensure all colors print correctly */
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        }
        .id-card-back {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        }
        .id-card-back .id-card-content {
            display: flex;
            flex-direction: column;
            height: 100%;
        }
        .id-card-back-header {
            border-bottom: 3px solid #006747;
            padding-bottom: 12px;
            margin-bottom: 15px;
        }
        .guideline-item {
            transition: all 0.3s ease;
        }
        .guideline-item:hover {
            background: rgba(0, 103, 71, 0.05);
            border-radius: 5px;
            padding: 5px;
            margin-left: -5px;
        }
        body {
            background-color: #f0f2f5;
            font-family: 'Hind Siliguri', sans-serif;
        }
        .search-section {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin: 20px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .background-controls-section {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin: 20px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .id-card-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 20px;
            padding: 20px;
        }
        .id-card {
            background: #fff;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            padding: 20px;
            border: 1px solid #eee;
            margin-bottom: 20px;
            display: flex;
            flex-direction: column;
            position: relative;
            overflow: hidden;
        }
        .id-card-background {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            opacity: 0.1;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }
        .id-card-content {
            position: relative;
            z-index: 1;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .id-card-header {
            text-align: center;
            margin-bottom: 15px;
        }
        .id-card-header img {
            max-height: 60px;
            margin-bottom: 5px;
        }
        .id-card-header h5 {
            font-weight: 700;
            font-size: 1.2rem;
            color: #333;
            margin-bottom: 5px;
        }
        .id-card-header .address {
            font-size: 0.8rem;
            color: #666;
        }
        .student-top-section {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        .student-image-section {
            flex: 0 0 auto;
        }
        .student-photo {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            object-fit: cover;
            border: 5px solid #fff;
            box-shadow: 0 0 15px rgba(0,0,0,0.2);
        }
        .student-main-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        .student-name {
            font-weight: 700;
            color: #0056b3;
            margin-bottom: 10px;
            text-align: left;
        }
        .student-main-info p {
            margin: 5px 0;
            font-size: 0.9rem;
        }
        .student-extra-info-container {
            display: flex;
            flex: 1;
            gap: 20px;
            margin-top: 10px;
        }
        .info-column-below {
            flex: 1;
            text-align: left;
        }
        .info-column-right {
            flex: 1;
            text-align: left;
        }
        .info-column-below p, .info-column-right p {
            margin: 8px 0;
            font-size: 0.9rem;
        }
        .id-card-footer {
            margin-top: auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .expiration-date-section {
            text-align: left;
        }
        .signature-section {
            text-align: right;
        }
        .signature-text {
            border-top: 1px dashed #ccc;
            padding-top: 5px;
            margin-top: 25px;
            font-size: 0.8rem;
            color: #555;
            width: 150px;
            margin-left: auto;
        }
        .expiration-section {
            text-align: center;
            margin: 5px 0;
            font-size: 0.9rem;
            color: #d32f2f;
            font-weight: 500;
        }
        .form-label {
            font-weight: 600;
        }
        .search-btn {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            border: none;
        }
        .search-btn:hover {
            background: linear-gradient(135deg, #004d35 0%, #006747 100%);
        }
        .save-btn {
            background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%);
            border: none;
        }
        .save-btn:hover {
            background: linear-gradient(135deg, #1565c0 0%, #1976d2 100%);
        }
        .expiration-input {
            width: 150px;
            margin: 0 auto;
            text-align: center;
        }
        .control-group {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <div class="sidebar-container no-print">
        <!-- Minimal sidebar with only dashboard -->
        <div class="sidebar" id="sidebar">
            <!-- Sidebar Header -->
            <div class="sidebar-header">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <div class="sidebar-logo">
                    <?php
                        // Get site settings
                        if (function_exists('get_all_settings') && isset($GLOBALS['pdo'])) {
                            $settings = get_all_settings($GLOBALS['pdo']);
                            $site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
                            $logo_image = $settings['logo_image'] ?? null;
                            // Get system name for branding
                            $system_name = get_system_name($GLOBALS['pdo']);
                        } else {
                            $site_name = 'বিদ্যা নিকেতন';
                            $logo_image = null;
                            $system_name = 'স্কুল ম্যানেজমেন্ট সিস্টেম';
                        }
                        
                        $logo_path = $logo_image;
                        if ($logo_image && !preg_match('/^https?:\/\/|^data:/i', $logo_image)) {
                            $logo_path = __DIR__ . '/../' . ltrim($logo_image, '/');
                        }
                    ?>
                    <?php if ($logo_image && ($logo_path && file_exists($logo_path))): ?>
                        <img src="<?php echo htmlspecialchars('../' . $logo_image); ?>" alt="Logo" style="height: 40px; width: auto;">
                    <?php else: ?>
                        <i class="fas fa-graduation-cap"></i>
                    <?php endif; ?>
                </div>
                <h3 class="sidebar-title"><?php echo htmlspecialchars($site_name); ?></h3>
                <p class="sidebar-subtitle"><?php echo htmlspecialchars($system_name); ?></p>
            </div>
            
            <!-- User Profile -->
            <div class="sidebar-user">
                <div class="user-avatar">
                    <i class="fas fa-user"></i>
                </div>
                <h4 class="user-name"><?php echo htmlspecialchars($user_name); ?></h4>
                <p class="user-role"><?php echo getRoleDisplayName($user_role); ?></p>
            </div>
            
            <!-- Navigation Menu - Only Dashboard -->
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <div class="nav-section-title">মূল মেনু</div>
                    <div class="nav-item">
                        <a href="/bidda/" class="nav-link <?php echo (basename($_SERVER['PHP_SELF']) == 'index.php' || $_SERVER['PHP_SELF'] == '/bidda/') ? 'active' : ''; ?>">
                            <span class="nav-icon">
                                <i class="fas fa-home"></i>
                            </span>
                            <span class="nav-text">ড্যাশবোর্ড</span>
                        </a>
                    </div>
                </div>
                
                <!-- Logout -->
                <div class="nav-section">
                    <div class="nav-item">
                        <a href="../logout.php" class="nav-link" onclick="return confirm('আপনি কি লগআউট করতে চান?')">
                            <span class="nav-icon">
                                <i class="fas fa-sign-out-alt"></i>
                            </span>
                            <span class="nav-text">লগআউট</span>
                        </a>
                    </div>
                </div>
            </nav>
        </div>

        <script>
            // Sidebar JavaScript Functions
            function toggleSidebar() {
                const sidebar = document.getElementById('sidebar');
                const toggleBtn = document.querySelector('.sidebar-toggle i');
                
                sidebar.classList.toggle('collapsed');
                
                if (sidebar.classList.contains('collapsed')) {
                    toggleBtn.className = 'fas fa-chevron-right';
                    localStorage.setItem('sidebarCollapsed', 'true');
                } else {
                    toggleBtn.className = 'fas fa-chevron-left';
                    localStorage.setItem('sidebarCollapsed', 'false');
                }
            }
            
            function toggleMobileSidebar() {
                const sidebar = document.getElementById('sidebar');
                const overlay = document.querySelector('.mobile-overlay');
                
                sidebar.classList.toggle('mobile-open');
                overlay.classList.toggle('active');
            }
            
            function closeMobileSidebar() {
                const sidebar = document.getElementById('sidebar');
                const overlay = document.querySelector('.mobile-overlay');
                
                sidebar.classList.remove('mobile-open');
                overlay.classList.remove('active');
            }
            
            // Initialize sidebar state
            document.addEventListener('DOMContentLoaded', function() {
                const sidebarCollapsed = localStorage.getItem('sidebarCollapsed');
                if (sidebarCollapsed === 'true') {
                    document.getElementById('sidebar').classList.add('collapsed');
                    document.querySelector('.sidebar-toggle i').className = 'fas fa-chevron-right';
                }
            });
            
            // Close mobile sidebar on window resize
            window.addEventListener('resize', function() {
                if (window.innerWidth > 768) {
                    closeMobileSidebar();
                }
            });
        </script>
        <div class="main-content">
            <div class="container-fluid">
                <!-- Background Controls Section -->
                <div class="background-controls-section">
                    <h3 class="mb-4"><i class="fas fa-image"></i> আইডি কার্ড ব্যাকগ্রাউন্ড সেটিংস</h3>
                    <form method="POST" enctype="multipart/form-data" class="row g-3">
                        <div class="col-md-4">
                            <div class="control-group">
                                <label for="background_image" class="form-label">ব্যাকগ্রাউন্ড ইমেজ আপলোড করুন</label>
                                <input type="file" name="background_image" id="background_image" class="form-control" accept="image/*">
                                <?php if (isset($bg_image_setting) && !empty($bg_image_setting)): ?>
                                    <small class="text-muted">বর্তমান ইমেজ: <?php echo htmlspecialchars($bg_image_setting); ?></small>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="control-group">
                                <label for="background_size" class="form-label">ব্যাকগ্রাউন্ড সাইজ</label>
                                <select name="background_size" id="background_size" class="form-select">
                                    <option value="cover" <?php echo ($background_size == 'cover') ? 'selected' : ''; ?>>Cover (সম্পূর্ণ কভার)</option>
                                    <option value="contain" <?php echo ($background_size == 'contain') ? 'selected' : ''; ?>>Contain (সম্পূর্ণ দেখানো)</option>
                                    <option value="auto" <?php echo ($background_size == 'auto') ? 'selected' : ''; ?>>Auto (আসল সাইজ)</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="control-group">
                                <label for="background_opacity" class="form-label">ব্যাকগ্রাউন্ড অপাসিটি (0-1)</label>
                                <input type="number" name="background_opacity" id="background_opacity" class="form-control" step="0.05" min="0" max="1" value="<?php echo htmlspecialchars($background_opacity); ?>">
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="control-group">
                                <label for="name_font_size" class="form-label">ছাত্রের নামের ফন্ট সাইজ (যেমন: 1.4rem, 16px)</label>
                                <input type="text" name="name_font_size" id="name_font_size" class="form-control" value="<?php echo htmlspecialchars($name_font_size); ?>">
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="control-group">
                                <label for="card_width" class="form-label">কার্ডের প্রস্থ (যেমন: 320px, 20rem)</label>
                                <input type="text" name="card_width" id="card_width" class="form-control" value="<?php echo htmlspecialchars($card_width); ?>">
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="control-group">
                                <label for="card_height" class="form-label">কার্ডের উচ্চতা (যেমন: 500px, 30rem)</label>
                                <input type="text" name="card_height" id="card_height" class="form-control" value="<?php echo htmlspecialchars($card_height); ?>">
                            </div>
                        </div>
                        
                        <div class="col-12 text-end">
                            <button type="submit" name="save_background_settings" class="btn save-btn">
                                <i class="fas fa-save"></i> সেটিংস সংরক্ষণ করুন
                            </button>
                        </div>
                    </form>
                </div>
                
                <!-- Guidelines Card -->
                <div class="background-controls-section" style="border-left: 5px solid #ffc107;">
                    <h3 class="mb-4"><i class="fas fa-info-circle" style="color: #ffc107;"></i> নির্দেশনা ও ব্যবহার বিধি</h3>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="d-flex align-items-start mb-3">
                                <i class="fas fa-check-circle text-success mt-1 me-2"></i>
                                <div>
                                    <strong>ব্যাকগ্রাউন্ড ইমেজ:</strong><br>
                                    <small class="text-muted">আইডি কার্ডের ব্যাকগ্রাউন্ডে ব্যবহারের জন্য একটি ইমেজ আপলোড করুন। সুপারিশকৃত সাইজ: 600x900px</small>
                                </div>
                            </div>
                            <div class="d-flex align-items-start mb-3">
                                <i class="fas fa-check-circle text-success mt-1 me-2"></i>
                                <div>
                                    <strong>অপাসিটি সেটিং:</strong><br>
                                    <small class="text-muted">ব্যাকগ্রাউন্ড ইমেজের স্বচ্ছতা নিয়ন্ত্রণ করুন (০-১)। কম মান = বেশি স্বচ্ছ, বেশি মান = কম স্বচ্ছ</small>
                                </div>
                            </div>
                            <div class="d-flex align-items-start mb-3">
                                <i class="fas fa-check-circle text-success mt-1 me-2"></i>
                                <div>
                                    <strong>কার্ড সাইজ:</strong><br>
                                    <small class="text-muted">কার্ডের প্রস্থ ও উচ্চতা কাস্টমাইজ করুন। স্ট্যান্ডার্ড: 320px x 500px</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="d-flex align-items-start mb-3">
                                <i class="fas fa-check-circle text-success mt-1 me-2"></i>
                                <div>
                                    <strong>ছাত্র অনুসন্ধান:</strong><br>
                                    <small class="text-muted">সেশন, ক্লাস, গ্রুপ বা নাম দিয়ে ছাত্রদের খুঁজুন। একাধিক ফিল্টর একসাথে ব্যবহার করতে পারেন</small>
                                </div>
                            </div>
                            <div class="d-flex align-items-start mb-3">
                                <i class="fas fa-check-circle text-success mt-1 me-2"></i>
                                <div>
                                    <strong>মেয়াদ তারিখ:</strong><br>
                                    <small class="text-muted">আইডি কার্ডের মেয়াদ শেষ হওয়ার তারিখ সেট করুন। এটি ঐচ্ছিক</small>
                                </div>
                            </div>
                            <div class="d-flex align-items-start mb-3">
                                <i class="fas fa-check-circle text-success mt-1 me-2"></i>
                                <div>
                                    <strong>প্রিন্টিং:</strong><br>
                                    <small class="text-muted">সরাসরি প্রিন্ট করুন অথবা PDF হিসেবে সংরক্ষণ করুন। A4 পেপারে ৩টি কার্ড প্রিন্ট হবে</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="alert alert-warning mt-3 mb-0">
                        <i class="fas fa-exclamation-triangle"></i> <strong>গুরুত্বপূর্ণ:</strong> প্রিন্ট করার আগে "প্রিন্ট প্রিভিউ" দেখে নিন এবং পেজ সেটআপে মার্জিন কমিয়ে নিন (সুপারিশকৃত: 10mm)
                    </div>
                </div>
                
                <!-- Search Section -->
                <div class="search-section">
                    <h3 class="mb-4"><i class="fas fa-search"></i> ছাত্র/ছাত্রী অনুসন্ধান করুন</h3>
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <label for="session" class="form-label">সেশন</label>
                            <select name="session" id="session" class="form-select">
                                <option value="">সব সেশন</option>
                                <?php foreach ($sessions as $session): ?>
                                    <option value="<?php echo htmlspecialchars($session); ?>" <?php echo ($search_session == $session) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($session); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label for="class_id" class="form-label">ক্লাস</label>
                            <select name="class_id" id="class_id" class="form-select">
                                <option value="">সব ক্লাস</option>
                                <?php foreach ($classes as $class): ?>
                                    <option value="<?php echo htmlspecialchars($class['id']); ?>" <?php echo ($search_class_id == $class['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label for="group" class="form-label">গ্রুপ</label>
                            <select name="group_name" id="group" class="form-select">
                                <option value="">সব গ্রুপ</option>
                                <?php foreach ($groups as $group): ?>
                                    <option value="<?php echo htmlspecialchars($group); ?>" <?php echo ($search_group == $group) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($group); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label for="status" class="form-label">অবস্থা</label>
                            <select name="status" id="status" class="form-select">
                                <option value="active" <?php echo (isset($_GET['status']) && $_GET['status'] == 'active') ? 'selected' : ''; ?>>সক্রিয়</option>
                                <option value="inactive" <?php echo (isset($_GET['status']) && $_GET['status'] == 'inactive') ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                                <option value="graduated" <?php echo (isset($_GET['status']) && $_GET['status'] == 'graduated') ? 'selected' : ''; ?>>স্নাতক</option>
                                <option value="transferred" <?php echo (isset($_GET['status']) && $_GET['status'] == 'transferred') ? 'selected' : ''; ?>>বদলি</option>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label for="first_name" class="form-label">নাম (প্রথম)</label>
                            <input type="text" name="first_name" id="first_name" class="form-control" value="<?php echo htmlspecialchars($_GET['first_name'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-md-3">
                            <label for="last_name" class="form-label">নাম (শেষ)</label>
                            <input type="text" name="last_name" id="last_name" class="form-control" value="<?php echo htmlspecialchars($_GET['last_name'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-md-3">
                            <label for="student_id" class="form-label">ছাত্র আইডি</label>
                            <input type="text" name="student_id" id="student_id" class="form-control" value="<?php echo htmlspecialchars($_GET['student_id'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-md-3">
                            <label for="roll_number" class="form-label">রোল নম্বর</label>
                            <input type="text" name="roll_number" id="roll_number" class="form-control" value="<?php echo htmlspecialchars($_GET['roll_number'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-12 text-end">
                            <button type="submit" name="search" value="1" class="btn search-btn">
                                <i class="fas fa-search"></i> অনুসন্ধান করুন
                            </button>
                            <a href="bulk_id_card.php" class="btn btn-secondary">
                                <i class="fas fa-redo"></i> রিসেট
                            </a>
                        </div>
                    </form>
                </div>

                <?php if (isset($_GET['search']) || isset($_GET['ids'])): ?>
                    <?php if (empty($students)): ?>
                        <div class="alert alert-info text-center mx-4">
                            <i class="fas fa-info-circle"></i> কোনো ছাত্র/ছাত্রী পাওয়া যায়নি।
                        </div>
                    <?php else: ?>
                        <div class="my-3 text-center">
                            <div class="btn-group mb-3" role="group" aria-label="Print Options">
                                <button class="btn btn-outline-primary active" id="print-both" onclick="setPrintOption('both')">
                                    <i class="fas fa-copy"></i> সামনে ও পিছনে
                                </button>
                                <button class="btn btn-outline-primary" id="print-front" onclick="setPrintOption('front')">
                                    <i class="fas fa-id-card"></i> শুধু সামনে
                                </button>
                                <button class="btn btn-outline-primary" id="print-back" onclick="setPrintOption('back')">
                                    <i class="fas fa-address-card"></i> শুধু পিছনে
                                </button>
                            </div>
                            <br>
                            <button class="btn btn-primary btn-lg" onclick="window.print()">
                                <i class="fas fa-print"></i> প্রিন্ট করুন (<?php echo count($students); ?> জনের আইডি কার্ড)
                            </button>
                            <a href="list.php" class="btn btn-secondary">ছাত্র তালিকায় ফিরে যান</a>
                            <div class="mt-3">
                                <label for="expiration_date" class="form-label">মেয়াদ শেষ হওয়ার তারিখ (ঐচ্ছিক):</label>
                                <input type="date" id="expiration_date" class="form-control expiration-input" onchange="updateExpirationDate(this.value)">
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php if (!empty($students)): ?>
        <div class="id-card-page">
            <div class="id-card-grid">
                <?php 
                foreach ($students as $student): 
                ?>
                    <div class="id-card" style="width: <?php echo htmlspecialchars($card_width); ?>; height: <?php echo htmlspecialchars($card_height); ?>;">
                        <div class="id-card-background" style="background-image: url('<?php echo htmlspecialchars($background_image); ?>'); background-size: <?php echo htmlspecialchars($background_size); ?>; opacity: <?php echo htmlspecialchars($background_opacity); ?>;"></div>
                        <div class="id-card-content">
                            <div class="id-card-header">
                                <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo">
                                <h5><?php echo htmlspecialchars($site_name); ?></h5>
                                <div class="address"><?php echo htmlspecialchars($site_address); ?></div>
                            </div>

                            <div class="student-top-section">
                                <div class="student-image-section">
                                    <img src="../<?php echo htmlspecialchars($student['photo'] ?? 'assets/images/default-avatar.png'); ?>" class="student-photo" alt="Student Photo">
                                </div>
                                
                                <div class="student-main-info">
                                    <h4 class="student-name" style="font-size: <?php echo htmlspecialchars($name_font_size); ?>;"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></h4>
                                    <p><strong>ক্লাস:</strong> <?php echo htmlspecialchars($student['class_name']); ?></p>
                                    <p><strong>রোল:</strong> <?php echo htmlspecialchars($student['roll_number']); ?></p>
                                </div>
                            </div>

                            <!-- Two-column layout for remaining information -->
                            <div class="student-extra-info-container">
                                <div class="info-column-below">
                                    <p><strong>পিতা:</strong> <?php echo htmlspecialchars($student['father_name'] ?? 'N/A'); ?></p>
                                    <p><strong>জন্ম:</strong> <?php echo htmlspecialchars($student['date_of_birth'] ?? 'N/A'); ?></p>
                                </div>
                                <div class="info-column-right">
                                    <p><strong>সেশন:</strong> <?php echo htmlspecialchars($student['session']); ?></p>
                                    <p><strong>রক্তের গ্রুপ:</strong> <?php echo htmlspecialchars($student['blood_group'] ?? 'N/A'); ?></p>
                                </div>
                            </div>

                            <!-- Footer with expiration date on left and signature on right -->
                            <div class="id-card-footer">
                                <div class="expiration-date-section">
                                    <div id="expiration_footer_<?php echo $student['id']; ?>" style="display: none;">
                                        মেয়াদ শেষ: <span class="expiration-date-text"></span>
                                    </div>
                                </div>
                                <div class="signature-section">
                                    <div class="signature-text">
                                        কর্তৃপক্ষ
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- ID Card Back Side -->
                    <div class="id-card id-card-back" style="width: <?php echo htmlspecialchars($card_width); ?>; height: <?php echo htmlspecialchars($card_height); ?>;">
                        <div class="id-card-background" style="background-image: url('<?php echo htmlspecialchars($background_image); ?>'); background-size: <?php echo htmlspecialchars($background_size); ?>; opacity: <?php echo htmlspecialchars($background_opacity); ?>;"></div>
                        <div class="id-card-content" style="padding: 20px;">
                            <div class="id-card-back-header" style="text-align: center; margin-bottom: 15px; border-bottom: 2px solid #006747; padding-bottom: 10px;">
                                <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="height: 40px; margin-bottom: 5px;">
                                <h5 style="color: #006747; font-weight: bold; margin: 0;">গুরুত্বপূর্ণ নির্দেশনা</h5>
                            </div>
                            
                            <div class="guidelines-content" style="font-size: 0.85rem; line-height: 1.6;">
                                <div class="guideline-item" style="margin-bottom: 10px; display: flex; align-items: flex-start;">
                                    <i class="fas fa-check-circle" style="color: #28a745; margin-right: 8px; margin-top: 3px;"></i>
                                    <span>এই কার্ডটি <?php echo htmlspecialchars($site_name); ?> এর সম্পত্তি</span>
                                </div>
                                
                                <div class="guideline-item" style="margin-bottom: 10px; display: flex; align-items: flex-start;">
                                    <i class="fas fa-check-circle" style="color: #28a745; margin-right: 8px; margin-top: 3px;"></i>
                                    <span>কার্ডটি হারিয়ে গেলে তাৎক্ষণিকভাবে কর্তৃপক্ষকে জানান</span>
                                </div>
                                
                                <div class="guideline-item" style="margin-bottom: 10px; display: flex; align-items: flex-start;">
                                    <i class="fas fa-check-circle" style="color: #28a745; margin-right: 8px; margin-top: 3px;"></i>
                                    <span>কার্ডটি ব্যবহার করে কোনো অনৈতিক কাজ করা যাবে না</span>
                                </div>
                                
                                <div class="guideline-item" style="margin-bottom: 10px; display: flex; align-items: flex-start;">
                                    <i class="fas fa-check-circle" style="color: #28a745; margin-right: 8px; margin-top: 3px;"></i>
                                    <span>মেয়াদোত্তীর্ণ কার্ড নবায়ন করতে হবে</span>
                                </div>
                                
                                <div class="guideline-item" style="margin-bottom: 10px; display: flex; align-items: flex-start;">
                                    <i class="fas fa-check-circle" style="color: #28a745; margin-right: 8px; margin-top: 3px;"></i>
                                    <span>প্রতারণার চেষ্ট করলে আইনানুগ ব্যবস্থা নেওয়া হবে</span>
                                </div>
                                
                                <div class="guideline-item" style="margin-bottom: 10px; display: flex; align-items: flex-start;">
                                    <i class="fas fa-phone-alt" style="color: #006747; margin-right: 8px; margin-top: 3px;"></i>
                                    <span>জরুরী যোগাযোগ: <?php echo htmlspecialchars($settings['contact_phone'] ?? 'N/A'); ?></span>
                                </div>
                            </div>
                            
                            <div class="back-footer" style="margin-top: auto; text-align: center; padding-top: 15px; border-top: 1px dashed #ccc;">
                                <div style="font-size: 0.75rem; color: #666; margin-bottom: 5px;">
                                    <?php echo htmlspecialchars($site_address); ?>
                                </div>
                                <div style="font-size: 0.7rem; color: #999;">
                                    কার্ড আইডি: <?php echo htmlspecialchars($student['student_id'] ?? $student['id']); ?> | সেশন: <?php echo htmlspecialchars($student['session']); ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php 
                endforeach; 
                ?>
            </div>
        </div>
    <?php endif; ?>

    <script>
        let currentPrintOption = 'both';
        
        function setPrintOption(option) {
            currentPrintOption = option;
            
            // Update button styles
            document.querySelectorAll('.btn-group .btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.getElementById('print-' + option).classList.add('active');
            
            // Update print styles
            const style = document.getElementById('print-style');
            if (style) {
                style.remove();
            }
            
            const newStyle = document.createElement('style');
            newStyle.id = 'print-style';
            
            if (option === 'front') {
                newStyle.textContent = `
                    @media print {
                        .id-card-back { display: none !important; }
                    }
                `;
            } else if (option === 'back') {
                newStyle.textContent = `
                    @media print {
                        .id-card:not(.id-card-back) { display: none !important; }
                    }
                `;
            } else {
                newStyle.textContent = `
                    @media print {
                        .id-card-back {
                            page-break-inside: avoid !important;
                        }
                    }
                `;
            }
            
            document.head.appendChild(newStyle);
        }
        
        function updateExpirationDate(dateValue) {
            const dateObj = new Date(dateValue);
            const formattedDate = dateValue ? dateObj.toLocaleDateString('bn-BD') : '';
            
            // Update all expiration sections (footer only)
            document.querySelectorAll('[id^="expiration_footer_"]').forEach(section => {
                if (dateValue) {
                    section.querySelector('.expiration-date-text').textContent = formattedDate;
                    section.style.display = 'block';
                } else {
                    section.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>