<?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($_FILES['imageFile'])) {
    $userId = $_SESSION['user_id'] ?? 0;
    $username = $_SESSION['username'] ?? 'Unknown';

    $target_dir = __DIR__ . "/galeria/";
    $original_filename = basename($_FILES["imageFile"]["name"]);
    $target_file = $target_dir . $original_filename;
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["imageFile"]["tmp_name"]);
    if($check === false) {
        log_activity($userId, 'Image Upload Failed', 'User ' . $username . ' attempted to upload invalid file: ' . $original_filename);
        header('Location: gallery.php?error=invalid_file');
        exit();
    }

    // Check file size (e.g., 5MB limit)
    if ($_FILES["imageFile"]["size"] > 5000000) {
        log_activity($userId, 'Image Upload Failed', 'User ' . $username . ' attempted to upload too large file: ' . $original_filename);
        header('Location: gallery.php?error=file_too_large');
        exit();
    }

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        log_activity($userId, 'Image Upload Failed', 'User ' . $username . ' attempted to upload invalid format: ' . $original_filename);
        header('Location: gallery.php?error=invalid_format');
        exit();
    }

    // Try to upload file
    if (move_uploaded_file($_FILES["imageFile"]["tmp_name"], $target_file)) {
        log_activity($userId, 'Image Uploaded', 'User ' . $username . ' uploaded image: ' . $original_filename);
        header('Location: gallery.php?success=upload');
    } else {
        log_activity($userId, 'Image Upload Failed', 'User ' . $username . ' failed to upload image: ' . $original_filename);
        header('Location: gallery.php?error=upload_failed');
    }
} else {
    header('Location: gallery.php');
}
?>