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

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

// Get filter parameters
$status_filter = isset($_GET['status_filter']) ? $_GET['status_filter'] : '';
$gender_filter = isset($_GET['gender_filter']) ? $_GET['gender_filter'] : '';
$search_text = isset($_GET['search_text']) ? trim($_GET['search_text']) : '';
$search_by = isset($_GET['search_by']) ? $_GET['search_by'] : 'name';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$experience_min = isset($_GET['experience_min']) ? $_GET['experience_min'] : '';
$experience_max = isset($_GET['experience_max']) ? $_GET['experience_max'] : '';
$show_results = isset($_GET['search']);

$teachers = [];
$total_teachers = 0;

if ($show_results) {
    // Build SQL query with filters
    $sql = "
        SELECT t.*,
               u.username, u.email as user_email, u.status as user_status,
               (SELECT COUNT(DISTINCT cs.class_id) FROM class_subjects cs WHERE cs.teacher_id = t.id) as total_classes,
               (SELECT COUNT(DISTINCT cs.subject_id) FROM class_subjects cs WHERE cs.teacher_id = t.id) as total_subjects
        FROM teachers t
        LEFT JOIN users u ON t.user_id = u.id
        WHERE 1=1
    ";
    $params = [];
    
    // Apply filters
    if (!empty($status_filter)) {
        $sql .= " AND t.status = ?";
        $params[] = $status_filter;
    }
    
    if (!empty($gender_filter)) {
        $sql .= " AND t.gender = ?";
        $params[] = $gender_filter;
    }
    
    if (!empty($search_text)) {
        switch ($search_by) {
            case 'name':
                $sql .= " AND (t.first_name LIKE ? OR t.last_name LIKE ? OR CONCAT(t.first_name, ' ', t.last_name) LIKE ?)";
                $search_param = '%' . $search_text . '%';
                $params[] = $search_param;
                $params[] = $search_param;
                $params[] = $search_param;
                break;
            case 'employee_id':
                $sql .= " AND t.employee_id LIKE ?";
                $params[] = '%' . $search_text . '%';
                break;
            case 'phone':
                $sql .= " AND t.phone LIKE ?";
                $params[] = '%' . $search_text . '%';
                break;
            case 'email':
                $sql .= " AND t.email LIKE ?";
                $params[] = '%' . $search_text . '%';
                break;
            case 'qualification':
                $sql .= " AND t.qualification LIKE ?";
                $params[] = '%' . $search_text . '%';
                break;
        }
    }
    
    if (!empty($date_from)) {
        $sql .= " AND t.joining_date >= ?";
        $params[] = $date_from;
    }
    
    if (!empty($date_to)) {
        $sql .= " AND t.joining_date <= ?";
        $params[] = $date_to;
    }
    
    if (!empty($experience_min)) {
        $sql .= " AND t.experience_years >= ?";
        $params[] = $experience_min;
    }
    
    if (!empty($experience_max)) {
        $sql .= " AND t.experience_years <= ?";
        $params[] = $experience_max;
    }
    
    $sql .= " ORDER BY t.first_name, t.last_name";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $teachers = $stmt->fetchAll();
    $total_teachers = count($teachers);
}

// Get statistics for display
$stats = [];
if ($show_results && !empty($teachers)) {
    $stats = [
        'total' => count($teachers),
        'male' => count(array_filter($teachers, fn($t) => $t['gender'] == 'male')),
        'female' => count(array_filter($teachers, fn($t) => $t['gender'] == 'female')),
        'active' => count(array_filter($teachers, fn($t) => $t['status'] == 'active')),
        'inactive' => count(array_filter($teachers, fn($t) => $t['status'] == 'inactive')),
        'avg_experience' => !empty($teachers) ? round(array_sum(array_column($teachers, 'experience_years')) / count($teachers), 1) : 0
    ];
}
?>

<!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">
    <style>
        .search-panel {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .report-header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .stats-card {
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .report-table {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .report-table table {
            margin-bottom: 0;
        }
        
        .report-table th {
            background: #0d6efd;
            color: white;
            font-weight: 600;
            white-space: nowrap;
        }
        
        .report-table td {
            vertical-align: middle;
        }
        
        /* Print styles */
        @media print {
            .no-print {
                display: none !important;
            }
            
            body {
                font-size: 12px;
            }
            
            .report-header {
                box-shadow: none;
                border: 2px solid #000;
            }
            
            .report-table {
                box-shadow: none;
            }
            
            .report-table th {
                background: #e9ecef !important;
                color: black !important;
                border: 1px solid #000 !important;
            }
            
            .report-table td {
                border: 1px solid #000 !important;
            }
            
            table {
                page-break-inside: auto;
            }
            
            tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }
            
            thead {
                display: table-header-group;
            }
            
            .stats-card {
                box-shadow: none;
                border: 1px solid #ddd;
            }
        }
    </style>
</head>
<body>
    <!-- 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> স্কুল ম্যানেজমেন্ট সিস্টেম
            </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_report.php">
                    <i class="fas fa-user-graduate"></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">
        <!-- Search Panel -->
        <div class="search-panel no-print">
            <h4 class="mb-3"><i class="fas fa-search"></i> উন্নত অনুসন্ধান বিকল্প</h4>
            <form method="GET" action="" id="searchForm">
                <input type="hidden" name="search" value="1">
                
                <div class="row g-3">
                    <!-- Status Filter -->
                    <div class="col-md-2">
                        <label class="form-label">স্ট্যাটাস</label>
                        <select name="status_filter" class="form-select">
                            <option value="">সকল স্ট্যাটাস</option>
                            <option value="active" <?php echo ($status_filter == 'active') ? 'selected' : ''; ?>>সক্রিয়</option>
                            <option value="inactive" <?php echo ($status_filter == 'inactive') ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                        </select>
                    </div>
                    
                    <!-- Gender Filter -->
                    <div class="col-md-2">
                        <label class="form-label">লিঙ্গ</label>
                        <select name="gender_filter" class="form-select">
                            <option value="">সকল লিঙ্গ</option>
                            <option value="male" <?php echo ($gender_filter == 'male') ? 'selected' : ''; ?>>পুরুষ</option>
                            <option value="female" <?php echo ($gender_filter == 'female') ? 'selected' : ''; ?>>মহিলা</option>
                            <option value="other" <?php echo ($gender_filter == 'other') ? 'selected' : ''; ?>>অন্যান্য</option>
                        </select>
                    </div>
                    
                    <!-- Search By -->
                    <div class="col-md-2">
                        <label class="form-label">অনুসন্ধান করুন</label>
                        <select name="search_by" class="form-select">
                            <option value="name" <?php echo ($search_by == 'name') ? 'selected' : ''; ?>>নাম</option>
                            <option value="employee_id" <?php echo ($search_by == 'employee_id') ? 'selected' : ''; ?>>কর্মচারী আইডি</option>
                            <option value="phone" <?php echo ($search_by == 'phone') ? 'selected' : ''; ?>>ফোন</option>
                            <option value="email" <?php echo ($search_by == 'email') ? 'selected' : ''; ?>>ইমেইল</option>
                            <option value="qualification" <?php echo ($search_by == 'qualification') ? 'selected' : ''; ?>>যোগ্যতা</option>
                        </select>
                    </div>
                    
                    <!-- Search Text -->
                    <div class="col-md-3">
                        <label class="form-label">অনুসন্ধান টেক্সট</label>
                        <input type="text" name="search_text" class="form-control" 
                               value="<?php echo htmlspecialchars($search_text); ?>"
                               placeholder="অনুসন্ধান করুন...">
                    </div>
                    
                    <!-- Experience Min -->
                    <div class="col-md-1.5">
                        <label class="form-label">অভিজ্ঞতা (মিনিট)</label>
                        <input type="number" name="experience_min" class="form-control" 
                               value="<?php echo htmlspecialchars($experience_min); ?>"
                               placeholder="0" min="0">
                    </div>
                    
                    <!-- Experience Max -->
                    <div class="col-md-1.5">
                        <label class="form-label">অভিজ্ঞতা (সর্বোচ্চ)</label>
                        <input type="number" name="experience_max" class="form-control" 
                               value="<?php echo htmlspecialchars($experience_max); ?>"
                               placeholder="50" min="0">
                    </div>
                </div>
                
                <div class="row g-3 mt-2">
                    <!-- Date From -->
                    <div class="col-md-3">
                        <label class="form-label">যোগদানের তারিখ (থেকে)</label>
                        <input type="date" name="date_from" class="form-control" 
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    
                    <!-- Date To -->
                    <div class="col-md-3">
                        <label class="form-label">যোগদানের তারিখ (পর্যন্ত)</label>
                        <input type="date" name="date_to" class="form-control" 
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                    
                    <!-- Buttons -->
                    <div class="col-md-6 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-search"></i> অনুসন্ধান করুন
                        </button>
                        <a href="teachers_report.php" class="btn btn-secondary me-2">
                            <i class="fas fa-redo"></i> রিসেট
                        </a>
                        <?php if ($show_results): ?>
                        <button type="button" class="btn btn-success" onclick="window.print()">
                            <i class="fas fa-print"></i> প্রিন্ট করুন
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>

        <?php if ($show_results): ?>
        
        <!-- Report Header -->
        <div class="report-header">
            <h2>শিক্ষক তথ্য রিপোর্ট</h2>
            <p class="mb-0">প্রতিবেদনের তারিখ: <?php echo date('d/m/Y'); ?></p>
        </div>

        <!-- Statistics Cards -->
        <?php if (!empty($stats)): ?>
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-primary"><?php echo $stats['total']; ?></h4>
                    <p class="mb-0">মোট শিক্ষক</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-info"><?php echo $stats['male']; ?></h4>
                    <p class="mb-0">পুরুষ</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-danger"><?php echo $stats['female']; ?></h4>
                    <p class="mb-0">মহিলা</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-success"><?php echo $stats['active']; ?></h4>
                    <p class="mb-0">সক্রিয়</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-warning"><?php echo $stats['inactive']; ?></h4>
                    <p class="mb-0">নিষ্ক্রিয়</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-info"><?php echo $stats['avg_experience']; ?></h4>
                    <p class="mb-0">গড় অভিজ্ঞতা (বছর)</p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Results Table -->
        <?php if (!empty($teachers)): ?>
        <div class="report-table">
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>ক্রমিক</th>
                            <th>কর্মচারী আইডি</th>
                            <th>নাম</th>
                            <th>লিঙ্গ</th>
                            <th>ফোন</th>
                            <th>ইমেইল</th>
                            <th>যোগ্যতা</th>
                            <th>অভিজ্ঞতা (বছর)</th>
                            <th>যোগদানের তারিখ</th>
                            <th class="no-print">শ্রেণী</th>
                            <th class="no-print">বিষয়</th>
                            <th>স্ট্যাটাস</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($teachers as $index => $teacher): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><?php echo htmlspecialchars($teacher['employee_id']); ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?></strong>
                            </td>
                            <td>
                                <?php 
                                $gender_text = ['male' => 'পুরুষ', 'female' => 'মহিলা', 'other' => 'অন্যান্য'];
                                echo $gender_text[$teacher['gender']] ?? '';
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($teacher['phone'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($teacher['email'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($teacher['qualification'] ?? 'N/A'); ?></td>
                            <td class="text-center"><?php echo htmlspecialchars($teacher['experience_years'] ?? '0'); ?></td>
                            <td><?php echo $teacher['joining_date'] ? date('d/m/Y', strtotime($teacher['joining_date'])) : 'N/A'; ?></td>
                            <td class="no-print text-center"><?php echo $teacher['total_classes'] ?? '0'; ?></td>
                            <td class="no-print text-center"><?php echo $teacher['total_subjects'] ?? '0'; ?></td>
                            <td>
                                <?php
                                $status_badges = [
                                    'active' => '<span class="badge bg-success">সক্রিয়</span>',
                                    'inactive' => '<span class="badge bg-warning">নিষ্ক্রিয়</span>'
                                ];
                                echo $status_badges[$teacher['status']] ?? '';
                                ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="mt-3 text-center">
            <p><strong>মোট শিক্ষক সংখ্যা: <?php echo $total_teachers; ?></strong></p>
        </div>
        
        <?php elseif ($show_results): ?>
        <div class="alert alert-info">
            <i class="fas fa-info-circle"></i> কোনো শিক্ষক খুঁজে পাওয়া যায়নি। অনুগ্রহ করে অনুসন্ধান শর্ত পরিবর্তন করুন।
        </div>
        <?php endif; ?>
        
        <?php else: ?>
        <div class="alert alert-info text-center">
            <i class="fas fa-info-circle"></i> শিক্ষক রিপোর্ট দেখতে উপরের ফিল্টার ব্যবহার করে অনুসন্ধান করুন।
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
