<?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;
$replace = false;
if ( isset($_REQUEST["replace"]) && ($_REQUEST["replace"] == "true") ) $replace = 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();
}

// If we are replacing a card set the previous card to unplayed,
// set the replacement card to played, then immediately send the response
if ( $replace ) {
    if ( $initialcard ) {
        $data["error"] = true;
        $data["message"] = "Replacement card requested when no card present";
        sendResponse();
    }
    $last_cardlist_index = array_key_last($_SESSION['cardlist']);
    $last_played_index = array_key_last($_SESSION['cardlist'][$last_cardlist_index]);
    $_SESSION['cardlist'][$last_cardlist_index][$last_played_index]->setPlayed(false);
    $_SESSION['cardlist'][$last_cardlist_index][$last_played_index]->save();
    $random_image->setPlayed(true);
    $random_image->save();
    $_SESSION['cardlist'][$last_cardlist_index][$last_played_index] = $random_image;
    $data['cards'] = $_SESSION['cardlist'][$last_cardlist_index];
    $data['cardcount'] = $_SESSION['cardcount'];
    sendResponse();
}

// Always increment the card count unless it's the first card request
if ( !$initialcard ) $_SESSION['cardcount']++;
$data['cardcount'] = $_SESSION['cardcount'];

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

sendResponse();

// vim: sw=4 ts=4:
