<?php

require "../header.php";

define("FAILED", true);

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

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($_REQUEST["id"]) || !isset($_REQUEST['filename']) || !isset($_REQUEST['enabled']) ) {
   sendResponse(FAILED, "Invalid Request");
}

$id = intval($_REQUEST["id"]);
if ( $id <= 0 ) sendResponse(FAILED, "Invalid Image Reference");
$image = new MTGImage($id);
if ( $image->getId() == 0 ) sendResponse(FAILED, "Unknown Image Reference");

$filename = $_REQUEST["filename"] . "." . $image->getFileExtension();
$data["newname"] = $filename;
if ( $filename != $image->getFileName() ) {
   $renamed = $image->renameImage($filename);
   if ( !$renamed ) {
      $conflict = MTGImage::getImageByFileName($filename);
      $data["conflict"] = $conflict;
      if ( $conflict === false ) {
         sendResponse(FAILED, "Invalid New File name");
      } else {
         sendResponse(FAILED, "New File Name Conflict");
      }
   }
}

$image->setEnabled(($_REQUEST["enabled"] == "1") ? true : false);
$image->save();
$data["image"] = $image;

sendResponse();

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