<?php
/**
 * Phoebe pedagogic planner
 *
 * PHP version 5
 *
 * LICENSE: The GNU General Public License (GPL), version 2. See LICENSE.txt
 *
 * Copyright (c) 2006-2008 JISC/HEFCE/University of Oxford
 *
 * @author      David Balch <david.balch@conted.ox.ac.uk>
 * @license     http://opensource.org/licenses/gpl-license.php GPL2
 * @link        http://phoebe-project.conted.ox.ac.uk/
 */

$content['settings'] = 'dbWrite';
include_once($_SERVER['DOCUMENT_ROOT'].'/inc/core.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/inc/session.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/inc/utils.php');

// Construct page
$content['main'] = '<h1 id="mainTitle"><a href="/" class="titleLink">Phoebe</a></h1>';
$content['main'] .= $topNav;

if($_GET['isTemplate'] == 1) {
    $content['windowTitle'] = 'Clone a template | Phoebe — pedagogic planner';
    $content['main'] .= '<h2>Clone a template</h2>';
} else {
    $content['windowTitle'] = 'Create a new design | Phoebe — pedagogic planner';
    $content['main'] .= '<h2>Create a new design</h2>';
}

//$content['main'] .= '<p id="quickDesc">Do design management here...</p>';

if($_SERVER['REQUEST_METHOD'] == 'GET') {
    // Get request could be clone existing or new from scratch
    if(isset($_GET['clone']) && ctype_digit($_GET['clone'])) {
        $cloneId = $_GET['clone'];
    }
    if(ctype_digit($_GET['isTemplate'])) {
        $isTemplate = $_GET['isTemplate'];
    } else {
        $isTemplate = 0;
    }
} else if(isset($_FILES['designFileUpload'])) {
    // Import design from file
    $_POST['is_template'] = 1;
    $importResult = importDesignFile($_FILES['designFileUpload']['tmp_name']);

    if($importResult !== true) {
        $content['main'] .= "<p>Could not import design from file: ".importResult."</p>";
    }

} else {
    // Clone design/template from exsisting
    if (ctype_digit($_POST['cloneId'])) {
        $cloneId = $_POST['cloneId'];
    }

    // Sanitize
    foreach($_POST as $name=>$val) {
        $html[$name] = htmlspecialchars($val);
    }

    if($_POST["title"] == '') {
        $content['main'] .= '<p> The field "Design title" is required.';
    } else {
        // Insert data into the database
        include_once($_SERVER['DOCUMENT_ROOT'].'/db/addFuncts.php');
        $newDesignId = addDesign($_POST);
        if ($cloneId) {
            // Clone all the properties and references into the new design
            include($_SERVER['DOCUMENT_ROOT'].'/db/getDesign.php');
            // Copy the original properties into a new array
            $newDesignArray = getDesignArray($cloneId);
            $newDesignArray = $newDesignArray['children'];

            $propIdUpdates = array();

            foreach($newDesignArray as &$value) {
                // Clone all properties
                //$content['main'] .= $key." ".$value;
                cloneProp($value);
            }

            //$content['main'] .= tableFromArray($propIdUpdates);

            foreach($newDesignArray as &$value) {
                // After all properties have been cloned, update them with the new id relationships
                //$content['main'] .= $key." ".$value;
                updatePropRelations($value);
            }
        }
    }
}

function cloneProp(&$theProp) {
    // Clone all the properties and references into the new design
    global $content, $newDesignId, $propIdUpdates;

    //$content['main'] .= '<hr/>[['.tableFromArray($propIdUpdates).']]';

    // Skip any redundant nesting
    if(!array_key_exists('prop_id', $theProp)) {
        $theProp = $theProp[0];
    }
    //$content['main'] .= tableFromArray($theProp, false);

    // Record old id
    $theProp['old_prop_id'] = $theProp['prop_id'];

    // Update basic values
    unset($theProp['prop_id']);
    $theProp['parent_design_id'] = $newDesignId;
    // Remove field data if unwanted.
    if($_POST['copyData'] != 'on') {
        $theProp['value'] = '';
    }

    // Add to prop to database
    //print_r($theProp);
    $newPropId = addprop($theProp);
    $theProp['prop_id'] = $newPropId;

    // Store the new id in the reference array
    $propIdUpdates[$theProp['old_prop_id']] = $newPropId;

    // Add references
    $propRefs = &$theProp['references'];
    if (sizeof($propRefs)) {
        foreach ($propRefs as &$value) {
            $vals = array('parent_design_id' => $newDesignId,
                          'parent_property_id' => $newPropId,
                          'type' => $value['type'],
                          'uri' => $value['uri']
                          );
            addRef($vals);
        }
    }

    // Debugging
    //$content['main'] .= tableFromArray($theProp, false);

    // Recurse through children
    $propChildren = &$theProp['children'];
    if (sizeof($propChildren)) {
        foreach ($propChildren as &$value) {
            cloneProp($value);
        }
    }
}

function updatePropRelations(&$theProp) {
    // Update ids: parent_id, first_child_id, next_sibling_id
    global $mdb2, $content, $propIdUpdates;

    // Skip any redundant nesting
    if(!array_key_exists('prop_id', $theProp)) {
        $theProp = $theProp[0];
    }

    /*
    $content['main'] .= "<hr/>";
    $content['main'] .= "<hr/><table><tr><td>";
    $content['main'] .= tableFromArray($theProp, false);
    $content['main'] .= "</td><td>";
   */

    // parent_id
    if (array_key_exists($theProp['parent_id'], $propIdUpdates)) {
        $theProp['parent_id'] = $propIdUpdates[$theProp['parent_id']];
    }

    // first_child_id
    if (array_key_exists($theProp['first_child_id'], $propIdUpdates)) {
        $theProp['first_child_id'] = $propIdUpdates[$theProp['first_child_id']];
    }

    // next_sibling_id
    if (array_key_exists($theProp['next_sibling_id'], $propIdUpdates)) {
        $theProp['next_sibling_id'] = $propIdUpdates[$theProp['next_sibling_id']];
    }

    /*
    $content['main'] .= tableFromArray($theProp, false);
    $content['main'] .= "</td></tr></table>";
    */

    // Update database
    $sql = 'UPDATE properties '.
           'SET first_child_id = '.$mdb2->quote($theProp['first_child_id']).','.
           ' next_sibling_id = '.$mdb2->quote($theProp['next_sibling_id']).' '.
           'WHERE prop_id = '.$mdb2->quote($theProp['prop_id']);
    //$content['main'] .= $sql.'<br/>';

    $update = $mdb2->exec($sql);
    if (PEAR::isError($update)) {
        $content['main'] .= 'Error saving update - '.$update->getMessage();
    }

    // Recurse through children
    $propChildren = $theProp['children'];
    if (sizeof($propChildren)) {
        foreach ($propChildren as &$value) {
            updatePropRelations($value);
        }
    }
}

if ($cloneId) {
    // Get info of design to clone from
    $desId = $mdb2->quote($cloneId);
    $sql = 'SELECT * FROM designs '.
           'WHERE design_id = '.$desId;
    //echo $sql.'<br>';

    $design = $mdb2->queryRow($sql);
    if (PEAR::isError($design)) {
        $error = $design->getMessage();
    } elseif ($design['share_level' == 0] ) {
        $error = "Sorry, you cannot copy that design, as it's owner has not shared it.";
    } else {
        $clone = true;
    }
}

if($design['is_template'] && !$_GET['newFromTemplate']) {
    $desOrTemp = 'template';
} else  {
    $desOrTemp = 'design';
}

if (ctype_digit($newDesignId)) {
    // Design inserted, go edit it.
    if (false) {//$CNF->debug) {
        $content['main'] .= '<p>New '.$desOrTemp.' <i>'.$html["title"]."</i> added.</p>\n";
        $content['main'] .= '<ul>';
        $content['main'] .= ' <li><a href="editDesign.php?design_id='.$newDesignId.'">Edit your '.$desOrTemp.' <i>'.$html["title"].'</i> <img src="/inc/img/edit.gif" alt="Edit" title="Click to edit this '.$desOrTemp.'" height="16" width="16"></a></li>';
        $content['main'] .= ' <li><a href="editDesignStructure.php?design)id='.$newDesignId.'">Edit this '.$desOrTemp.'<img src="/inc/img/spanner.gif" alt="Edit this template" title="Edit this template" height="16" width="16"></a></li>';
        $content['main'] .= '</ul>';
        $content['main'] .= '<p>Return to <a href="/designs.php">your designs</a>.</p>';
    } else {
        if ($_POST['is_template'] == 1) {
            header('Location: /editDesignStructure.php?design_id='.$newDesignId);
        } else  {
            header('Location: /editDesign.php?design_id='.$newDesignId);
        }
    }

} else {
    // Present design creation form
    if ($clone && $isTemplate) {
        $content['main'] .= '<p>Creating a new template based on "'.$design['title'].'".</p>';
    } else if ($clone) {
        $content['main'] .= '<p>Creating a new '.$desOrTemp.' based on "'.$design['title'].'".</p>';
    }

    // Display design creation form
    $designForm = '<form action ="" method="POST" class="bigFields">';
    $designForm .= '<fieldset><legend>New '.$desOrTemp.' information</legend><dl>';
    $designForm .= '<dt><label for="title">Title (required)</label></dt>
                    <dd><input name="title" id="title" type="text" size="64" value="'.$html["title"].'" /> </dd>';
    $designForm .= '<dt><label for="description">Description</label></dt>
                    <dd><textarea name="description" id="description" rows="4" cols="65" class="fullWidth">';
    if ($html["description"]) {
        $designForm .= $html["description"];
    } elseif ($clone) {
        $designForm .= 'Cloned from "'.$design['title'].'".';
    }
    $designForm .= '</textarea></dd>';
    if ($clone) {
        $designForm .= '<dt><label for="copyData">Copy information</label></dt>
                        <dd><input type="checkbox" name="copyData" id="copyData" checked="checked"> Copy any information already in the template to your new design. (Deselect this box if you want to create a blank '.$desOrTemp.'.)
                        <input name="is_template" value="'.$isTemplate.'" type="hidden" />
                        <input name="cloneId" value="'.$cloneId.'" type="hidden" /></dd>';
    }

    $designForm .= '</dl></fieldset>';
    $designForm .= '<div class="formButtons"><input value="Create '.$desOrTemp.'" type="submit" /></div>';
    $designForm .= '</form>';

    $content['main'] .= $designForm;
}

// Write via template
include_once($CNF->template);
?> 