<?php

require "../header.php";

define("FAILED", true);

$data = array();
$data["error"] = false;
$data["message"] = "";
$data["uploadcount"] = 0;

function sendResponse($error = false, $message = "") {
   global $data;
   $data["error"] = $error;
   if ( $error ) $data["message"] = $message;
   header('Content-Type: application/json');
   echo json_encode($data);
   exit();
}

if ( !$_SESSION["validated"] ) sendResponse(FAILED, "Login Required");

if ( !isset($_POST["goodform"]) ) {
   sendResponse(FAILED, "Invalid Request");
}

$uploadDir = "../images/";

foreach ( $_FILES['images']['name'] as $key => $name ) {
   if ( !($_FILES['images']['error'][$key] == UPLOAD_ERR_OK) ) continue;
   $tempname = $_FILES['images']['tmp_name'][$key];
   $filename = basename($name);
   $destination = $uploadDir . $filename;
   if ( move_uploaded_file($tempname, $destination) ) {
      list($width, $height) = getimagesize($destination);
      $conflict = MTGImage::getImageByFileName($filename);
      if ( $conflict === false ) {
         $data["uploadcount"]++;
         $image = new MTGImage();
         $image->setFileName($filename);
         $image->setWidth($width);
         $image->setHeight($height);
         $image->save();
      }
   }
}

sendResponse();

// vim:ts=3 sw=3 et:
