<?php
/**
 * ===================================================================================
 * Material Actions Handler (with Publish)
 * ===================================================================================
 *
 * File: material_actions.php
 * Location: /homework_portal/teacher/material_actions.php
 *
 * Purpose:
 * 1. Securely handles actions like deleting or publishing posted materials.
 * 2. Ensures a teacher can only modify their own materials.
 */

require_once '../config.php';

// --- Security Check: Ensure teacher is logged in ---
if (!isset($_SESSION['teacher_id'])) {
    header('Location: login.php');
    exit();
}

$teacher_id = $_SESSION['teacher_id'];
$action = $_GET['action'] ?? '';
$assignment_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message_type = 'error';
$message = 'An unknown error occurred.';

if ($assignment_id > 0) {
    try {
        // First, verify the teacher owns this material for any action
        $check_stmt = $pdo->prepare("SELECT file_path FROM assignments WHERE id = ? AND teacher_id = ?");
        $check_stmt->execute([$assignment_id, $teacher_id]);
        $assignment = $check_stmt->fetch();

        if ($assignment) {
            // Ownership confirmed, proceed with the action
            switch ($action) {
                case 'delete':
                    // If an associated file exists, delete it
                    if (!empty($assignment['file_path']) && file_exists($assignment['file_path'])) {
                        @unlink($assignment['file_path']);
                    }
                    $delete_stmt = $pdo->prepare("DELETE FROM assignments WHERE id = ?");
                    $delete_stmt->execute([$assignment_id]);
                    $message = 'Material has been deleted successfully.';
                    $message_type = 'success';
                    break;
                
                case 'publish':
                    // Change the status from 'draft' to 'published'
                    $publish_stmt = $pdo->prepare("UPDATE assignments SET status = 'published' WHERE id = ?");
                    $publish_stmt->execute([$assignment_id]);
                    $message = 'Material has been published and is now visible to students.';
                    $message_type = 'success';
                    break;

                default:
                    $message = 'Invalid action specified.';
                    break;
            }
        } else {
            $message = "Material not found or you don't have permission to modify it.";
        }
    } catch (PDOException $e) {
        $message = "Database error: " . $e->getMessage();
    }
} else {
    $message = "Invalid material ID.";
}

// Redirect back to the materials management page with feedback.
header('Location: my_materials.php?' . $message_type . '=' . urlencode($message));
exit();
?>
