<?php
/**
 * ===================================================================================
 * Private File Actions Handler (for Teachers)
 * ===================================================================================
 *
 * File: private_file_actions.php
 * Location: /homework_portal/teacher/private_file_actions.php
 *
 * Purpose:
 * 1. Handles actions like deleting a private file for a student.
 * 2. Ensures a teacher can only delete files they themselves uploaded.
 */

require_once '../config.php';

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

$teacher_id = $_SESSION['teacher_id'];
$action = $_GET['action'] ?? '';
$file_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$student_id_redirect = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0; // For redirecting back

$message_type = 'error';
$message = 'An unknown error occurred.';

if ($file_id > 0 && $action === 'delete') {
    try {
        // --- Ownership Verification ---
        // Ensure the file to be deleted was uploaded by the logged-in teacher.
        $stmt = $pdo->prepare("SELECT file_path FROM student_private_files WHERE id = ? AND teacher_id = ?");
        $stmt->execute([$file_id, $teacher_id]);
        $file = $stmt->fetch();

        if ($file) {
            // If the file exists on the server, delete it
            if (!empty($file['file_path']) && file_exists($file['file_path'])) {
                @unlink($file['file_path']);
            }

            // Proceed with deleting the database record
            $delete_stmt = $pdo->prepare("DELETE FROM student_private_files WHERE id = ?");
            $delete_stmt->execute([$file_id]);
            
            $message = 'Private file has been deleted successfully.';
            $message_type = 'success';
        } else {
            $message = "File not found or you don't have permission to delete it.";
        }
    } catch (PDOException $e) {
        $message = "Database error: Could not delete the file.";
    }
} else {
    $message = "Invalid action or file ID.";
}

// Redirect back to the student file inventory page with feedback.
header('Location: view_student_files.php?id=' . $student_id_redirect . '&' . $message_type . '=' . urlencode($message));
exit();
?>
