<?php
session_start();

// Include access control functions
require_once '../includes/access_control.php';
require_once '../config/database.php';

// Check if user is logged in and has appropriate role
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'teacher')) {
    header('Location: ../login.php');
    exit();
}

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

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Search and filter
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'active';

// Build query
$where_conditions = ["t.status = :status"];
$params = ['status' => $status_filter];

if (!empty($search)) {
    $where_conditions[] = "(t.first_name LIKE :search OR t.last_name LIKE :search OR t.employee_id LIKE :search OR t.email LIKE :search OR t.phone LIKE :search OR t.designation LIKE :search)";
    $params['search'] = "%$search%";
}

$where_clause = implode(' AND ', $where_conditions);

// Get total count
$count_sql = "SELECT COUNT(*) FROM teachers t WHERE $where_clause";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

// Get teachers
$sql = "
    SELECT t.*, u.username, u.email as user_email
    FROM teachers t 
    LEFT JOIN users u ON t.user_id = u.id 
    WHERE $where_clause
    ORDER BY t.created_at DESC 
    LIMIT :limit OFFSET :offset
";
$stmt = $pdo->prepare($sql);
foreach ($params as $key => $value) {
    $stmt->bindValue(":$key", $value);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$teachers = $stmt->fetchAll();
?>

<!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/style.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
    html, body, .table, .card, .navbar, .form-control, .form-select, .btn { font-family: 'Hind Siliguri', sans-serif !important; }
    .table th, .table td { font-family: 'Hind Siliguri', sans-serif !important; }
        /* Print adjustments for compact, page-fitted list */
        @media print {
            @page { size: A4 landscape; margin: 8mm; }
            html, body { height: auto; }
            body { -webkit-print-color-adjust: exact; print-color-adjust: exact; font-size: 11px; }

            /* Hide chrome */
            .navbar, .no-print, form, .alert, .pagination, .btn, .input-group, .form-select { display: none !important; }
            .card, .card-header, .card-body { border: 0 !important; box-shadow: none !important; }
            .card-body { padding: 0 !important; }

            /* Table formatting */
            .table { width: 100% !important; border-collapse: collapse !important; font-size: 11px; }
            .table th, .table td { border: 1px solid #000 !important; padding: 4px 6px !important; vertical-align: top; word-break: break-word; }
            .table thead th { background: #000 !important; color: #fff !important; font-weight: 700 !important; }

            /* Hide photo column to save space */
            .table thead th:nth-child(1),
            .table tbody td:nth-child(1) { display: none !important; }

            /* Signature column height in print */
            .table tbody td:nth-last-child(2) { height: 28px !important; }
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="<?php echo ($_SESSION['user_role'] == 'teacher') ? 'dashboard.php' : '../index.php'; ?>">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="<?php echo ($_SESSION['user_role'] == 'teacher') ? 'dashboard.php' : '../index.php'; ?>">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-chalkboard-teacher"></i> শিক্ষক তালিকা</h5>
                        <div>
                            <?php if ($_SESSION['user_role'] == 'admin'): ?>
                            <a href="add.php" class="btn btn-success btn-sm">
                                <i class="fas fa-plus"></i> নতুন শিক্ষক যোগ
                            </a>
                            <a href="routine.php" class="btn btn-primary btn-sm">
                                <i class="fas fa-calendar-alt"></i> ক্লাস রুটিন
                            </a>
                            <?php endif; ?>
                            <button class="btn btn-info btn-sm" onclick="window.print()">
                                <i class="fas fa-print"></i> প্রিন্ট
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Display success or error messages -->
                        <?php if (isset($_SESSION['success_message'])): ?>
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success_message']; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                            <?php unset($_SESSION['success_message']); ?>
                        <?php endif; ?>
                        
                        <?php if (isset($_SESSION['error_message'])): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $_SESSION['error_message']; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                            <?php unset($_SESSION['error_message']); ?>
                        <?php endif; ?>

                        <!-- Search and Filter -->
                        <form method="GET" class="mb-4">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="input-group">
                                        <span class="input-group-text">
                                            <i class="fas fa-search"></i>
                                        </span>
                                        <input type="text" class="form-control" name="search" 
                                               placeholder="নাম, আইডি, ইমেইল বা ফোন দিয়ে খুঁজুন" 
                                               value="<?php echo htmlspecialchars($search); ?>">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <select class="form-select" name="status">
                                        <option value="active" <?php echo ($status_filter == 'active') ? 'selected' : ''; ?>>সক্রিয়</option>
                                        <option value="inactive" <?php echo ($status_filter == 'inactive') ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <div class="btn-group w-100">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-search"></i> খুঁজুন
                                        </button>
                                        <a href="list.php" class="btn btn-secondary">
                                            <i class="fas fa-refresh"></i> রিসেট
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <!-- Results Info -->
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <span class="text-muted">
                                    মোট <?php echo $total_records; ?> জন শিক্ষক পাওয়া গেছে
                                    (পৃষ্ঠা <?php echo $page; ?> এর <?php echo $total_pages; ?>)
                                </span>
                            </div>
                        </div>

                        <!-- Teachers Table -->
                        <div class="table-responsive">
                            <table class="table table-striped table-hover table-sm align-middle">
                                <thead>
                                    <tr>
                                        <th>ছবি</th>
                                        <th>কর্মচারী আইডি</th>
                                        <th>নাম</th>
                                        <th>পদবী</th>
                                        <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 if (empty($teachers)): ?>
                                        <tr>
                                            <td colspan="13" class="text-center py-4">
                                                <i class="fas fa-chalkboard-teacher fa-3x text-muted mb-3"></i>
                                                <p class="text-muted">কোন শিক্ষক পাওয়া যায়নি</p>
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($teachers as $teacher): ?>
                                            <tr class="searchable">
                                                <td>
                                                    <?php if ($teacher['photo']): ?>
                                                        <img src="../<?php echo $teacher['photo']; ?>" 
                                                             alt="<?php echo $teacher['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 $teacher['employee_id']; ?></strong>
                                                </td>
                                                <td>
                                                    <div>
                                                        <strong><?php echo $teacher['first_name'] . ' ' . $teacher['last_name']; ?></strong>
                                                        <?php if ($teacher['username']): ?>
                                                            <br><small class="text-muted">@<?php echo $teacher['username']; ?></small>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                                <td><?php echo $teacher['designation'] ? htmlspecialchars($teacher['designation']) : '<span class="text-muted">-</span>'; ?></td>
                                                <td><?php echo !empty($teacher['date_of_birth']) ? date('d-m-Y', strtotime($teacher['date_of_birth'])) : '-'; ?></td>
                                                <td><?php echo !empty($teacher['joining_date']) ? date('d-m-Y', strtotime($teacher['joining_date'])) : '-'; ?></td>
                                                <td><?php echo $teacher['email']; ?></td>
                                                <td><?php echo $teacher['phone'] ?: '-'; ?></td>
                                                <td><?php echo $teacher['qualification'] ?: '-'; ?></td>
                                                <td>
                                                    <?php if ($teacher['experience_years'] > 0): ?>
                                                        <span class="badge bg-info"><?php echo $teacher['experience_years']; ?> বছর</span>
                                                    <?php else: ?>
                                                        <span class="text-muted">নতুন</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($teacher['salary'] > 0): ?>
                                                        ৳<?php echo number_format($teacher['salary'], 0); ?>
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td style="height:32px; min-width:90px;"></td>
                                                <td class="no-print">
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="view.php?id=<?php echo $teacher['id']; ?>" 
                                                           class="btn btn-info" title="বিস্তারিত দেখুন">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        <?php if ($_SESSION['user_role'] == 'admin'): ?>
                                                        <a href="edit.php?id=<?php echo $teacher['id']; ?>" 
                                                           class="btn btn-warning" title="সম্পাদনা">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <a href="delete.php?id=<?php echo $teacher['id']; ?>" 
                                                           class="btn btn-danger btn-delete" 
                                                           title="মুছে ফেলুন"
                                                           data-item-name="<?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?>">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Signature Area for print -->
                        <div class="mt-5 d-print-block" style="page-break-inside: avoid;">
                            <div class="row text-center">
                                <div class="col-4">
                                    <div style="border-top:1px solid #000; margin-top:60px; padding-top:6px;">প্রস্তুতকারীর স্বাক্ষর</div>
                                </div>
                                <div class="col-4">
                                    <div style="border-top:1px solid #000; margin-top:60px; padding-top:6px;">শাখা প্রধান</div>
                                </div>
                                <div class="col-4">
                                    <div style="border-top:1px solid #000; margin-top:60px; padding-top:6px;">প্রধান শিক্ষক</div>
                                </div>
                            </div>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                            <nav aria-label="Page navigation" class="mt-4 no-print">
                                <ul class="pagination justify-content-center">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                                                <i class="fas fa-chevron-left"></i> পূর্ববর্তী
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <?php
                                    $start_page = max(1, $page - 2);
                                    $end_page = min($total_pages, $page + 2);
                                    
                                    for ($i = $start_page; $i <= $end_page; $i++): ?>
                                        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>">
                                                <?php echo $i; ?>
                                            </a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if ($page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                                                পরবর্তী <i class="fas fa-chevron-right"></i>
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        <?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>
    <script>
        // Auto-submit search form on filter change
        document.querySelector('select[name="status"]').addEventListener('change', function() {
            this.form.submit();
        });
        
        // Add event listener for delete buttons after DOM is loaded
        document.addEventListener('DOMContentLoaded', function() {
            const deleteButtons = document.querySelectorAll('.btn-delete');
            deleteButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    const itemName = this.dataset.itemName || 'এই শিক্ষক';
                    
                    if (confirm(`আপনি কি নিশ্চিত যে "${itemName}" মুছে ফেলতে চান? এই কাজটি পূর্বাবস্থায় ফেরানো যাবে না।`)) {
                        // Show loading message
                        const originalText = this.innerHTML;
                        this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> মুছে ফেলা হচ্ছে...';
                        this.disabled = true;
                        
                        // Proceed with deletion after a short delay to show the loading message
                        setTimeout(() => {
                            window.location.href = this.href;
                        }, 100);
                    }
                });
            });
        });
    </script>
</body>
</html>