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

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

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

// Get user info based on role
$user_info = null;
if ($user_role == 'student') {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_info = $stmt->fetch();
} elseif ($user_role == 'teacher') {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_info = $stmt->fetch();
}

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

// Search and filter
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$category_filter = isset($_GET['category']) ? $_GET['category'] : '';

// Build query
$where_conditions = ["fu.uploader_type = ? AND fu.uploader_id = ? AND fu.status = 'active'"];
$params = [$user_role, $user_info ? $user_info['id'] : 0];

if (!empty($search)) {
    $where_conditions[] = "(fu.original_name LIKE ? OR fu.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($category_filter)) {
    $where_conditions[] = "fu.category = ?";
    $params[] = $category_filter;
}

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

// Get total count
$count_sql = "SELECT COUNT(*) FROM file_uploads fu 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 files
$sql = "
    SELECT fu.*, 
           c.name as class_name,
           sub.name as subject_name
    FROM file_uploads fu
    LEFT JOIN classes c ON fu.target_class_id = c.id
    LEFT JOIN subjects sub ON fu.target_subject_id = sub.id
    WHERE $where_clause
    ORDER BY fu.created_at DESC 
    LIMIT ? OFFSET ?
";
$stmt = $pdo->prepare($sql);
foreach ($params as $key => $value) {
    $stmt->bindValue($key + 1, $value);
}
$stmt->bindValue(count($params) + 1, $limit, PDO::PARAM_INT);
$stmt->bindValue(count($params) + 2, $offset, PDO::PARAM_INT);
$stmt->execute();
$files = $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">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <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-arrow-left"></i> ফিরে যান
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-folder"></i> ফাইল ব্যবস্থাপনা</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            <a href="upload.php" class="btn btn-success">
                                <i class="fas fa-plus"></i> নতুন ফাইল আপলোড
                            </a>
                            <a href="index.php" class="btn btn-outline-primary">
                                <i class="fas fa-home"></i> হোম
                            </a>
                        </div>
                        
                        <hr>
                        
                        <!-- File Statistics -->
                        <div class="text-center">
                            <h6>পরিসংখ্যান</h6>
                            <p class="text-muted small">
                                মোট ফাইল: <strong><?php echo $total_records; ?></strong><br>
                                <?php
                                $total_size = 0;
                                foreach ($files as $file) {
                                    $total_size += $file['file_size'];
                                }
                                $size_mb = round($total_size / (1024 * 1024), 2);
                                ?>
                                ব্যবহৃত স্থান: <strong><?php echo $size_mb; ?>MB</strong>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4><i class="fas fa-file"></i> আমার ফাইলসমূহ</h4>
                            <span class="badge bg-primary"><?php echo $total_records; ?> টি ফাইল</span>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Search and Filter -->
                        <form method="GET" action="" class="mb-4">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="input-group">
                                        <input type="text" class="form-control" name="search" 
                                               placeholder="ফাইল নাম বা বিবরণ দিয়ে খুঁজুন" 
                                               value="<?php echo htmlspecialchars($search); ?>">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <select class="form-select" name="category" onchange="this.form.submit()">
                                        <option value="">সব ধরনের ফাইল</option>
                                        <option value="document" <?php echo ($category_filter == 'document') ? 'selected' : ''; ?>>ডকুমেন্ট</option>
                                        <option value="assignment" <?php echo ($category_filter == 'assignment') ? 'selected' : ''; ?>>অ্যাসাইনমেন্ট</option>
                                        <option value="image" <?php echo ($category_filter == 'image') ? 'selected' : ''; ?>>ছবি</option>
                                        <option value="video" <?php echo ($category_filter == 'video') ? 'selected' : ''; ?>>ভিডিও</option>
                                        <option value="other" <?php echo ($category_filter == 'other') ? 'selected' : ''; ?>>অন্যান্য</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <a href="my_files.php" class="btn btn-secondary w-100">
                                        <i class="fas fa-refresh"></i> রিসেট
                                    </a>
                                </div>
                            </div>
                        </form>

                        <!-- Files List -->
                        <?php if (empty($files)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">কোন ফাইল পাওয়া যায়নি</h5>
                                <p class="text-muted">আপনার প্রথম ফাইল আপলোড করুন</p>
                                <a href="upload.php" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> ফাইল আপলোড করুন
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ফাইল নাম</th>
                                            <th>ধরন</th>
                                            <th>সাইজ</th>
                                            <th>টার্গেট</th>
                                            <th>স্ট্যাটাস</th>
                                            <th>তারিখ</th>
                                            <th>কার্যক্রম</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($files as $file): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-file text-primary me-2"></i>
                                                        <div>
                                                            <strong><?php echo htmlspecialchars($file['original_name']); ?></strong>
                                                            <?php if ($file['description']): ?>
                                                                <br><small class="text-muted"><?php echo htmlspecialchars($file['description']); ?></small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="badge bg-secondary"><?php echo strtoupper($file['category']); ?></span>
                                                </td>
                                                <td><?php echo round($file['file_size'] / 1024, 2); ?> KB</td>
                                                <td>
                                                    <?php if ($file['class_name']): ?>
                                                        <span class="badge bg-info"><?php echo $file['class_name']; ?></span>
                                                    <?php endif; ?>
                                                    <?php if ($file['subject_name']): ?>
                                                        <br><span class="badge bg-warning"><?php echo $file['subject_name']; ?></span>
                                                    <?php endif; ?>
                                                    <?php if (!$file['class_name'] && !$file['subject_name']): ?>
                                                        <span class="text-muted">সাধারণ</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($file['is_public']): ?>
                                                        <span class="badge bg-success">পাবলিক</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-secondary">প্রাইভেট</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php echo date('d/m/Y', strtotime($file['created_at'])); ?>
                                                    <br><small class="text-muted"><?php echo date('H:i', strtotime($file['created_at'])); ?></small>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="download.php?id=<?php echo $file['id']; ?>" class="btn btn-outline-primary" title="ডাউনলোড">
                                                            <i class="fas fa-download"></i>
                                                        </a>
                                                        <a href="view.php?id=<?php echo $file['id']; ?>" class="btn btn-outline-info" title="দেখুন">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        <a href="edit.php?id=<?php echo $file['id']; ?>" class="btn btn-outline-warning" title="সম্পাদনা">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <a href="delete.php?id=<?php echo $file['id']; ?>" class="btn btn-outline-danger" title="মুছুন"
                                                           onclick="return confirm('এই ফাইলটি মুছে ফেলতে চান?')">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <!-- Pagination -->
                            <?php if ($total_pages > 1): ?>
                                <nav aria-label="Page navigation">
                                    <ul class="pagination justify-content-center">
                                        <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo ($page - 1); ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>">
                                                    <i class="fas fa-chevron-left"></i>
                                                </a>
                                            </li>
                                        <?php endif; ?>

                                        <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                            <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>">
                                                    <?php echo $i; ?>
                                                </a>
                                            </li>
                                        <?php endfor; ?>

                                        <?php if ($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo ($page + 1); ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>">
                                                    <i class="fas fa-chevron-right"></i>
                                                </a>
                                            </li>
                                        <?php endif; ?>
                                    </ul>
                                </nav>
                            <?php endif; ?>
                        <?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>
</body>
</html>