<?php
session_start();

$target_dir = __DIR__ . "/uploads/glasses/";
if (!file_exists($target_dir)) {
    mkdir($target_dir, 0777, true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES["glasses_image"])) {
    $file = $_FILES["glasses_image"];
    
    // Check for errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $_SESSION['error'] = "Upload error code: " . $file['error'];
        header("Location: admin.php");
        exit();
    }

    $imageFileType = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
    
    // Allow only PNG
    if ($imageFileType != "png") {
        $_SESSION['error'] = "Sorry, only PNG files are allowed for glasses (needs transparency).";
        header("Location: admin.php");
        exit();
    }
    
    // Check if image file is a actual image or fake image
    $check = getimagesize($file["tmp_name"]);
    if ($check === false) {
        $_SESSION['error'] = "File is not an image.";
        header("Location: admin.php");
        exit();
    }
    
    // Generate unique name
    $new_file_name = uniqid("glass_") . ".png";
    $target_file = $target_dir . $new_file_name;
    
    if (move_uploaded_file($file["tmp_name"], $target_file)) {
        chmod($target_file, 0644);
        $_SESSION['success'] = "The file " . htmlspecialchars(basename($file["name"])) . " has been uploaded.";
    } else {
        $_SESSION['error'] = "Sorry, there was an error uploading your file.";
    }
    
    header("Location: admin.php");
    exit();
} else {
    header("Location: admin.php");
    exit();
}
?>
