<?php
require_once __DIR__ . "/functions.php";
middlewareAuthorized("admin");

function error_redirect($message) {
    $error = urlencode($message);
    header("Location: new_photo.php?error=$error");
    exit;
}

$is_file_uploaded = isset($_FILES['file']) && !empty($_FILES['file']['tmp_name']);
$category = $_POST['category_id'] ?? '';
$description = $_POST['description'] ?? '';

if(empty($category) || empty($description)) {
    error_redirect("Description or category empty");
}
$category = intval($category);

if(!$is_file_uploaded)
    error_redirect("File is not uploaded");

$tmpPath = $_FILES['file']['tmp_name'];
$imageType = exif_imagetype($tmpPath);
if($imageType !== IMAGETYPE_PNG)
    error_redirect("File is not png format");

$path = upload_file($_FILES['file'], "photos/");
insertPhoto($_SESSION['id_user'], $category, $path, $description);
header("Location: new_photo.php?success=true");