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

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

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

// Get sessions for dropdown
$sessions_stmt = $pdo->query("SELECT id, session_name FROM academic_sessions WHERE status = 'active' ORDER BY is_current DESC, start_date DESC");
$sessions = $sessions_stmt->fetchAll();

// Get classes for dropdown
$classes_stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
$classes = $classes_stmt->fetchAll();

// Initialize search variables
$search_results = [];
$search_performed = false;

// Handle search
if (isset($_GET['search'])) {
    $session_id = isset($_GET['session_id']) ? (int)$_GET['session_id'] : 0;
    $class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
    $group_name = isset($_GET['group_name']) ? trim($_GET['group_name']) : '';
    $student_id = isset($_GET['student_id']) ? trim($_GET['student_id']) : '';
    $roll_number = isset($_GET['roll_number']) ? trim($_GET['roll_number']) : '';
    
    // Build query
    $where_conditions = ["s.status = 'active'"];
    $params = [];
    
    if ($session_id > 0) {
        $where_conditions[] = "s.session_id = :session_id";
        $params[':session_id'] = $session_id;
    }
    
    if ($class_id > 0) {
        $where_conditions[] = "s.class_id = :class_id";
        $params[':class_id'] = $class_id;
    }
    
    if (!empty($group_name)) {
        $where_conditions[] = "s.group_name = :group_name";
        $params[':group_name'] = $group_name;
    }
    
    if (!empty($student_id)) {
        $where_conditions[] = "s.student_id LIKE :student_id";
        $params[':student_id'] = "%$student_id%";
    }
    
    if (!empty($roll_number)) {
        $where_conditions[] = "s.roll_number = :roll_number";
        $params[':roll_number'] = $roll_number;
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    $sql = "SELECT s.*, c.name as class_name, c.section as class_section, ses.session_name 
            FROM students s 
            LEFT JOIN classes c ON s.class_id = c.id 
            LEFT JOIN academic_sessions ses ON s.session_id = ses.id 
            WHERE $where_clause 
            ORDER BY s.class_id, s.roll_number";
    
    $stmt = $pdo->prepare($sql);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    
    try {
        $stmt->execute();
        $search_results = $stmt->fetchAll();
        $search_performed = true;
    } catch (Exception $e) {
        $search_results = [];
        $search_performed = true;
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষার্থী অনুসন্ধান - স্কুল ম্যানেজমেন্ট সিস্টেম</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/jessoreboard-theme.css" rel="stylesheet">
    <link href="../../assets/css/sidebar.css" rel="stylesheet">
</head>
<body>
    <div class="sidebar-container">
        <?php echo renderSidebar('index_with_sidebar.php', $user_role, $user_name); ?>
        <div class="main-content">
            <div class="container-fluid mt-4">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-search"></i> শিক্ষার্থী অনুসন্ধান</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="mb-4">
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">সেশন</label>
                                    <select class="form-select" name="session_id">
                                        <option value="0">সব সেশন</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?php echo $session['id']; ?>" <?php echo (isset($_GET['session_id']) && $_GET['session_id'] == $session['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($session['session_name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">ক্লাস</label>
                                    <select class="form-select" name="class_id">
                                        <option value="0">সব ক্লাস</option>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>" <?php echo (isset($_GET['class_id']) && $_GET['class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">গ্রুপ</label>
                                    <select class="form-select" name="group_name">
                                        <option value="">সব গ্রুপ</option>
                                        <option value="Science" <?php echo (isset($_GET['group_name']) && $_GET['group_name'] == 'Science') ? 'selected' : ''; ?>>Science</option>
                                        <option value="Arts" <?php echo (isset($_GET['group_name']) && $_GET['group_name'] == 'Arts') ? 'selected' : ''; ?>>Arts</option>
                                        <option value="Commerce" <?php echo (isset($_GET['group_name']) && $_GET['group_name'] == 'Commerce') ? 'selected' : ''; ?>>Commerce</option>
                                        <option value="General" <?php echo (isset($_GET['group_name']) && $_GET['group_name'] == 'General') ? 'selected' : ''; ?>>General</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">শিক্ষার্থী আইডি</label>
                                    <input type="text" class="form-control" name="student_id" placeholder="শিক্ষার্থী আইডি" value="<?php echo isset($_GET['student_id']) ? htmlspecialchars($_GET['student_id']) : ''; ?>">
                                </div>
                                
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">রোল নম্বর</label>
                                    <input type="text" class="form-control" name="roll_number" placeholder="রোল নম্বর" value="<?php echo isset($_GET['roll_number']) ? htmlspecialchars($_GET['roll_number']) : ''; ?>">
                                </div>
                                
                                <div class="col-md-12">
                                    <button type="submit" name="search" class="btn btn-primary">
                                        <i class="fas fa-search"></i> অনুসন্ধান
                                    </button>
                                    <a href="search.php" class="btn btn-secondary">
                                        <i class="fas fa-refresh"></i> রিসেট
                                    </a>
                                </div>
                            </div>
                        </form>
                        
                        <?php if ($search_performed): ?>
                            <div class="mt-4">
                                <h5>অনুসন্ধানের ফলাফল</h5>
                                <?php if (empty($search_results)): ?>
                                    <div class="alert alert-warning">
                                        <i class="fas fa-exclamation-triangle"></i> কোন শিক্ষার্থী পাওয়া যায়নি।
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>ছবি</th>
                                                    <th>শিক্ষার্থী আইডি</th>
                                                    <th>নাম</th>
                                                    <th>ক্লাস</th>
                                                    <th>সেশন</th>
                                                    <th>গ্রুপ</th>
                                                    <th>রোল</th>
                                                    <th>ফোন</th>
                                                    <th class="no-print">কার্যক্রম</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($search_results as $student): ?>
                                                    <tr>
                                                        <td>
                                                            <?php if ($student['photo']): ?>
                                                                <img src="../../<?php echo $student['photo']; ?>" alt="<?php echo $student['first_name']; ?>" class="profile-img-small">
                                                            <?php else: ?>
                                                                <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                                    <i class="fas fa-user text-white"></i>
                                                                </div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><strong><?php echo $student['student_id']; ?></strong></td>
                                                        <td>
                                                            <div>
                                                                <strong><?php echo $student['first_name'] . ' ' . $student['last_name']; ?></strong>
                                                                <?php if ($student['email']): ?>
                                                                    <br><small class="text-muted"><?php echo $student['email']; ?></small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <?php if ($student['class_name']): ?>
                                                                <span class="badge bg-primary"><?php echo $student['class_name'] . ' - ' . $student['class_section']; ?></span>
                                                            <?php else: ?>
                                                                <span class="text-muted">-</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?php echo $student['session_name'] ?: '-'; ?></td>
                                                        <td><?php echo $student['group_name'] ?: '-'; ?></td>
                                                        <td><span class="badge bg-info"><?php echo $student['roll_number']; ?></span></td>
                                                        <td><?php echo $student['phone'] ?: '-'; ?></td>
                                                        <td class="no-print">
                                                            <div class="btn-group btn-group-sm">
                                                                <a href="../../students/view.php?id=<?php echo $student['id']; ?>" class="btn btn-info" title="বিস্তারিত দেখুন">
                                                                    <i class="fas fa-eye"></i>
                                                                </a>
                                                                <a href="../../students/id_card.php?id=<?php echo $student['id']; ?>" class="btn btn-primary" title="আইডি কার্ড দেখুন" target="_blank">
                                                                    <i class="fas fa-id-card"></i>
                                                                </a>
                                                                <?php if ($_SESSION['user_role'] == 'admin' || $_SESSION['user_role'] == 'teacher'): ?>
                                                                <a href="../../students/edit.php?id=<?php echo $student['id']; ?>" class="btn btn-warning" title="সম্পাদনা">
                                                                    <i class="fas fa-edit"></i>
                                                                </a>
                                                                <?php endif; ?>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-3">
                                        <p class="text-muted">মোট <?php echo count($search_results); ?> জন শিক্ষার্থী পাওয়া গেছে।</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../../assets/js/script.js"></script>
</body>
</html>