<?php

require "../header.php";

function sendResponse() {
    global $data;
    header('Content-Type: application/json');
    echo json_encode($data);
    exit();
}

$second = false;
if ( isset($_REQUEST["second"]) && ($_REQUEST["second"] == "true") ) $second = true;
$initialcard = false;
if ( isset($_REQUEST["initialcard"]) && ($_REQUEST["initialcard"] == "true") ) $initialcard = true;
$skip = false;
if ( isset($_REQUEST["skip"]) && ($_REQUEST["skip"] == "true") ) $skip = true;
$reverse = false;
if ( isset($_REQUEST["reverse"]) && ($_REQUEST["reverse"] == "true") ) $reverse = true;

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

if ( $reverse ) {
    if ( $_SESSION['cardcount'] > $_SESSION['startcount'] ) {
        $_SESSION['cardcount']--;
        $reverse_cards = array_pop($_SESSION["cardlist"]);
        $reverse_cards[array_key_last($reverse_cards)]->setPlayed(false);
        $reverse_cards[array_key_last($reverse_cards)]->save(false);
    } else {
    }
    $data['cards'] = $_SESSION['cardlist'][array_key_last($_SESSION['cardlist'])];
    $data['cardcount'] = $_SESSION['cardcount'];
    sendResponse();
}

$previous_cards = (count($_SESSION['cardlist']) > 0) ? $_SESSION['cardlist'][array_key_last($_SESSION['cardlist'])] : [];

if ( $second ) {
    $random_image = MTGImage::getRandomImage($previous_cards[0]->getFileName());
} else {
    $random_image = MTGImage::getRandomImage();
}
if ( $random_image === false ) {
    $data["error"] = true;
    $data["message"] = "Error retrieving filename from database";
    sendResponse();
}

$new_cards = [];
if ( $second ) {
    $new_cards[] = $previous_cards[0];
}
$new_cards[] = $random_image;
$_SESSION['cardlist'][] = $new_cards;
$data['cards'] = $new_cards;

if ( !$skip && !$initialcard ) $_SESSION['cardcount']++;
if ( !$skip ) {
    $random_image->setPlayed(true);
    $random_image->save();
}
$data['cardcount'] = $_SESSION['cardcount'];

sendResponse();

// vim: sw=4 ts=4:
