<?php

require_once 'config.php';
require_once 'GeocodingHelper.php';
require_once 'XNC/Form.php';

$header = "Add a ".Config::$subjectDescription;

if (! XN_Profile::current()->isLoggedIn()) {
    $message = 'Sorry, you\'re not signed in! Please sign in to add a ' . Config::$subjectDescription . '.';
    include 'html/confirm.php';
    exit();
}

if (isset($_GET['id'])) {
    $content = XN_Content::load($_GET['id']);
    $defaults = ModelHelper::getDefaultsFromContent(new Config::$subjectType(), $content);
} else {
    $defaults = array();
}

$form = new XNC_Form($defaults);


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    normalizeState();   
    // Validate both the submitted subject and the submitted review
    if ($errors = array_merge(ModelHelper::validate(Config::$subjectType),
                              ModelHelper::validate(Config::$reviewType))) {
        include 'html/formAdd.php';
    } else {
        $newSubjectID = process();
        if ($newSubjectID !== false) {
            $target = 'subject';
            $targetQueryString = array('SubjectID' => $newSubjectID); 
            include 'html/redirect.php';
        } else {
            $message = 'Sorry! your '.strtolower(Config::$subjectType).' and review were not saved because of an error.';
            include 'html/confirm.php';
        }
    }
} else {
    // uses $form, $errors
    include 'html/formAdd.php';
}

function normalizeState() {
    $_POST[Config::$subjectType.':state'] = strtoupper(trim($_POST[Config::$subjectType.':state'])); 
}

function process() {    
    try {                        
        $subjectShape = new Config::$subjectType();
        $subject = $subjectShape->exists();
        if (! $subject) {
            $subject = XN_Content::create(Config::$subjectType);
        }        
        ModelHelper::processContent($subjectShape, $subject);
        
        $reviewShape = new Config::$reviewType();
        $review = XN_Content::create(Config::$reviewType);
        ModelHelper::processContent($reviewShape, $review);
        
        // And now for calculated values and other stuff not from the form
        $review->isPrivate = true;

        // Save the review so it can be added to the subject
        $review->save();

        // Make the Subject contain the Review
        $subject->my->addContent(Config::$reviewAttribute,$review);
    
        // Update the Subject's rating count and average stats
        $subjectShape->updateStats($subject);
        
        if ($subject->my->latitude && $subject->my->longitude) {
            $subject->my->latitudeAndLongitudeFound = "Y";
        }
        // Save the Subject (necessary after addContent())
        $subject->save();

        // Add tags to the subject
        try {          
            XN_Tag::addTags($subject, $_POST[Config::$subjectType.':_tags']);
        } catch (Exception $e) {
            // @todo Properly deal with the fact that we can't tag existing content
        }
        
        // Everything went OK
        return $subject->id;
    } catch (Exception $e) {
        echo XN_ExceptionHandler($e);
        return false;
    }
}
