<?php
/**
 * phpaga
 *
 * data service
 *
 * Return requested data as JSON
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id$
 *
 * Copyright (c) 2010, 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");

$type = null;
$data = array();
$h_data = array();
$title = null;
$xlabel = null;

$req = isset($REQUEST_DATA["req"]) ? $REQUEST_DATA["req"] : null;

switch($req) {

case "mhrsstatpe":
    if (isset($REQUEST_DATA["pe_id"]) && is_numeric($REQUEST_DATA["pe_id"])) {
        $pe_id = $REQUEST_DATA["pe_id"];
        $mhrs_sumstats = phpaga_persons_getBillableManhoursStats($pe_id);
        if (!PhPagaError::isError($mhrs_sumstats))
            $data = $mhrs_sumstats;
    }
    break;


case "mhrs":
    $opInfo = array('cpn_id' => null,
        'prj_id' => null,
        'pe_id' => null,
        'opcat_id' => null,
        'bill_id' => null,
        'op_startdatefrom' => date("Y-m-d"));

    if (isset($REQUEST_DATA["cpn_id"]) && is_numeric($REQUEST_DATA["cpn_id"]))
        $opInfo["cpn_id"] = $REQUEST_DATA["cpn_id"];

    if (isset($REQUEST_DATA["prj_id"]) && is_numeric($REQUEST_DATA["prj_id"]))
        $opInfo["prj_id"] = $REQUEST_DATA["prj_id"];

    if (isset($REQUEST_DATA["pe_id"]) && is_numeric($REQUEST_DATA["pe_id"]))
        $opInfo["pe_id"] = $REQUEST_DATA["pe_id"];

    if (isset($REQUEST_DATA["opcat_id"]) && is_numeric($REQUEST_DATA["opcat_id"]))
        $opInfo["opcat_id"] = $REQUEST_DATA["opcat_id"];

    if (isset($REQUEST_DATA["bill_id"]) && is_numeric($REQUEST_DATA["bill_id"]))
        $opInfo["bill_id"] = $REQUEST_DATA["bill_id"];

    if (isset($REQUEST_DATA["date"]) && strlen($REQUEST_DATA["date"]))
        $opInfo["op_startdatefrom"] = $REQUEST_DATA["date"];

    if (isset($REQUEST_DATA["type"]) && ($REQUEST_DATA["type"] == PHPAGA_MANHOURS_DISPLAY_YEAR)) {
        $title = _('Weekly manhours');
        $xlabel = _('calendar week');
        $type = PHPAGA_MANHOURS_DISPLAY_YEAR;
        for ($i = 1; $i <= 53; $i++)
            $h_data[$i] = 0;

    } else {
        $title = _('Daily manhours').': '.phpaga_strftime('%B %Y', strtotime($opInfo["op_startdatefrom"]));
        $xlabel = _('day');
        $type = PHPAGA_MANHOURS_DISPLAY_MONTH;
        for ($i = 1; $i <= date("t", strtotime($opInfo["op_startdatefrom"])); $i++)
            $h_data[date('Y-m-', strtotime($opInfo["op_startdatefrom"])).sprintf("%02s", $i)] = 0;
    }

    $rows = phpaga_operations_getManhours($opInfo, $type);
    if (PhPagaError::isError($rows)) {
        $rows->printMessage();
        exit;
    }

    foreach ($rows as $tmp_stats) {
        if ($type == PHPAGA_MANHOURS_DISPLAY_YEAR) {
            list($h_date,) = preg_split("/ /", $tmp_stats["mhrs_date"]);
            $h_date = (int) $h_date;
        } else
            $h_date = $tmp_stats["mhrs_date"];

        $h_data[$h_date] = (float)$tmp_stats["mhrs_duration"];
    }

    $data = array('ticks' => array_keys($h_data),
        'values' => array_values($h_data),
        'title' => $title,
        'xlabel' => $xlabel
    );

    break;


case "opcat":

    $opInfo = array('cpn_id' => null,
        'prj_id' => null,
        'pe_id' => null,
        'opcat_id' => null,
        'op_desc' => null,
        'op_startdatefrom' => null,
        'op_startdateto' => null);

    if (isset($REQUEST_DATA["cpn_id"]) && is_numeric($REQUEST_DATA["cpn_id"]))
        $opInfo["cpn_id"] = $REQUEST_DATA["cpn_id"];

    if (isset($REQUEST_DATA["prj_id"]) && is_numeric($REQUEST_DATA["prj_id"]))
        $opInfo["prj_id"] = $REQUEST_DATA["prj_id"];

    if (isset($REQUEST_DATA["pe_id"]) && is_numeric($REQUEST_DATA["pe_id"]))
        $opInfo["pe_id"] = $REQUEST_DATA["pe_id"];

    if (isset($REQUEST_DATA["opcat_id"]) && is_numeric($REQUEST_DATA["opcat_id"]))
        $opInfo["opcat_id"] = $REQUEST_DATA["opcat_id"];

    if (isset($REQUEST_DATA["op_desc"]) && strlen($REQUEST_DATA["op_desc"]))
        $opInfo["op_desc"] = $REQUEST_DATA["op_desc"];

    if (isset($REQUEST_DATA["op_startdatefrom"]) && strlen($REQUEST_DATA["op_startdatefrom"]))
        $opInfo["op_startdatefrom"] = $REQUEST_DATA["op_startdatefrom"];

    if (isset($REQUEST_DATA["op_startdateto"]) && strlen($REQUEST_DATA["op_startdateto"]))
        $opInfo["op_startdateto"] = $REQUEST_DATA["op_startdateto"];

    $rows = phpaga_operations_getOpcatStats($opInfo, $sum_duration);

    if (PhPagaError::isError($rows))
        $rows->printMessage();
    else {
        foreach ($rows as $t) {
            $h_data[$t["opcat_title"]] = (float)$t["opcat_duration"] / 60.0;
        }
    }

    $data = array('ticks' => array_keys($h_data),
        'values' => array_values($h_data),
        'title' => _('Task categories')
    );
    break;


case "summary":

    $t = array();
    $summary = phpaga_getSummary();
    if (PhPagaError::isError($summary)) {
        $summary->printMessage();
        exit;
    }

    $type = isset($REQUEST_DATA["type"]) ? $REQUEST_DATA["type"]: null;

    switch($type) {

    case "prj":

        $title = _('Manhours per project');
        foreach ($summary["projects"]["rows"] as $t)
            if (isset($t["sum_duration"]) && is_numeric($t["sum_duration"]) && ($t["sum_duration"] > 0))
                $h_data[$t["prj_title"]] = $t["sum_duration"] / 60.0;
        break;

    case "pe":

        $title = _('Persons');
        foreach ($summary["persons"]["rows"] as $t)
            if (isset($t["sum_duration"]) && is_numeric($t["sum_duration"]) && ($t["sum_duration"] > 0))
                $h_data[$t["pe_person"]] = $t["sum_duration"] / 60.0;
        break;

    case "cu":

        if (!isset($REQUEST_DATA["curr_id"]) || !is_numeric($REQUEST_DATA["curr_id"])) {
            phpaga_error(_("Illegal currency"));
            exit;
        }

        if (!isset($summary["customers"][$REQUEST_DATA["curr_id"]])) {
            phpaga_error(_("Unable to fetch data for currency"));
            exit;
        }

        $curr = phpaga_currencies_getCurrencyInfo($REQUEST_DATA["curr_id"]);

        $title = _('Currency').': '.$curr['curr_name'];

        foreach ($summary["customers"][$REQUEST_DATA["curr_id"]]["rows"] as $t)
            if (isset($t["sum_amount"]) && is_numeric($t["sum_amount"]) && ($t["sum_amount"] > 0))
                $h_data[$t["cpn_name"]] = $t["sum_amount"];

        break;

    default:
        break;
    }

    $data = array('ticks' => array_keys($h_data),
        'values' => array_values($h_data),
        'title' => $title
    );

    break;

case "fin_bpc":

    phpaga_user_pageperm(PHPAGA_PERM_VIEW_FINANCE);
    $currency = PHPAGA_DEFAULTCURRENCY;
    $year = date ('Y');

    $title = _('Amounts invoiced per customer');
    if (isset($REQUEST_DATA['year']) && is_numeric($REQUEST_DATA['year']))
        $year = $REQUEST_DATA['year'];

    if (isset ($REQUEST_DATA['currency']) && is_numeric($REQUEST_DATA['currency']))
        $currency = $REQUEST_DATA['currency'];

    $billedPerCompany = phpaga_finances_billedPerCompany($currency, $year);
    if (PhPagaError::isError($billedPerCompany)) {
        $billedPerCompany->printMessage();
        exit;
    }

    $values = array();
    foreach ($billedPerCompany as $bpc) {
        $values[] = array($bpc['cpn_name'], (float)$bpc['amount_src']);
    }

    $data = array('ticks' => null,
        'values' => $values,
        'title' => $title
    );

    break;

case "fin_bprpm":

    phpaga_user_pageperm(PHPAGA_PERM_VIEW_FINANCE);

    $paidPerMonth = array();
    $billedPerMonth = array();
    $missingPerMonth = array();

    $months = array();
    $currInfo = array();
    $year = date ("Y");

    $currency = PHPAGA_DEFAULTCURRENCY;

    if (isset($REQUEST_DATA["year"]) && is_numeric($REQUEST_DATA["year"]))
        $year = $REQUEST_DATA["year"];

    $fy_dates = phpaga_finances_getfiscalyeardates($year);
    $t_month = date("m", strtotime($fy_dates["start"]));

    $oldlocale = setlocale(LC_TIME, 0);
    setlocale(LC_TIME, PHPAGA_LANGNAME);

    for ($i = 1; $i <= 12; $i++) {
        $m = ($i + $t_month -1) % 12;
        if ($m == 0)
            $m = 12;

        $months[$m] = $i;
        $cal_monthNamesShort[$i] = strftime ("%b", mktime (0, 0, 0, $m, 1, 2001));
    }

    setlocale(LC_TIME, $oldlocale);

    if (isset ($_GET["currency"]) && is_numeric ($_GET["currency"]))
        $currency = $_GET["currency"];

    $currInfo = phpaga_currencies_getCurrencyInfo($currency);

    $billedPerMonth = phpaga_finances_billedPerMonth($currency, $year);
    if (PhPagaError::isError($billedPerMonth)) {
        $billedPerMonth->printMessage();
        exit;
    }

    $paidPerMonth = phpaga_finances_paidPerMonth($currency, $year);
    if (PhPagaError::isError($paidPerMonth)) {
        $paidPerMonth->printMessage();
        exit;
    }

    $missingPerMonth = phpaga_finances_missingPerMonth($currency, $year);
    if (PhPagaError::isError($missingPerMonth)) {
        $missingPerMonth->printMessage();
        exit;
    }

    for ($i = 1; $i <= 12; $i++) {
        $idx = $cal_monthNamesShort[$i];
        $months_billed[$idx] = (float)0;
        $months_paid[$idx] = (float)0;
        $months_missing[$idx] = (float)0;
    }

    /* Setting monetary amount for each month */
    foreach ($billedPerMonth as $t)
        $months_billed[$cal_monthNamesShort[$months[$t["month"]]]] = (float)$t["amount"];

    foreach ($paidPerMonth as $t)
        $months_paid[$cal_monthNamesShort[$months[$t["month"]]]] = (float)$t["amount"];

    foreach ($missingPerMonth as $t)
        $months_missing[$cal_monthNamesShort[$months[$t["month"]]]] = (float)$t["amount"];

    $title = sprintf(_("Invoiced / Received / Missing (FY %s)"), $year);
    $series_labels = array(_('Invoiced'),_('Received'),_('Missing'));
    $data = array('ticks' => array_values($cal_monthNamesShort),
        'values' => array(
            array_values($months_billed),
            array_values($months_paid),
            array_values($months_missing),
        ),
        'title' => $title,
        'series_labels' => $series_labels
    );

    break;

default:
    break;
}

header('Content-Type: text/javascript; charset=utf8');
print json_encode($data);
?>
