<?php
/**
 * cCdvb0100
 *
 * dentalair voorraadbeheer
 *
 * @version    1.0
 * @author     Erik Timmers, amgate <erik.timmers@amgate.com>
 * @copyright  Amgate, 2010
 * @since      06-01-2010 - initial creation
 * @package    CDVB0100
 */

require_once 'class.stdModule.php';
require_once 'cdvb0100/Scanning.php';

define('CDVB_INTVAL_MONTH', 'mn');
define('CDVB_INTVAL_WEEK',  'wk');
define('CDVB_INTVAL_YEAR',  'yr');
define('CDVB_INTVAL_NONESELECTED',  'none');

class cCdvb0100 extends stdModule
{

    /**
     * cCdvb0100
     *
     * PHP4 constructor
     *
     * @access public
     * @return void
     */
    function cCdvb0100 ()
    {
        $this->stdModule('cdvb0100');
        $this->setVariable('modcode', 'cdvb0100');

        $this->oScanning = new cCdvb0100_scanning();
    }

    /**
     * getInkoopProfiles
     *
     * get list of all Inkoopprofileorganisations
     *
     * @access public
     * @param  object   $oI3a       i3a-object
     * @param  boolean  $bKeyValue  return a key=>value pair array or an recordset array
     * @return array
     */
    function getInkoopProfiles(&$oI3a, $bKeyValue=false)
    {
        // get all inkooporganisations from db = orgs of type IKP
        $q = array( 'AND'
                  , array(I3A_FLD, 'ORG_ID')
                  , array(I3A_FLD, 'ORG_NAME')
                  , array(I3A_FLD, 'ORG_DEF_CODE', " = 'IKP'")
                  );

        $oI3a->searchOrganizations($aOrgs, $q);

        if ($bKeyValue) {
            // combine them in $key => $value array (for cmb)
            $aReturn[0] = '';
            foreach((array)$aOrgs as $value) {
                $aReturn[$value['ORG_ID']] = $value['ORG_NAME'];
            }

        } else {
            $aReturn = $aOrgs;
        }

        return $aReturn;

    }

    /**
     * setInkoopProfile
     *
     * set an inkoopprofile for an praktijk-orginisation
     *
     * @access public
     * @param  object   $oI3a       i3a-object
     * @param  int      $child      id of praktijk-org
     * @param  int      $parent     id of inkoopprofile-org
     * @return void
     */
    function setInkoopProfile(&$oI3a, $child, $parent)
    {
        $aIkp = $this->getInkoopProfile(&$oI3a, $child);
        if ($aIkp['VAL_ID']) {
            $sSql = " UPDATE TBL_I3A_ATT_VALUES
                         SET VAL_VALUE = '" . (int)$parent ."'
                       WHERE VAL_ID = " . (int)$aIkp['VAL_ID'] . "
                    ";
            $oI3a->_db->Execute($sSql);
        } else {
            $sSql = " INSERT INTO TBL_I3A_ATT_VALUES
                           ( VAL_ID
                           , VAL_CREATEDATE
                           , VAL_CHANGEDATE
                           , VAL_ATT_CODE
                           , VAL_USR_ID
                           , VAL_ORG_ID
                           , VAL_VALUE
                           )
                      VALUES
                           ( SEQ_I3A_ATT_VALUES.NEXTVAL
                           , SYSDATE
                           , SYSDATE
                           , 'GATT_IKPID'
                           , NULL
                           , '" . (int)$child ."'
                           , '" . (int)$parent ."'
                           )
                    ";
            $oI3a->_db->Execute($sSql);
        }

    }

    /**
     * getInkoopProfile
     *
     * get the inkoopprofile organisation of the org.
     * returns array (VAL_ID => the id  , VAL_VALUE => the name )
     *
     * @access public
     * @param  object   $oI3a       i3a-object
     * @param  int      $org        id of praktijk-org
     * @return array
     */
    function getInkoopProfile(&$oI3a, $org)
    {
        $sSql = " SELECT VAL_ID, VAL_VALUE
                    FROM TBL_I3A_ATT_VALUES
                   WHERE VAL_ATT_CODE = 'GATT_IKPID'
                     AND VAL_ORG_ID = " . (int)$org . "
                ";
        $rst = $oI3a->_db->Query($sSql);
        $aRec = $rst->Row();
        $rst->Close();
        return $aRec;

    }



    /**
     * getProfileInfo
     *
     * get detail info of an profile org
     *
     * @access public
     * @param  object   $oI3a       i3a-object
     * @param  int      $org        id of profile-org
     * @return array
     */
    function getProfileInfo(&$oI3a, $org)
    {
        $q = array( 'AND'
                  , array(I3A_FLD, 'ORG_ID', " = " . $org)
                  , array(I3A_FLD, 'ORG_DEF_CODE', " = 'IKP'")
                  , array(I3A_FLD, 'ORG_NAME')
                  , array(I3A_FLD, 'GATT_NORMPC')
                  , array(I3A_FLD, 'GATT_VOORRCONTROLEINTVAL')
                  , array(I3A_FLD, 'GATT_VOORRCONTROLEEMAIL')
                  );
        $oI3a->searchOrganizations($aOrgs, $q);
        return $aOrgs[0];

    }

    /**
     * getProfilePraktijk
     *
     * get all clientele of an profile
     *
     * @access public
     * @param  object   $oI3a       i3a-object
     * @param  boolean  $bKeyValue  true => key/value format,  false => recordset format
     * @return array
     */
    function getProfilePraktijk(&$oI3a, $bKeyValue=false)
    {
        // get all inkooporganisations from db = orgs of type IKP
        $q = array( 'AND'
                  , array(I3A_FLD, 'ORG_ID')
                  , array(I3A_FLD, 'ORG_NAME')
                  , array(I3A_FLD, 'ORG_DEF_CODE', " = 'PRK'")
                  , array(I3A_FLD, "nvl(GATT_IKPID,'0')", " != '0'")
                  );

        $oI3a->searchOrganizations($aOrgs, $q);

        if ($bKeyValue) {
            foreach((array)$aOrgs as $aValue) {
                $aReturn[$aValue['GATT_IKPID']][$aValue['ORG_ID']] = $aValue['ORG_NAME'];
            }

        } else {
            $aReturn = $aOrgs;
        }

        return $aReturn;

    }

    /**
     * getPraktijkInfo
     *
     * get info of a clientele
     *
     * @access public
     * @param  object   $oI3a       i3a-object
     * @param  int      $org        id of clientele-org
     * @return array
     */
    function getPraktijkInfo(&$oI3a, $org)
    {
        $q = array( 'AND'
                  , array(I3A_FLD, 'ORG_ID', " = " . $org)
                  , array(I3A_FLD, 'ORG_DEF_CODE', " = 'PRK'")
                  , array(I3A_FLD, 'ORG_NAME')
                  );
        $oI3a->searchOrganizations($aOrgs, $q);
        return $aOrgs[0];
    }

    /**
     * saveStock
     *
     * save stock-inventory
     *
     * @access public
     * @param  object  $oStock  stock-object
     * @return void
     */
    function saveStock(&$oStock)
    {

        // save header
        $nNewId = $this->saveInventory( $oStock->getProfile()
                                      , $oStock->getPraktijk()
                                      , $oStock->getScannerId()
                                      , $oStock->getDateTime()
                                      );

        // save all products
        $aStock = $oStock->getStock();
        foreach((array)$aStock as $nId=>$nNumber) {
            $this->saveInventoryRow($nNewId, $nId, $nNumber);
        }


    }

    /**
     * saveInventory
     *
     * save the inventory header-record
     *
     * @access public
     * @param  int    $nProfileId   id of profile
     * @param  int    $nClienteleId id of clientele
     * @param  string $sScannerId   scannerid
     * @param  string $dtDateTime   datetime of scan
     * @return void
     */
    function saveInventory($nProfileId, $nClienteleId, $sScannerId, $dtDateTime)
    {
        $sSql = " INSERT INTO tbl_dvb_inventory
                            ( inv_id
                            , inv_profile_id
                            , inv_clientele_id
                            , inv_scannerid
                            , inv_datetime
                            , inv_notification
                            )
                       VALUES
                            ( NULL
                            , " . (int)$nProfileId . "
                            , " . (int)$nClienteleId . "
                            , '" . mysql_real_escape_string($sScannerId) . "'
                            , '" . $dtDateTime . "'
                            , 'N'
                            )
                ";
        $this->_db->Execute($sSql);
        $nNewId = $this->_db->lastInsertID();


        return $nNewId;
    }

    /**
     * saveInventoryRow
     *
     * save one product of the inventory
     *
     * @access public
     * @param  int    $nInventoryId     id of inventory
     * @param  int    $nProductdId      id of product
     * @param  int    $nNumber          number of products in the inventory
     * @return void
     */
    function saveInventoryRow($nInventoryId, $nProductdId, $nNumber)
    {
        $sSql = " INSERT INTO tbl_dvb_inventory_row
                            ( invr_id
                            , invr_inv_id
                            , invr_prd_id
                            , invr_number
                            )
                       VALUES
                            ( NULL
                            , " . (int)$nInventoryId . "
                            , " . (int)$nProductdId . "
                            , " . (int)$nNumber . "
                            )
                ";
        $this->_db->Execute($sSql);
        $nNewId = $this->_db->lastInsertID();
        return $nNewId;

    }

    /**
     * getLastInventory
     *
     * get last inventory of all clientele of a profile. Return a recordset-type array
     *
     * @access public
     * @param  int     $nProfileId   id of the profile-org
     * @param  boolean $bAll         if false get only the ones without a notification-mail
     * @return array
     */
    function getLastInventory($nProfileId, $bAll = false)
    {
        $sSql = " SELECT inv.inv_id
                       , inv.inv_clientele_id
                       , inv.inv_datetime
                       , DATEDIFF(now(), inv.inv_datetime) as diff
                    FROM tbl_dvb_inventory inv
                        JOIN (
                                SELECT inv_clientele_id, max(inv_datetime) as inv_datetime
                                  FROM tbl_dvb_inventory
                                 WHERE inv_profile_id = " . (int)$nProfileId . "
                                 GROUP BY inv_clientele_id
                             ) q
                          ON inv.inv_profile_id = " . (int)$nProfileId . "
                         AND inv.inv_clientele_id = q.inv_clientele_id
                         AND inv.inv_datetime = q.inv_datetime
                         " . (!$bAll ? " AND inv_notification = 'N' " : "") . "
                ";
        $rst = $this->_db->Query($sSql);
        while (!$rst->EOF()) {
            $aRec[] = $rst->Row();
            $rst->MoveNext();
        }
        $rst->Close();
        return $aRec;

    }

    /**
     * markMailSend
     *
     * set the notification-sent flag for one or more inventories
     *
     * @access public
     * @param  array    $aInventoryId   array with one or more inventory id's
     * @return void
     */
    function markMailSend($aInventoryId)
    {
        if (count($aInventoryId) > 0) {
            $sSql = " UPDATE tbl_dvb_inventory
                         SET inv_notification = 'Y'
                       WHERE inv_id in ( " . implode(', ', $aInventoryId) . ")
                    ";
            $this->_db->Execute($sSql);
        }

    }

    /**
     * getUsersProfile
     *
     * get default profile for Inkoopmedewerker (IKM) users
     *
     * @access public
     * @param  int    $uid  id of user
     * @return void
     */
    function getProfileOfUser(&$oI3a, $uid)
    {
        $q = array(I3A_AND
                  , array(I3A_FLD, 'USR_ORG_ID')
                  , array(I3A_FLD, 'USR_DEF_CODE', " = 'IKM' ")
                  , array(I3A_FLD, 'USR_ID', " = " . (int)$uid)
                  );
        $oI3a->searchUsers($aUser, $q);

        return $aUser[0]['USR_ORG_ID'];
    }

    /**
     * getClienteleOverview
     *
     * get the total, final and complete overvie of all clientel in a profile
     *
     * @access public
     * @param  object   $oI3a           i3a object
     * @param  int      $profileOrgId   id of profile
     * @param  array    $aDates         array of interval
     * @return array
     */
    function getClienteleOverview(&$oI3a, $profileOrgId, $aDates)
    {
        // first of all get the org
        $q = array( 'AND'
                  , array(I3A_FLD, 'ORG_ID')
                  , array(I3A_FLD, 'ORG_DEF_CODE', " = 'PRK'")
                  , array(I3A_FLD, 'ORG_NAME')
                  , array(I3A_FLD, 'GATT_IKPID', " = '" . (int)$profileOrgId . "'")
                  );
        $oI3a->searchOrganizations($aOrgs, $q);

        // get lastInventoryDates
        $aRawInventory = $this->getLastInventory($profileOrgId, true);
        foreach((array)$aRawInventory as $value) {
            $aInventory[$value['inv_clientele_id']] = $value;
        }

        $aProfileInfo = $this->getProfileInfo($oI3a, $profileOrgId);
        $nInterval = $this->getDaysFromInventoryControlIntval($aProfileInfo["GATT_VOORRCONTROLEINTVAL"]);

        // add stuff to aOrgs table
        foreach((array)$aOrgs as $key=>$aOrg) {
            $aOrgs[$key]['diff'] = $aInventory[$aOrg['ORG_ID']]['diff'];
            if ($aInventory[$aOrg['ORG_ID']]['diff'] > $nInterval) {
                $aOrgs[$key]['acknack'] = "nack";
            } else {
                $aOrgs[$key]['acknack'] = "ack";
            }

        }

        return $aOrgs;
    }

    /**
     * handleDates
     *
     * handle dates in interval select
     * return an array (dateStart   => startdate in unix-timestamp format
     *                  fmDateStart => startdate in dd-mm-YYYY format
     *                  dateEnd     => enddate in unix-timestamp format
     *                  fmDateEnd   => enddate in dd-mm-YYYY format
     *                  intval      => selected interval wk, mn, yr
     *                  msg         => string to message to user
     *                  first       => interval string of first month in interval ( string format YYYY, YYYYmm or YYYYWW)
     *                  last        => interval string of last month in interval
     *
     * @access public
     * @param  string $dtStart  date in mdd-mm-YYYY format; startdate of interval
     * @param  string $dtEnd    date in mdd-mm-YYYY format; enddate of interval
     * @param  string $interval
     * @param  array $aName beschrijving
     * @return array
     */
    function handleDates($dtStart=null, $dtEnd=null, $intval = CDVB_INTVAL_NONESELECTED)
    {

        $aMonthTrans = array ( 1 => 'Jan', 2 => 'Feb', 3 => 'Mrt', 4 => 'Apr', 5=> 'Mei', 6 => 'Jun',
                              7 => 'Jul', 8 => 'Aug', 9 => 'Sep', 10 => 'Okt', 11 => 'Nov', 12 => 'Dec');

        $dayStart = substr($dtStart, 0, 2);
        $monthStart = substr($dtStart, 3, 2);
        $yearStart = substr($dtStart, 6, 4);

        $dayEnd = substr($dtEnd, 0, 2);
        $monthEnd = substr($dtEnd, 3, 2);
        $yearEnd = substr($dtEnd, 6, 4);

        switch($intval) {
            case CDVB_INTVAL_WEEK:

                // correct startdate to begin of week (previous monday)
                $tsStart = mktime(0, 0, 0, $monthStart, $dayStart, $yearStart);
                $day = date('w', $tsStart); // Sun = 0, Sat =6, while date('W') starts week on monday
                if ($day == 0) {
                    $diff = 6;
                } else {
                    $diff = $day - 1;
                }

                $tsStart = mktime(0, 0, 0, $monthStart, $dayStart - $diff, $yearStart);

                // correct enddate to end of week (next sunday)
                $tsEnd = mktime(0, 0, 0, $monthEnd, $dayEnd, $yearEnd);
                $day = date('w', $tsEnd); // Sun = 0, Sat =6
                if ($day == 0) {
                    $diff = 0;
                } else {
                    $diff = 7 - $day;
                }

                $tsEnd = mktime(0, 0, 0, $monthEnd, $dayEnd + $diff, $yearEnd);

                $aReturn['intval'] = CDVB_INTVAL_WEEK;

                // correct startdate to a maximum interval of 8 weeks
                $tsLimit = mktime(0, 0, 0, $monthEnd, $dayEnd + $diff - 55, $yearEnd); // 8 weeks - 1 day
                if ($tsStart >= $tsEnd ||
                    $tsStart < $tsLimit) {

                    // correct startdate to a maximum interval of 8 weeks
                    $aReturn['dateStart']   = $tsLimit;
                    $aReturn['fmDateStart'] = date('d-m-Y', $tsLimit);
                    $aReturn['dateEnd']     = $tsEnd;
                    $aReturn['fmDateEnd']   = date('d-m-Y', $tsEnd);
                    $aReturn['msg']         = "De periode kan niet langer zijn dan 8 weken. Voor een langere periode kies interval maanden of jaren";
                    $firstyear = date('Y', $tsLimit); // needing dateformat option o!!!
                    $firstweek = date('W', $tsLimit);
                    if (date('W', $tsLimit) >= 52 && date('m', $tsLimit) == 1) {
                        // needing dateformat option o!!!
                        $firstyear -= 1;
                    }

                    $aReturn['first']       = date('YW', $tsLimit); // needing dateformat option o!!!
                    $lastyear = date('Y', $tsEnd);
                    $lastweek = date('W', $tsEnd);
                    if (date('W', $tsEnd) >= 52 && date('m', $tsEnd) == 1) {
                        $lastyear -= 1;
                    }
                    $aReturn['last']        = date('YW', $tsEnd);

                } else {
                    $aReturn['dateStart']   = $tsStart;
                    $aReturn['fmDateStart'] = date('d-m-Y', $tsStart);
                    $aReturn['dateEnd']     = $tsEnd;
                    $aReturn['fmDateEnd']   = date('d-m-Y', $tsEnd);
                    $firstyear = date('Y', $tsStart);
                    $firstweek = date('W', $tsStart);
                    $aReturn['first']       = date('YW', $tsStart);
                    if (date('W', $tsStart) >= 52 && date('m', $tsStart) == 1) {
                        $firstyear -= 1;
                    }

                    $lastyear = date('Y', $tsEnd);
                    $lastweek = date('W', $tsEnd);
                    if (date('W', $tsEnd) >= 52 && date('m', $tsEnd) == 1) {
                        $lastyear -= 1;
                    }

                    $aReturn['last']        = date('YW', $tsEnd);
                }

                for ($i = $firstyear; $i <= $lastyear; $i++) {
                    for ($j = ($i == $firstyear ? $firstweek : 1); $j <= ($i == $lastyear ? $lastweek : date('W', mktime(0, 0, 0, 12, 28, $i))); $j++) {
                        $aReturn['enum'][$i . str_pad($j, 2, '0', STR_PAD_LEFT)] = 'W' . $j . ' ' . $i;
                    }
                }

                break;

            case CDVB_INTVAL_YEAR:
                // set start and enddate to previous begin resp next end of year
                $tsStart = mktime(0, 0, 0, 1, 1, $yearStart);
                $tsEnd = mktime(0, 0, 0, 12, 31, $yearEnd);

                $aReturn['intval'] = CDVB_INTVAL_YEAR;
                // correct startdate to max of six years
                $tsLimit = mktime(0, 0, 0, 1, 1, $yearEnd-5); // 6 year
                if ($tsStart >= $tsEnd ||
                    $tsStart < $tsLimit) {
                    $aReturn['dateStart']   = $tsLimit;
                    $aReturn['fmDateStart'] = date('d-m-Y', $tsLimit);
                    $aReturn['dateEnd']     = $tsEnd;
                    $aReturn['fmDateEnd']   = date('d-m-Y', $tsEnd);
                    $aReturn['msg']         = "De periode kan niet langer zijn dan 6 jaren.";
                    $aReturn['first']       = date('Y', $tsLimit);
                    $aReturn['last']        = date('Y', $tsEnd);
                    $firstyear = date('Y', $tsLimit);
                    $lastyear = date('Y', $tsEnd);

                } else {
                    $aReturn['dateStart']   = $tsStart;
                    $aReturn['fmDateStart'] = date('d-m-Y', $tsStart);
                    $aReturn['dateEnd']     = $tsEnd;
                    $aReturn['fmDateEnd']   = date('d-m-Y', $tsEnd);
                    $aReturn['first']       = date('Y', $tsStart);
                    $aReturn['last']        = date('Y', $tsEnd);
                    $firstyear = date('Y', $tsStart);
                    $lastyear = date('Y', $tsEnd);
                }

                for ($i = $firstyear; $i <= $lastyear; $i++) {
                    $aReturn['enum'][$i] = $i;
                }

                break;

            case CDVB_INTVAL_MONTH:
                // set start and enddate to previous begin resp next end of month
                $tsStart = mktime(0, 0, 0, $monthStart, 1, $yearStart);
                $tsEnd = mktime(0, 0, 0, $monthEnd+1, 0, $yearEnd);

                $aReturn['intval'] = CDVB_INTVAL_MONTH;
                // correct startdate to max of six months
                $tsLimit = mktime(0, 0, 0, $monthEnd -5, 1, $yearEnd); // 6 months
                if ($tsStart >= $tsEnd ||
                    $tsStart < $tsLimit) {
                    $aReturn['dateStart']   = $tsLimit;
                    $aReturn['fmDateStart'] = date('d-m-Y', $tsLimit);
                    $aReturn['dateEnd']     = $tsEnd;
                    $aReturn['fmDateEnd']   = date('d-m-Y', $tsEnd);
                    $aReturn['msg']         = "De periode kan niet langer zijn dan 6 maanden. Voor een langere periode kies interval jaren";
                    $aReturn['first']       = date('Ym', $tsLimit);
                    $aReturn['last']        = date('Ym', $tsEnd);
                    $firstyear = date('Y', $tsLimit);
                    $firstmonth = (int)date('m', $tsLimit);
                    $lastyear = date('Y', $tsEnd);
                    $lastmonth = (int)date('m', $tsEnd);

                } else {
                    $aReturn['dateStart']   = $tsStart;
                    $aReturn['fmDateStart'] = date('d-m-Y', $tsStart);
                    $aReturn['dateEnd']     = $tsEnd;
                    $aReturn['fmDateEnd']   = date('d-m-Y', $tsEnd);
                    $aReturn['first']       = date('Ym', $tsStart);
                    $aReturn['last']        = date('Ym', $tsEnd);
                    $firstyear = date('Y', $tsStart);
                    $firstmonth = (int)date('m', $tsStart);
                    $lastyear = date('Y', $tsEnd);
                    $lastmonth = (int)date('m', $tsEnd);
                }

                for ($i = $firstyear; $i <= $lastyear; $i++) {
                    for ($j = ($i == $firstyear ? $firstmonth : 1); $j <= ($i == $lastyear ? $lastmonth : 12); $j++) {
                        $aReturn['enum'][$i . str_pad($j, 2, '0', STR_PAD_LEFT)] = $aMonthTrans[$j] . ' ' . $i;
                    }
                }


                break;

            case CDVB_INTVAL_NONESELECTED:
            default:

                if ($_SESSION['cdvb_dateselection']) {
                    $aReturn = $_SESSION['cdvb_dateselection'];
                    $aReturn['msg'] = "";

                } else {
                    // default = six months including current month
                    $aReturn['intval'] = CDVB_INTVAL_MONTH;
                    $aReturn['dateStart']   = mktime( 0, 0, 0, date('m') - 5, 1, date('Y'));
                    $aReturn['dateEnd']     = mktime( 0, 0, 0, date('m')+1, 0, date('Y'));;
                    $aReturn['fmDateStart'] = date('d-m-Y', $aReturn['dateStart']);
                    $aReturn['fmDateEnd']   = date('d-m-Y', $aReturn['dateEnd']);
                    $aReturn['first']       = date('Ym', $aReturn['dateStart']);
                    $aReturn['last']        = date('Ym', $aReturn['dateEnd']);
                    $firstyear = date('Y', $aReturn['dateStart']);
                    $firstmonth = (int)date('m', $aReturn['dateStart']);
                    $lastyear = date('Y', $aReturn['dateEnd']);
                    $lastmonth = (int)date('m', $aReturn['dateEnd']);

                    for ($i = $firstyear; $i <= $lastyear; $i++) {
                        for ($j = ($i == $firstyear ? $firstmonth : 1); $j <= ($i == $lastyear ? $lastmonth : 12); $j++) {
                            $aReturn['enum'][$i . str_pad($j, 2, '0', STR_PAD_LEFT)] = $aMonthTrans[$j] . ' ' . $i;
                        }
                    }

                }
                break;



        }

        $_SESSION['cdvb_dateselection'] = $aReturn;

        return $aReturn;

    }

    /**
     * getDaysFromInventoryControlIntval
     *
     * translate InventoryControlIntval to number of days
     *
     * @access public
     * @param  string $sIntval  InventoryControlIntval (from org-settings)
     * @return integer
     */
    function getDaysFromInventoryControlIntval($sIntval) {
        if (strpos(strtolower($sIntval), 'dag') > 0) {
            $nInterval = (int)$sIntval;
        } elseif (strpos(strtolower($sIntval), 'maand') > 0) {
            // assume month = default 30 days
            $nInterval = (int)$sIntval * 30;
        } elseif (strpos(strtolower($sIntval), 'wek') > 0) {
            // weeks = wek(en)
            $nInterval = (int)$sIntval * 7;
        } elseif (strpos(strtolower($sIntval), 'week') > 0) {
            $nInterval = (int)$sIntval * 7;
        } else {
            // no length string in it: assume days
            $nInterval = (int)$sIntval;
        }
        return $nInterval;
    }


    function getPercentage($aProc, $aRev, $targetpc) {

        foreach((array)$aProc['total']['periods'] as $id => $value) {
            if ($aRev[$id]['rev_amount']) {
                //$aReturn[$id]['pc']   = ($value['price'] / $aRev[$id]['rev_amount']) * 100;
                $aReturn[$id]['pc']   = bcmul(bcdiv($value['price'], $aRev[$id]['rev_amount'], 4), '100', 2);
            } else {
                //$aReturn[$id]['pc']   = ($value['price'] / 0.00001) * 100;
                $aReturn[$id]['pc']   = bcmul(bcdiv($value['price'], '0.00001', 4), '100', 2);
            }
            //$aReturn[$id]['diff'] = $aReturn[$id]['pc'] - $targetpc;
            $aReturn[$id]['diff'] = bcsub($aReturn[$id]['pc'], $targetpc, 2);
        }

        if ($aRev['total']['rev_amount']) {
            //$aReturn['total']['pc'] = ($aProc['total']['price'] / $aRev['total']['rev_amount']) * 100;
            $aReturn['total']['pc'] = bcmul(bcdiv($aProc['total']['price'], $aRev['total']['rev_amount'], 4), '100', 2);
        } else {
            //$aReturn['total']['pc'] = ($aProc['total']['price'] / 0.00001) * 100;
            $aReturn['total']['pc'] = bcmul(bcdiv($aProc['total']['price'], '0.00001', 4), '100', 2);
        }
        
        //$aReturn['total']['diff'] = $aReturn['total']['pc'] - $targetpc;
        $aReturn['total']['diff'] = bcsub($aReturn['total']['pc'], $targetpc, 2);

        return $aReturn;
    }
    
    
    /**
     * userHasRightsForOrg
     *
     * check if user is allowed to see this org
     *
     * @access public
     * @param  object   $oI3a   i3a
     * @param  int      $uid    id of user
     * @param  int      $oid    id of org to check
     * @return void
     */    
    function userHasRightsForOrg(&$oI3a, $uid, $oid)
    {
        
        if ($_SESSION['session_usr_def_code'] == 'IKM') {
            $q = array(I3A_AND
                      , array(I3A_FLD, 'USR_ORG_ID')
                      , array(I3A_FLD, 'USR_DEF_CODE', " = 'IKM' ")
                      , array(I3A_FLD, 'USR_ID', " = " . (int)$uid)
                      );
            $oI3a->searchUsers($aUser, $q);
    
            $nUserOid = $aUser[0]['USR_ORG_ID'];
    
            $q = array( 'AND'
                      , array(I3A_FLD, 'ORG_ID'      , ' = ' . (int)$oid)
                      , array(I3A_FLD, 'ORG_DEF_CODE', " = 'PRK'")
                      , array(I3A_FLD, 'GATT_IKPID'  , " = " . (int)$nUserOid)
                      
                      );
    
            $oI3a->searchOrganizations($aOrgs, $q);
            
            if ($aOrgs[0]['ORG_ID']) {
                return true;
            } else {
                return false;
            }
                
        
        } elseif ($_SESSION['session_usr_def_code'] == 'IKB') {       
             return true;
            
        } else {
             return false;
            
        }

    }

    function getShowPrice(&$oI3a, $uid)
    {
            $q = array(I3A_AND
                      , array(I3A_FLD, 'GATT_SHOW_PRICES')
                      , array(I3A_FLD, 'USR_DEF_CODE', " = 'MEM' ")
                      , array(I3A_FLD, 'USR_ID', " = " . (int)$uid)
                      );
            $oI3a->searchUsers($aUser, $q);
            return $aUser[0]['GATT_SHOW_PRICES'];
    }

}


?>
