<?php
/**
 * phpaga
 *
 * View/edit operation
 *
 * View or edit an operation
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: operation.php 684 2006-03-23 21:33:38Z worf $
 *
 * Copyright (c) 2002, Florian Lanthaler <florian@phpaga.net>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *
 *    * Neither the name of Florian Lanthaler nor the names of his
 *      contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

include_once("./config.php");

$result = PHPAGA_ERR_NONE;
$status = "";
$ref = "";
$ref_del = "";
$userInfo = array();
$count = 0;

/* if we were invoked by post, we have to save the modifications */
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    $action = ACTION_NONE;

    $opInfo["op_id"] = $_POST["op_id"];
    $opInfo["prj_id"] = $_POST["prj_id"];
    $opInfo["pe_id"] = $_POST["pe_id"];
    $opInfo["opcat_id"] = $_POST["opcat_id"];
    $opInfo["op_desc"] = $_POST["op_desc"];

    if (isset($_REQUEST["op_billabletype"]) && ($_REQUEST["op_billabletype"] == 0)) {

        $opInfo["op_billabletype"] = 0;
        $opInfo["billable_checked"] = true;
    } else {
        $opInfo["op_billabletype"] = 10;
        $opInfo["billable_checked"] = false;
    }

    $opInfo["op_duration"] = $_POST["op_duration"];

	/* if the duration is numeric, convert it from fractional hours into hours:minutes */

	if (is_numeric($opInfo["op_duration"]))
	{
	// Under 24 - assume the duration was given in hours
		if ($opInfo["op_duration"] < 24)
			$opInfo["op_duration"] = (int)$opInfo["op_duration"].':'.sprintf('%02d', 60 * ($opInfo["op_duration"] - (int)$opInfo["op_duration"]));
	// More than 60 minutes, different calculation
		elseif ($opInfo["op_duration"] >= 60)
			$opInfo["op_duration"] = (int)($opInfo["op_duration"] / 60).':'.sprintf('%02d', $opInfo["op_duration"] % 60);
	// duration given in minutes
		else
			$opInfo["op_duration"] = '0:'.(int)$opInfo["op_duration"];
	}

	/* if there is a valid start date and time then convert it to a timestamp */

    $opInfo["op_startdate"] = $_POST["op_startdate"];
    $opInfo["op_starthours"] = $_POST["op_starthours"];

    $start_tmp = "";

    if ($opInfo["op_startdate"] != "")
    {
        $start_tmp = $opInfo["op_startdate"];

        if ($opInfo["op_starthours"] != "")
            $start_tmp .= " ".$opInfo["op_starthours"];

        $opInfo["op_timestamp_start"] = strtotime($start_tmp);
    }
    else
    {
        $opInfo["op_timestamp_start"] = "";
    }

    /* if there is a valid end date and time then convert it to a timestamp */

    $opInfo["op_enddate"]  = $_POST["op_enddate"];
    $opInfo["op_endhours"] = $_POST["op_endhours"];

    $end_tmp = "";

    if ($opInfo["op_enddate"] != "")
    {
        $end_tmp = $opInfo["op_enddate"];

        if ($opInfo["op_endhours"] != "")
            $end_tmp .= " ".$opInfo["op_endhours"];

        $opInfo["op_timestamp_end"] = strtotime($end_tmp);
    }
    else
        $opInfo["op_timestamp_end"] = "";


    /* check if operation data is valid and update the operation */

    $result = phpaga_operations_validdata($opInfo);

    if (count($result) > 0)
    {
        $status = phpaga_returnerror($result);
    }
    else
    {

        $edit_result = phpaga_operations_update($opInfo);

        if ($edit_result != PHPAGA_ERR_NONE)
            $status = phpaga_returnerror($edit_result);
        else
            $status =
                phpaga_returnmessage(_("Information"),
                                     _("The task has been updated successfully."));
    }
}
else
{
    /* first invocation */

    if (isset($_GET["action"]) && is_numeric($_GET["action"]))
        $action = $_GET["action"];
    else
        $action = ACTION_NONE;

    if (isset($_GET["id"]) && is_numeric($_GET["id"]))
        $op_id = $_GET["id"];
    else
        $op_id = "";

    /* where did we come from? that's where will be going to. */
    if (isset($_GET["ref"]) && strlen($_GET["ref"]) > 0)
        $ref = rawurldecode($_GET["ref"])."?";
    else
        $ref = "operation.php?";

    /* build referrer options array */
    if (isset($_GET["refop"]) && strlen($_GET["refop"]) > 0)
        $ref .= str_replace("|", "&", rawurldecode($_GET["refop"]));

    $ref_del = $ref."&op_id=$op_id&action=".ACTION_OP_REMOVE;

    $result = phpaga_operations_getInfo($op_id, $opInfo);
    if (phpaga_errorhappened($result))
        $status = phpaga_returnerror($result);
}

/* don't show the full header when just displaying operation info (view) */

switch ($action)
{

    case ACTION_OP_VIEW:
        $menu = false;
        break;

    default:
        $menu = true;
        phpaga_operations_getCategoryList($select_opcat);
        phpaga_arrayAddOption($select_opcat, PHPAGA_OPTION_ALL);
        break;
}

phpaga_header(array("menu" => $menu,
                    "calendar" => true));

phpaga_projects_getInfo($opInfo["prj_id"], $prjInfo);
phpaga_projects_getDuration($prjInfo["prj_id"], $duration);

switch ($action)
{
    case ACTION_OP_VIEW:

        /* view the task's details */
        $tpl = new psmarty;
        $tpl->assign("prjInfo", $prjInfo);
        $tpl->assign("opInfo", $opInfo);
        $tpl->display("view_operation.tpl.html");
        break;

    default:

        /* edit the task's details */

        if (isset($opInfo["op_billabletype"]) && ($opInfo["op_billabletype"] != 10))
            $opInfo["billable_checked"] = true;
        else
            $opInfo["billable_checked"] = false;

        $is_owner_or_manager = ((($prjInfo["pe_id"] == $_SESSION["auth_user"]["pe_id"])
                                 && phpaga_user_hasperm(PHPAGA_PERM_MANAGE_PROJECTS))
                                || phpaga_user_hasperm(PHPAGA_PERM_MANAGE_OTHERPROJECTS));

        /* only the project owner and general project managers or the
         * task's owner can change this task's data
         */

        if (!$is_owner_or_manager && ($opInfo["pe_id"] != $_SESSION["auth_user"]["pe_id"]))
            phpaga_error(_("You are not the owner of this task, and you do not have the required permissions to change other people's tasks."));
        else
        {

            /* only the project owner and general project managers can
             * set an operation's user
             */

            if (!$is_owner_or_manager)
            {
                $result = phpaga_persons_getInfo($_SESSION["auth_user"]["pe_id"],
                                                 $peInfo);

                $select_user[$peInfo["pe_id"]] = $peInfo["pe_person"]
                    ." (".$_SESSION["auth_user"]["usr_login"].")";
            }
            else
            {

                $userInfo["prj_id"] = $opInfo["prj_id"];
                $result = phpaga_user_search($users, $userInfo);

                foreach ($users as $u)
                    $select_user[$u["pe_id"]] = $u["pe_name"]." (".$u["usr_login"].")";
            }

            $tpl = new psmarty;
            $tpl->assign("PRJ_OPERATION", _("Edit task"));
            $tpl->assign("FORM_ACTION", basename($_SERVER["PHP_SELF"]));
            $tpl->assign("prjInfo", $prjInfo);
            $tpl->assign("opInfo", $opInfo);
            $tpl->assign("STATUSMSG", $status);
            $tpl->assign("HOURS_SO_FAR", $duration);
            $tpl->assign("select_person", $select_user);
            $tpl->assign("select_opcat", $select_opcat);
            $tpl->display("edit_operation.tpl.html");
            break;
        }

}

phpaga_footer();

?>
