<?php
/**
 * ===================================================================================
 * Edit Private File Page (with File Upload)
 * ===================================================================================
 *
 * File: edit_private_file.php
 * Location: /homework_portal/teacher/edit_private_file.php
 *
 * Purpose:
 * 1. Allows a teacher to edit the title, notes, and replace the file for a private record.
 * 2. Ensures the teacher has permission to edit the file.
 */

require_once '../config.php';

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

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

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

// --- Fetch existing file data (with ownership check) ---
try {
    $stmt = $pdo->prepare("SELECT pf.*, s.full_name as student_name FROM student_private_files pf JOIN students s ON pf.student_id = s.id WHERE pf.id = ? AND pf.teacher_id = ?");
    $stmt->execute([$file_id, $teacher_id]);
    $file_data = $stmt->fetch();
    if (!$file_data) {
        header('Location: manage_students.php?error=File not found or permission denied.');
        exit();
    }
} catch (PDOException $e) {
    die("Database error fetching file data.");
}

// --- Handle Form Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_file'])) {
    $title = trim($_POST['title'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    
    // Keep the existing file path unless a new one is uploaded
    $new_file_path = $file_data['file_path'];

    if (empty($title)) {
        $errors[] = "Title is required.";
    }

    // --- Handle New File Upload ---
    if (isset($_FILES['new_private_file']) && $_FILES['new_private_file']['error'] == UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/private_files/';
        
        $new_file_name = "student_{$file_data['student_id']}_" . uniqid() . '_' . basename($_FILES['new_private_file']['name']);
        $target_file = $upload_dir . $new_file_name;

        // Add validation here if desired (file type, size)
        
        if (move_uploaded_file($_FILES['new_private_file']['tmp_name'], $target_file)) {
            // New file uploaded successfully, delete the old one
            if (!empty($file_data['file_path']) && file_exists($file_data['file_path'])) {
                @unlink($file_data['file_path']);
            }
            $new_file_path = $target_file; // Set the new path for the database update
        } else {
            $errors[] = "There was an error uploading the new file.";
        }
    }

    if (empty($errors)) {
        try {
            $sql = "UPDATE student_private_files SET title = ?, notes = ?, file_path = ? WHERE id = ? AND teacher_id = ?";
            $pdo->prepare($sql)->execute([$title, $notes, $new_file_path, $file_id, $teacher_id]);
            $success_message = "File details updated successfully!";
            // Re-fetch data to show the changes
            $stmt->execute([$file_id, $teacher_id]);
            $file_data = $stmt->fetch();
        } catch (PDOException $e) {
            $errors[] = "Could not update file details.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Private File - 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-2xl mx-auto py-8 px-4">
        <div class="mb-4">
            <a href="view_student_files.php?id=<?php echo e($file_data['student_id']); ?>" 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 <?php echo e($file_data['student_name']); ?>'s Files
            </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 File Details</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</li>"; ?></ul></div><?php endif; ?>

            <form action="edit_private_file.php?id=<?php echo $file_id; ?>" method="POST" enctype="multipart/form-data" class="space-y-6">
                 <div>
                    <label for="title" class="block text-sm font-medium text-gray-700">File Title</label>
                    <input type="text" name="title" id="title" value="<?php echo e($file_data['title']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                </div>
                 <div>
                    <label for="notes" class="block text-sm font-medium text-gray-700">Notes (Optional)</label>
                    <textarea name="notes" id="notes" rows="4" class="mt-1 block w-full p-2 border border-gray-300 rounded-md"><?php echo e($file_data['notes']); ?></textarea>
                </div>
                <div>
                    <label for="new_private_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 <strong class="text-red-500">replace</strong> the old one.</p>
                    <input type="file" name="new_private_file" id="new_private_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">
                    <p class="text-sm text-gray-600 mt-2">
                        Current file: 
                        <a href="../<?php echo e($file_data['file_path']); ?>" download class="font-medium text-blue-600 hover:underline"><?php echo basename($file_data['file_path']); ?></a>
                    </p>
                </div>
                <div class="flex justify-end pt-4 border-t">
                    <a href="view_student_files.php?id=<?php echo e($file_data['student_id']); ?>" 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_file" 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>
