<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/Course.php';

requireLogin();
requireAnyRole(['instructor']);
$user = getCurrentUser();
$db = Database::getInstance();

// Handle deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['action']) && $_POST['action'] === 'delete' && !empty($_POST['id'])) {
    $id = (int)$_POST['id'];
    // Ensure media belongs to instructor
    $m = $db->get("SELECT m.* FROM course_media m JOIN courses c ON m.course_id = c.id WHERE m.id = ? AND c.instructor_id = ?", [$id, $user['id']]);
    if ($m) {
        // Remove files
        $paths = [];
        if (!empty($m['file_path'])) $paths[] = __DIR__ . '/../' . $m['file_path'];
        if (!empty($m['thumbnail_path'])) $paths[] = __DIR__ . '/../' . $m['thumbnail_path'];
        foreach ($paths as $p) {
            if (file_exists($p)) @unlink($p);
        }
        $db->query("DELETE FROM course_media WHERE id = ?", [$id]);
        setFlashMessage('success', 'Media deleted.');
    } else {
        setFlashMessage('error', 'Media not found or permission denied.');
    }
    header('Location: ' . APP_URL . '/lms/media.php');
    exit;
}

$pageTitle = 'Media';
include __DIR__ . '/includes/header.php';

$media = $db->getAll("SELECT m.*, c.title as course_title FROM course_media m JOIN courses c ON m.course_id = c.id WHERE c.instructor_id = ? ORDER BY m.created_at DESC", [$user['id']]);
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="m-0">Media</h5>
        <a href="<?php echo APP_URL; ?>/lms/dashboards/instructor.php" class="btn btn-outline-secondary btn-sm">Back</a>
    </div>
    <div class="card-body">
        <?php if (empty($media)): ?>
            <p class="text-muted">No uploaded media found.</p>
        <?php else: ?>
            <div class="row g-3">
                <?php foreach ($media as $m): ?>
                    <div class="col-md-4">
                        <div class="card">
                            <?php if (!empty($m['thumbnail_path'])): ?>
                                <img src="<?php echo htmlspecialchars($m['thumbnail_path']); ?>" class="card-img-top" alt="">
                            <?php endif; ?>
                            <div class="card-body">
                                <h6 class="card-title mb-1"><?php echo htmlspecialchars($m['course_title']); ?></h6>
                                <p class="small text-muted mb-2"><?php echo htmlspecialchars($m['mime']); ?> &bull; <?php echo (int)$m['size']; ?> bytes</p>
                                <form method="post" onsubmit="return confirm('Delete media?');">
                                    <input type="hidden" name="id" value="<?php echo (int)$m['id']; ?>">
                                    <button name="action" value="delete" class="btn btn-sm btn-outline-danger">Delete</button>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php';
