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

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

// Get filter parameters
$session_filter = $_GET['session_id'] ?? '';
$class_filter = $_GET['class_id'] ?? '';
$group_filter = $_GET['group_name'] ?? '';
$search_query = $_GET['search'] ?? '';

// Per page options
$per_page_options = [5, 10, 15, 20, 25, 50, 100, 500, 1000];
$per_page = (int)($_GET['per_page'] ?? 50);

// Validate per_page value
if (!in_array($per_page, $per_page_options)) {
    $per_page = 50; // Default value if invalid
}

$current_page = $_GET['page'] ?? 1;
$view_mode = $_GET['view'] ?? 'table'; // table or list

// Get all academic sessions
$stmt = $pdo->query("SELECT * FROM academic_sessions ORDER BY start_date DESC");
$sessions = $stmt->fetchAll();

// Get all active classes
$stmt = $pdo->query("SELECT * FROM classes WHERE status = 'active' ORDER BY name");
$classes = $stmt->fetchAll();

// Get groups based on selected class
$groups = [];
if ($class_filter) {
    $stmt = $pdo->prepare("
        SELECT DISTINCT group_name 
        FROM students 
        WHERE class_id = ? AND group_name IS NOT NULL AND group_name != ''
        ORDER BY group_name
    ");
    $stmt->execute([$class_filter]);
    $groups = $stmt->fetchAll();
}

// Check if session_id column exists
$session_column_exists = false;
try {
    $check_stmt = $pdo->query("SHOW COLUMNS FROM students LIKE 'session_id'");
    $session_column_exists = $check_stmt->rowCount() > 0;
} catch (Exception $e) {
    $session_column_exists = false;
}

// Build student query with subjects
$sql = "
    SELECT 
        s.id,
        s.student_id,
        s.first_name,
        s.last_name,
        s.roll_number,
        s.group_name,
        s.status,
        c.name as class_name,
        c.section";

if ($session_column_exists) {
    $sql .= ",
        ses.session_name";
} else {
    $sql .= ",
        NULL as session_name";
}

$sql .= ",
        (SELECT COUNT(*) FROM student_subjects WHERE student_id = s.id) as total_subjects
    FROM students s
    LEFT JOIN classes c ON s.class_id = c.id";

if ($session_column_exists) {
    $sql .= "
    LEFT JOIN academic_sessions ses ON s.session_id = ses.id";
}

$sql .= "
    WHERE 1=1
";

$params = [];

// Apply filters
if ($session_filter && $session_column_exists) {
    $sql .= " AND s.session_id = ?";
    $params[] = $session_filter;
}

if ($class_filter) {
    $sql .= " AND s.class_id = ?";
    $params[] = $class_filter;
}

if ($group_filter) {
    $sql .= " AND s.group_name = ?";
    $params[] = $group_filter;
}

if ($search_query) {
    $sql .= " AND (s.student_id LIKE ? OR s.first_name LIKE ? OR s.last_name LIKE ? OR s.roll_number LIKE ?)";
    $search_term = "%$search_query%";
    $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term]);
}

// Count total records
$count_sql = "SELECT COUNT(*) as total FROM (" . $sql . ") as count_query";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_records = $count_stmt->fetch()['total'];

// Calculate pagination
$total_pages = ceil($total_records / $per_page);
$offset = ($current_page - 1) * $per_page;

// Add order and pagination
$sql .= " ORDER BY c.name, s.group_name, s.roll_number, s.first_name";
$sql .= " LIMIT ? OFFSET ?";
$params[] = (int)$per_page;
$params[] = (int)$offset;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$students = $stmt->fetchAll();

// Get subjects for each student
foreach ($students as &$student) {
    $stmt = $pdo->prepare("
        SELECT 
            s.id,
            s.name,
            s.code,
            ss.is_fourth_subject
        FROM student_subjects ss
        JOIN subjects s ON ss.subject_id = s.id
        WHERE ss.student_id = ?
        ORDER BY ss.is_fourth_subject DESC, s.name
    ");
    $stmt->execute([$student['id']]);
    $student['subjects'] = $stmt->fetchAll();
}
unset($student);

// Get site settings for logo preview
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'প্রতিষ্ঠানের নাম';
$site_address = $settings['site_address'] ?? 'ঠিকানা, ফোন: ০১৭xxxxxxxx';
$logo_image = $settings['logo_image'] ?? '';
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;
$logo_opacity = isset($settings['logo_opacity']) ? floatval($settings['logo_opacity']) : 0.9;
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষার্থী বিষয় তালিকা - <?php echo htmlspecialchars($site_name); ?></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="../assets/css/style.css" rel="stylesheet">
    <style>
        @media print {
            .no-print { display: none !important; }
            .print-only { display: block !important; }
            body { font-size: 12px; }
            .card { border: 1px solid #000 !important; box-shadow: none !important; }
            .table { font-size: 11px; }
            .bordered-table { border: 2px solid #000 !important; }
            .bordered-table th, 
            .bordered-table td { 
                border: 1px solid #000 !important; 
                padding: 5px !important;
            }
            .subject-list-item {
                border: 1px solid #000 !important;
                padding: 3px !important;
                margin-bottom: 2px !important;
            }
            .page-break { page-break-after: always; }
        }
        
        .print-only { display: none; }
        
        .report-header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #000;
            padding-bottom: 20px;
        }
        
        .bordered-table {
            border: 2px solid #000;
        }
        
        .bordered-table th,
        .bordered-table td {
            border: 1px solid #000 !important;
            padding: 8px;
            text-align: center;
        }
        
        .subject-list-item {
            border: 1px solid #000;
            padding: 5px;
            margin-bottom: 5px;
            border-radius: 3px;
        }
        
        .subject-badge {
            display: inline-block;
            padding: 2px 8px;
            font-size: 0.8rem;
            border-radius: 10px;
            margin: 1px;
        }
        
        .subject-badge.regular {
            background: #e9ecef;
            color: #495057;
            border: 1px solid #ccc;
        }
        
        .subject-badge.fourth {
            background: #667eea;
            color: white;
            border: 1px solid #4a5fc1;
        }
        
        .filter-section {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .view-toggle {
            margin-bottom: 20px;
        }
    </style>
</head>
<body class="bengali-text">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> <?php echo htmlspecialchars($site_name); ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="../students/students_with_subjects.php">
                    <i class="fas fa-users"></i> শিক্ষার্থী তালিকা
                </a>
                <a class="nav-link" href="../reports/">
                    <i class="fas fa-chart-bar"></i> রিপোর্টসমূহ
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="report-header no-print">
            <h2><i class="fas fa-list"></i> শিক্ষার্থী বিষয় তালিকা</h2>
            <p>শিক্ষার্থীদের নাম ও বিষয়সমূহের তালিকা</p>
        </div>
        
        <!-- Print Header (Visible only when printing) -->
        <div class="report-header print-only">
            <div class="text-center mb-3">
                <?php if ($logo_image): ?>
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="max-height: <?php echo $logo_size; ?>px; opacity: <?php echo $logo_opacity; ?>; max-width: 200px; object-fit: contain;">
                <?php endif; ?>
                <h3><?php echo htmlspecialchars($site_name); ?></h3>
                <p><?php echo htmlspecialchars($site_address); ?></p>
            </div>
            <h3>শিক্ষার্থী বিষয় তালিকা</h3>
            <?php if ($class_filter): ?>
                <?php foreach ($classes as $class): ?>
                    <?php if ($class['id'] == $class_filter): ?>
                        <p><strong>ক্লাস:</strong> <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?></p>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endif; ?>
            <?php if ($session_filter): ?>
                <?php foreach ($sessions as $session): ?>
                    <?php if ($session['id'] == $session_filter): ?>
                        <p><strong>সেশন:</strong> <?php echo htmlspecialchars($session['session_name']); ?></p>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endif; ?>
            <?php if ($group_filter): ?>
                <p><strong>গ্রুপ:</strong> <?php echo htmlspecialchars($group_filter); ?></p>
            <?php endif; ?>
            <p><strong>মোট শিক্ষার্থী:</strong> <?php echo $total_records; ?></p>
        </div>

        <!-- Filters Section (Not visible when printing) -->
        <div class="filter-section no-print">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label for="session_id" class="form-label">সেশন</label>
                    <select class="form-select" id="session_id" name="session_id">
                        <option value="">সব সেশন</option>
                        <?php foreach ($sessions as $session): ?>
                            <option value="<?php echo $session['id']; ?>" <?php echo ($session_filter == $session['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($session['session_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-3">
                    <label for="class_id" class="form-label">ক্লাস</label>
                    <select class="form-select" id="class_id" name="class_id">
                        <option value="">সব ক্লাস</option>
                        <?php foreach ($classes as $class): ?>
                            <option value="<?php echo $class['id']; ?>" <?php echo ($class_filter == $class['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-3">
                    <label for="group_name" class="form-label">গ্রুপ</label>
                    <select class="form-select" id="group_name" name="group_name">
                        <option value="">সব গ্রুপ</option>
                        <?php foreach ($groups as $group): ?>
                            <option value="<?php echo htmlspecialchars($group['group_name']); ?>" <?php echo ($group_filter == $group['group_name']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($group['group_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-3">
                    <label for="search" class="form-label">খুঁজুন</label>
                    <input type="text" class="form-control" id="search" name="search" placeholder="নাম, আইডি, রোল নাম্বার" value="<?php echo htmlspecialchars($search_query); ?>">
                </div>
                
                <div class="col-md-3">
                    <label for="per_page" class="form-label">প্রতি পেজে দেখান</label>
                    <select class="form-select" id="per_page" name="per_page" onchange="this.form.submit()">
                        <?php foreach ($per_page_options as $option): ?>
                            <option value="<?php echo $option; ?>" <?php echo ($per_page == $option) ? 'selected' : ''; ?>><?php echo $option; ?> জন</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-12 text-end">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-filter"></i> ফিল্টার করুন
                    </button>
                    <a href="?per_page=<?php echo $per_page; ?>" class="btn btn-secondary">
                        <i class="fas fa-redo"></i> রিসেট
                    </a>
                </div>
            </form>
        </div>
        
        <!-- View Toggle (Not visible when printing) -->
        <div class="view-toggle no-print text-center mb-3">
            <div class="btn-group" role="group">
                <a href="?view=table&per_page=<?php echo $per_page; ?><?php echo $class_filter ? '&class_id='.$class_filter : ''; ?><?php echo $session_filter ? '&session_id='.$session_filter : ''; ?><?php echo $group_filter ? '&group_name='.$group_filter : ''; ?><?php echo $search_query ? '&search='.urlencode($search_query) : ''; ?>" 
                   class="btn <?php echo ($view_mode == 'table') ? 'btn-primary' : 'btn-outline-primary'; ?>">
                    <i class="fas fa-table"></i> টেবিল ভিউ
                </a>
                <a href="?view=list&per_page=<?php echo $per_page; ?><?php echo $class_filter ? '&class_id='.$class_filter : ''; ?><?php echo $session_filter ? '&session_id='.$session_filter : ''; ?><?php echo $group_filter ? '&group_name='.$group_filter : ''; ?><?php echo $search_query ? '&search='.urlencode($search_query) : ''; ?>" 
                   class="btn <?php echo ($view_mode == 'list') ? 'btn-primary' : 'btn-outline-primary'; ?>">
                    <i class="fas fa-list"></i> লিস্ট ভিউ
                </a>
            </div>
        </div>
        
        <!-- Print Button (Not visible when printing) -->
        <div class="text-center mb-3 no-print">
            <button onclick="window.print()" class="btn btn-success btn-lg">
                <i class="fas fa-print"></i> প্রিন্ট করুন
            </button>
        </div>
        
        <!-- Results Info -->
        <div class="alert alert-info no-print">
            <i class="fas fa-info-circle"></i> 
            মোট <?php echo $total_records; ?> জন শিক্ষার্থী পাওয়া গেছে। 
            <?php if ($total_pages > 1): ?>
                পৃষ্ঠা <?php echo $current_page; ?> এর <?php echo $total_pages; ?>।
            <?php endif; ?>
        </div>
        
        <?php if (empty($students)): ?>
            <div class="alert alert-warning text-center">
                <i class="fas fa-exclamation-triangle"></i> কোন শিক্ষার্থী পাওয়া যায়নি।
            </div>
        <?php else: ?>
            <?php if ($view_mode == 'table'): ?>
                <!-- Table View -->
                <div class="table-responsive">
                    <table class="table table-bordered bordered-table">
                        <thead>
                            <tr>
                                <th>ক্রমিক</th>
                                <th>শিক্ষার্থী আইডি</th>
                                <th>নাম</th>
                                <th>রোল নাম্বার</th>
                                <th>ক্লাস</th>
                                <?php if ($group_filter || !$class_filter): ?>
                                    <th>গ্রুপ</th>
                                <?php endif; ?>
                                <th>বিষয়সমূহ</th>
                                <th>মোট বিষয়</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $serial = $offset + 1; ?>
                            <?php foreach ($students as $student): ?>
                                <tr>
                                    <td><?php echo $serial++; ?></td>
                                    <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                                    <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                    <td><?php echo htmlspecialchars($student['roll_number']); ?></td>
                                    <td><?php echo htmlspecialchars($student['class_name'] . ' - ' . $student['section']); ?></td>
                                    <?php if ($group_filter || !$class_filter): ?>
                                        <td><?php echo htmlspecialchars($student['group_name'] ?? 'N/A'); ?></td>
                                    <?php endif; ?>
                                    <td>
                                        <?php if (!empty($student['subjects'])): ?>
                                            <?php foreach ($student['subjects'] as $subject): ?>
                                                <span class="subject-badge <?php echo $subject['is_fourth_subject'] ? 'fourth' : 'regular'; ?>">
                                                    <?php echo htmlspecialchars($subject['name']); ?>
                                                    <?php if ($subject['is_fourth_subject']): ?>
                                                        <i class="fas fa-star"></i>
                                                    <?php endif; ?>
                                                </span>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <span class="text-danger">কোন বিষয় নেই</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $student['total_subjects']; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <!-- List View -->
                <div class="row">
                    <?php foreach ($students as $student): ?>
                        <div class="col-md-6 mb-3">
                            <div class="card bordered-table">
                                <div class="card-header">
                                    <div class="row">
                                        <div class="col-9">
                                            <h5 class="mb-0">
                                                <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?>
                                            </h5>
                                            <small class="text-muted">
                                                আইডি: <?php echo htmlspecialchars($student['student_id']); ?> | 
                                                রোল: <?php echo htmlspecialchars($student['roll_number']); ?>
                                            </small>
                                        </div>
                                        <div class="col-3 text-end">
                                            <span class="badge bg-primary">
                                                <?php echo $student['total_subjects']; ?> টি বিষয়
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-2">
                                        <div class="col-6">
                                            <strong>ক্লাস:</strong> <?php echo htmlspecialchars($student['class_name'] . ' - ' . $student['section']); ?>
                                        </div>
                                        <?php if ($group_filter || !$class_filter): ?>
                                            <div class="col-6">
                                                <strong>গ্রুপ:</strong> <?php echo htmlspecialchars($student['group_name'] ?? 'N/A'); ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="mt-3">
                                        <strong>বিষয়সমূহ:</strong>
                                        <div class="mt-2">
                                            <?php if (!empty($student['subjects'])): ?>
                                                <?php foreach ($student['subjects'] as $subject): ?>
                                                    <div class="subject-list-item">
                                                        <span class="subject-badge <?php echo $subject['is_fourth_subject'] ? 'fourth' : 'regular'; ?>">
                                                            <?php echo htmlspecialchars($subject['name']); ?>
                                                            <?php if ($subject['is_fourth_subject']): ?>
                                                                <i class="fas fa-star"></i>
                                                            <?php endif; ?>
                                                        </span>
                                                        <small class="text-muted">(<?php echo htmlspecialchars($subject['code']); ?>)</small>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <div class="alert alert-warning py-1 px-2 mb-0">
                                                    <i class="fas fa-exclamation-triangle"></i> কোন বিষয় নেই
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Page break after every 6 items in print view -->
                        <?php if (($serial ?? 0) % 6 == 0): ?>
                            <div class="page-break print-only"></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <!-- Pagination (Not visible when printing) -->
            <?php if ($total_pages > 1): ?>
                <nav aria-label="Page navigation" class="no-print">
                    <ul class="pagination justify-content-center">
                        <?php if ($current_page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $current_page - 1; ?>&view=<?php echo $view_mode; ?>&per_page=<?php echo $per_page; ?><?php echo $class_filter ? '&class_id='.$class_filter : ''; ?><?php echo $session_filter ? '&session_id='.$session_filter : ''; ?><?php echo $group_filter ? '&group_name='.$group_filter : ''; ?><?php echo $search_query ? '&search='.urlencode($search_query) : ''; ?>" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>
                        
                        <?php for ($i = max(1, $current_page - 2); $i <= min($total_pages, $current_page + 2); $i++): ?>
                            <li class="page-item <?php echo ($i == $current_page) ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&view=<?php echo $view_mode; ?>&per_page=<?php echo $per_page; ?><?php echo $class_filter ? '&class_id='.$class_filter : ''; ?><?php echo $session_filter ? '&session_id='.$session_filter : ''; ?><?php echo $group_filter ? '&group_name='.$group_filter : ''; ?><?php echo $search_query ? '&search='.urlencode($search_query) : ''; ?>">
                                    <?php echo $i; ?>
                                </a>
                            </li>
                        <?php endfor; ?>
                        
                        <?php if ($current_page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $current_page + 1; ?>&view=<?php echo $view_mode; ?>&per_page=<?php echo $per_page; ?><?php echo $class_filter ? '&class_id='.$class_filter : ''; ?><?php echo $session_filter ? '&session_id='.$session_filter : ''; ?><?php echo $group_filter ? '&group_name='.$group_filter : ''; ?><?php echo $search_query ? '&search='.urlencode($search_query) : ''; ?>" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-submit when class changes to update groups
        document.getElementById('class_id').addEventListener('change', function() {
            this.form.submit();
        });
    </script>
</body>
</html>