<?php
require_once __DIR__ . '/includes/session_check.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/activity_logger.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['old_filename'], $_POST['new_filename'])) {
    $userId = $_SESSION['user_id'] ?? 0;
    $username = $_SESSION['username'] ?? 'Unknown';

    $gallery_dir = __DIR__ . '/galeria/';
    
    // Sanitize filenames to prevent directory traversal attacks
    $old_filename = basename($_POST['old_filename']);
    $new_filename_raw = basename($_POST['new_filename']);

    // Check for empty new filename
    if (empty($new_filename_raw)) {
        log_activity($userId, 'Image Rename Failed', 'User ' . $username . ' attempted to rename ' . $old_filename . ' to empty name.');
        header('Location: gallery.php?error=empty_name');
        exit();
    }

    // Preserve the file extension
    $old_extension = pathinfo($old_filename, PATHINFO_EXTENSION);
    $new_filename_without_ext = pathinfo($new_filename_raw, PATHINFO_FILENAME);
    $new_filename_with_ext = $new_filename_without_ext . '.' . $old_extension;

    $old_filepath = $gallery_dir . $old_filename;
    $new_filepath = $gallery_dir . $new_filename_with_ext;

    // Check if the old file exists and the new name isn't already taken
    if (!file_exists($old_filepath)) {
        log_activity($userId, 'Image Rename Failed', 'User ' . $username . ' attempted to rename non-existent file: ' . $old_filename);
        header('Location: gallery.php?error=not_found');
        exit();
    }
    if (file_exists($new_filepath)) {
        log_activity($userId, 'Image Rename Failed', 'User ' . $username . ' attempted to rename ' . $old_filename . ' to existing name: ' . $new_filename_with_ext);
        header('Location: gallery.php?error=name_exists');
        exit();
    }

    // Attempt to rename
    if (rename($old_filepath, $new_filepath)) {
        log_activity($userId, 'Image Renamed', 'User ' . $username . ' renamed image from ' . $old_filename . ' to ' . $new_filename_with_ext);
        header('Location: gallery.php?success=renamed');
    } else {
        log_activity($userId, 'Image Rename Failed', 'User ' . $username . ' failed to rename image from ' . $old_filename . ' to ' . $new_filename_with_ext);
        header('Location: gallery.php?error=rename_failed');
    }
} else {
    header('Location: gallery.php');
}
?>