<?php
/**
 * IBVTE Admin - Manage Downloads
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

Auth()->requireRole(['super_admin', 'admin']);

$db = DB();
$flash = getFlashMessage();

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = cleanInput($_POST['title'] ?? '');
    $session = cleanInput($_POST['session'] ?? '');
    $category = cleanInput($_POST['category'] ?? '');
    
    if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === 0) {
        $targetDir = "../uploads/downloads/";
        if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);
        
        $fileName = time() . '_' . basename($_FILES['pdf_file']['name']);
        $targetPath = $targetDir . $fileName;
        
        if (move_uploaded_file($_FILES['pdf_file']['tmp_name'], $targetPath)) {
            $filePath = "uploads/downloads/" . $fileName;
            
            $db->insert('notifications', [
                'title' => $title,
                'category' => $category,
                'session' => $session,
                'attachment_path' => $filePath,
                'is_active' => 1,
                'published_at' => date('Y-m-d H:i:s')
            ]);
            
            redirectWithMessage('downloads.php', 'File uploaded and added to downloads successfully.', 'success');
        }
    }
}

// Fetch Downloads (Using notifications table as storage for simplicity as it has attachment_path)
$downloads = $db->fetchAll("SELECT * FROM notifications ORDER BY created_at DESC");

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Downloads - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: #3b0b7c; }
        body { background: #f4f7f6; font-family: 'Inter', sans-serif; }
        .sidebar { width: 250px; background: #2c3e50; min-height: 100vh; position: fixed; color: white; }
        .main-content { margin-left: 250px; padding: 30px; }
        .card-custom { border-radius: 15px; border: none; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
    </style>
</head>
<body>

<div class="sidebar p-4">
    <h4 class="fw-bold mb-4">IBVTE Admin</h4>
    <nav class="nav flex-column">
        <a class="nav-link text-white mb-2" href="dashboard.php"><i class="fas fa-home me-2"></i>Dashboard</a>
        <a class="nav-link text-white mb-2" href="fund-requests.php"><i class="fas fa-wallet me-2"></i>Fund Requests</a>
        <a class="nav-link text-white mb-2" href="students.php"><i class="fas fa-users me-2"></i>Students</a>
        <a class="nav-link text-white mb-2 active" href="downloads.php"><i class="fas fa-download me-2"></i>Downloads</a>
        <a class="nav-link text-danger mt-4" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a>
    </nav>
</div>

<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">Manage Downloads</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#uploadModal"><i class="fas fa-upload me-2"></i>Upload PDF</button>
    </div>

    <?php if ($flash): ?>
        <div class="alert alert-<?= $flash['type'] ?>"><?= $flash['message'] ?></div>
    <?php endif; ?>

    <div class="card card-custom p-4">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead class="bg-light">
                    <tr>
                        <th>Title</th>
                        <th>Session</th>
                        <th>Category</th>
                        <th>File</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($downloads)): ?>
                        <tr><td colspan="6" class="text-center py-5">No files found</td></tr>
                    <?php else: ?>
                        <?php foreach ($downloads as $d): ?>
                        <tr>
                            <td class="fw-bold"><?= htmlspecialchars($d['title']) ?></td>
                            <td><?= htmlspecialchars($d['session'] ?: 'All') ?></td>
                            <td><span class="badge bg-info"><?= ucfirst($d['category'] ?: 'General') ?></span></td>
                            <td><a href="../<?= $d['attachment_path'] ?>" target="_blank" class="btn btn-sm btn-outline-danger"><i class="fas fa-file-pdf"></i> PDF</a></td>
                            <td class="small"><?= date('d M, Y', strtotime($d['created_at'])) ?></td>
                            <td>
                                <button class="btn btn-sm btn-light"><i class="fas fa-trash text-danger"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow rounded-4">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">Upload New Document</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Title *</label>
                        <input type="text" name="title" class="form-control" required placeholder="e.g. Annual Result 2024">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Session</label>
                        <input type="text" name="session" class="form-control" placeholder="2024-25">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Category</label>
                        <select name="category" class="form-select">
                            <option value="results">Results</option>
                            <option value="syllabus">Syllabus</option>
                            <option value="timetable">Time Table</option>
                            <option value="forms">Forms</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">PDF File *</label>
                        <input type="file" name="pdf_file" class="form-control" accept="application/pdf" required>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4 fw-bold">Upload & Publish</button>
                </div>
            </form>
        </div>
    </div>
</div>

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