<?php
/**
 * ===================================================================================
 * Edit Material Page (for Teachers) - with File Upload
 * ===================================================================================
 *
 * File: edit_material.php
 * Location: /homework_portal/teacher/edit_material.php
 *
 * Purpose:
 * 1. Provides a form for a teacher to edit their posted materials.
 * 2. Allows updating the title, instructions, and replacing the attached file.
 * 3. Fetches existing data to pre-fill the form.
 * 4. Handles form submission to update the record.
 */

require_once '../config.php';

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

$teacher_id = $_SESSION['teacher_id'];
$assignment_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$errors = [];
$success_message = '';

if ($assignment_id <= 0) {
    header('Location: my_materials.php');
    exit();
}

// --- Fetch existing assignment data (with ownership check) ---
try {
    $stmt = $pdo->prepare("SELECT * FROM assignments WHERE id = ? AND teacher_id = ?");
    $stmt->execute([$assignment_id, $teacher_id]);
    $material = $stmt->fetch();
    if (!$material) {
        header('Location: my_materials.php?error=Material not found or permission denied.');
        exit();
    }
} catch (PDOException $e) {
    die("Database error fetching material data.");
}

// --- Handle Form Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_material'])) {
    $title = trim($_POST['title'] ?? '');
    $instructions = trim($_POST['instructions'] ?? '');
    $due_date = !empty($_POST['due_date']) ? trim($_POST['due_date']) : null;
    
    // Keep existing file path by default
    $file_path = $material['file_path'];
    $file_type = $material['file_type'];

    // --- Handle New File Upload ---
    if (isset($_FILES['new_assignment_file']) && $_FILES['new_assignment_file']['error'] == UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/assignments/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

        // Basic file validation
        $new_file_type = $_FILES['new_assignment_file']['type'];
        $allowed_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png'];
        if (!in_array($new_file_type, $allowed_types)) {
            $errors[] = "Invalid file type. Only PDF, DOC, DOCX, JPG, and PNG are allowed.";
        } elseif ($_FILES['new_assignment_file']['size'] > 10000000) { // 10MB limit
            $errors[] = "File is too large. Maximum size is 10MB.";
        } else {
            // New file is valid, proceed with upload
            $new_file_name = uniqid() . '_' . basename($_FILES['new_assignment_file']['name']);
            $target_file = $upload_dir . $new_file_name;

            if (move_uploaded_file($_FILES['new_assignment_file']['tmp_name'], $target_file)) {
                // If a new file is successfully uploaded, delete the old one
                if (!empty($material['file_path']) && file_exists($material['file_path'])) {
                    @unlink($material['file_path']);
                }
                // Update file path and type for the database query
                $file_path = $target_file;
                $file_type = $new_file_type;
            } else {
                $errors[] = "There was an error uploading your new file.";
            }
        }
    }


    if (empty($title)) $errors[] = "Title cannot be empty.";

    if (empty($errors)) {
        try {
            $sql = "UPDATE assignments SET title = ?, instructions = ?, due_date = ?, file_path = ?, file_type = ? WHERE id = ? AND teacher_id = ?";
            $pdo->prepare($sql)->execute([$title, $instructions, $due_date, $file_path, $file_type, $assignment_id, $teacher_id]);
            $success_message = "Material updated successfully!";
            // Re-fetch data to show the changes
            $stmt->execute([$assignment_id, $teacher_id]);
            $material = $stmt->fetch();
        } catch (PDOException $e) {
            $errors[] = "Could not update material.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Material - Teacher Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f9ff; }
        .font-brand { font-family: 'Baloo 2', cursive; }
    </style>
</head>
<body class="min-h-screen">
    <div class="max-w-4xl mx-auto py-8 px-4">
        <div class="mb-4">
            <a href="my_materials.php" class="flex items-center text-teal-600 hover:text-teal-800 font-medium">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                Back to My Materials
            </a>
        </div>
        <div class="bg-white p-8 rounded-lg shadow-lg">
             <h1 class="text-2xl font-bold text-gray-800 mb-6 font-brand">Edit Material</h1>
             <?php if ($success_message): ?><div class="p-4 mb-4 text-sm text-green-700 bg-green-100 rounded-lg"><?php echo e($success_message); ?></div><?php endif; ?>
             <?php if (!empty($errors)): ?><div class="p-4 mb-4 text-sm text-red-700 bg-red-100 rounded-lg"><ul class="list-disc list-inside"><?php foreach($errors as $e) echo "<li>" . e($e) . "</li>"; ?></ul></div><?php endif; ?>

             <form action="edit_material.php?id=<?php echo $assignment_id; ?>" method="POST" enctype="multipart/form-data" class="space-y-6">
                <div>
                    <label for="title" class="block text-sm font-medium text-gray-700">Title / Headline</label>
                    <input type="text" name="title" id="title" value="<?php echo e($material['title']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                </div>
                <div>
                    <label for="instructions" class="block text-sm font-medium text-gray-700">Instructions / Description</label>
                    <textarea name="instructions" id="instructions" rows="8" class="mt-1 block w-full p-2 border border-gray-300 rounded-md"><?php echo e($material['instructions']); ?></textarea>
                </div>
                <div>
                    <label for="due_date" class="block text-sm font-medium text-gray-700">Due Date</label>
                    <input type="datetime-local" name="due_date" id="due_date" value="<?php echo !empty($material['due_date']) ? date('Y-m-d\TH:i', strtotime($material['due_date'])) : ''; ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="new_assignment_file" class="block text-sm font-medium text-gray-700">Upload New File (Optional)</label>
                    <p class="text-xs text-gray-500 mb-2">If you upload a new file, it will replace the old one.</p>
                    <input type="file" name="new_assignment_file" id="new_assignment_file" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:font-semibold file:bg-sky-50 file:text-sky-700 hover:file:bg-sky-100">
                     <?php if(!empty($material['file_path'])): ?>
                        <p class="text-sm text-gray-600 mt-2">
                            Current file: 
                            <a href="../<?php echo e($material['file_path']); ?>" download class="font-medium text-blue-600 hover:underline"><?php echo basename($material['file_path']); ?></a>
                        </p>
                    <?php endif; ?>
                </div>

                 <div class="flex justify-end pt-4 border-t">
                    <a href="my_materials.php" class="px-6 py-2 text-gray-600 font-medium rounded-lg hover:bg-gray-100 mr-4">Cancel</a>
                    <button type="submit" name="update_material" class="px-6 py-2 bg-teal-600 text-white font-semibold rounded-lg shadow hover:bg-teal-700">Save Changes</button>
                </div>
             </form>
        </div>
    </div>
</body>
</html>
