<?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
$role_filter = isset($_GET['role_filter']) ? $_GET['role_filter'] : '';
$status_filter = isset($_GET['status_filter']) ? $_GET['status_filter'] : '';
$search_text = isset($_GET['search_text']) ? trim($_GET['search_text']) : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$show_results = isset($_GET['search']);

$users = [];
$total_users = 0;

if ($show_results) {
    // Build SQL query with filters
    $sql = "
        SELECT u.*,
               CASE 
                   WHEN u.role = 'student' THEN CONCAT(s.first_name, ' ', s.last_name)
                   WHEN u.role = 'teacher' THEN CONCAT(t.first_name, ' ', t.last_name)
                   ELSE u.username
               END as full_name,
               CASE 
                   WHEN u.role = 'student' THEN s.phone
                   WHEN u.role = 'teacher' THEN t.phone
                   ELSE NULL
               END as phone,
               CASE 
                   WHEN u.role = 'student' THEN c.name
                   ELSE NULL
               END as class_name,
               CASE 
                   WHEN u.role = 'student' THEN s.student_id
                   WHEN u.role = 'teacher' THEN t.employee_id
                   ELSE NULL
               END as identifier
        FROM users u
        LEFT JOIN students s ON u.id = s.user_id AND u.role = 'student'
        LEFT JOIN teachers t ON u.id = t.user_id AND u.role = 'teacher'
        LEFT JOIN classes c ON s.class_id = c.id
        WHERE 1=1
    ";
    $params = [];
    
    // Apply filters
    if (!empty($role_filter)) {
        $sql .= " AND u.role = ?";
        $params[] = $role_filter;
    }
    
    if (!empty($status_filter)) {
        $sql .= " AND u.status = ?";
        $params[] = $status_filter;
    }
    
    if (!empty($search_text)) {
        $sql .= " AND (
            u.username LIKE ? OR 
            u.email LIKE ? OR 
            CONCAT(s.first_name, ' ', s.last_name) LIKE ? OR 
            CONCAT(t.first_name, ' ', t.last_name) LIKE ? OR
            s.student_id LIKE ? OR
            t.employee_id LIKE ?
        )";
        $search_param = '%' . $search_text . '%';
        $params[] = $search_param;
        $params[] = $search_param;
        $params[] = $search_param;
        $params[] = $search_param;
        $params[] = $search_param;
        $params[] = $search_param;
    }
    
    if (!empty($date_from)) {
        $sql .= " AND u.created_at >= ?";
        $params[] = $date_from;
    }
    
    if (!empty($date_to)) {
        $sql .= " AND u.created_at <= ?";
        $params[] = $date_to . ' 23:59:59';
    }
    
    $sql .= " ORDER BY u.role, u.created_at DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $users = $stmt->fetchAll();
    $total_users = count($users);
}

// Get statistics for display
$stats = [];
if ($show_results && !empty($users)) {
    $stats = [
        'total' => count($users),
        'admin' => count(array_filter($users, fn($u) => $u['role'] == 'admin')),
        'teacher' => count(array_filter($users, fn($u) => $u['role'] == 'teacher')),
        'student' => count(array_filter($users, fn($u) => $u['role'] == 'student')),
        'parent' => count(array_filter($users, fn($u) => $u['role'] == 'parent')),
        'active' => count(array_filter($users, fn($u) => $u['status'] == 'active')),
        'inactive' => count(array_filter($users, fn($u) => $u['status'] == 'inactive'))
    ];
}
?>

<!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="teachers_report.php">
                    <i class="fas fa-chalkboard-teacher"></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">
                    <!-- Role Filter -->
                    <div class="col-md-3">
                        <label class="form-label">ইউজার টাইপ</label>
                        <select name="role_filter" class="form-select">
                            <option value="">সকল ইউজার</option>
                            <option value="admin" <?php echo ($role_filter == 'admin') ? 'selected' : ''; ?>>অ্যাডমিন</option>
                            <option value="teacher" <?php echo ($role_filter == 'teacher') ? 'selected' : ''; ?>>শিক্ষক</option>
                            <option value="student" <?php echo ($role_filter == 'student') ? 'selected' : ''; ?>>শিক্ষার্থী</option>
                            <option value="parent" <?php echo ($role_filter == 'parent') ? 'selected' : ''; ?>>অভিভাবক</option>
                        </select>
                    </div>
                    
                    <!-- 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>
                    
                    <!-- Search Text -->
                    <div class="col-md-4">
                        <label class="form-label">অনুসন্ধান টেক্সট</label>
                        <input type="text" name="search_text" class="form-control" 
                               value="<?php echo htmlspecialchars($search_text); ?>"
                               placeholder="নাম, ইমেইল, আইডি...">
                    </div>
                    
                    <!-- Date From -->
                    <div class="col-md-1.5">
                        <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-1.5">
                        <label class="form-label">তারিখ (পর্যন্ত)</label>
                        <input type="date" name="date_to" class="form-control" 
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                </div>
                
                <div class="row g-3 mt-2">
                    <!-- Buttons -->
                    <div class="col-md-12 d-flex">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-search"></i> অনুসন্ধান করুন
                        </button>
                        <a href="all_users_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-danger"><?php echo $stats['admin']; ?></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['teacher']; ?></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['student']; ?></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['parent']; ?></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>
        <?php endif; ?>

        <!-- Results Table -->
        <?php if (!empty($users)): ?>
        <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>স্ট্যাটাস</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $index => $user): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($user['full_name']); ?></strong>
                            </td>
                            <td><?php echo htmlspecialchars($user['identifier'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                            <td><?php echo htmlspecialchars($user['phone'] ?? 'N/A'); ?></td>
                            <td>
                                <?php
                                $role_badges = [
                                    'admin' => '<span class="badge bg-danger">অ্যাডমিন</span>',
                                    'teacher' => '<span class="badge bg-success">শিক্ষক</span>',
                                    'student' => '<span class="badge bg-info">শিক্ষার্থী</span>',
                                    'parent' => '<span class="badge bg-warning">অভিভাবক</span>'
                                ];
                                echo $role_badges[$user['role']] ?? '';
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($user['class_name'] ?? '-'); ?></td>
                            <td><?php echo date('d/m/Y', strtotime($user['created_at'])); ?></td>
                            <td>
                                <?php
                                $status_badges = [
                                    'active' => '<span class="badge bg-success">সক্রিয়</span>',
                                    'inactive' => '<span class="badge bg-warning">নিষ্ক্রিয়</span>'
                                ];
                                echo $status_badges[$user['status']] ?? '';
                                ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="mt-3 text-center">
            <p><strong>মোট ইউজার সংখ্যা: <?php echo $total_users; ?></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>
