<?php

date_default_timezone_set('America/Chicago');

require('config.php');

require 'Slim/Slim.php';
require 'lib/custom_view.php';
require 'utils/clientUtils.php';
require 'utils/commonUtils.php';
require 'utils/mailUtils.php';
require 'utils/logUtils.php';
require 'utils/loginUtils.php';
require 'utils/security.php';
require '../../common/utils/url.php';

function startsWith($haystack, $needle)
{
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}

require '../../common/models/user.php';
require 'models/timeentry.php';
require 'models/client.php';
require 'models/mileageentry.php';
require 'models/closedate.php';
require 'models/car.php';
require 'models/agreement.php';
require 'models/agreementWeekly.php';
require 'models/expense.php';
require 'models/slsindividual.php';
require 'models/slstimeentry.php';
require 'models/fsIndividuals/fsIndividualDefaultHours.php';
require 'models/slsAfterHours/slsafterhourstimeentry.php';
require '../employees/common/model/payperiod.php';
require '../employees/common/model/payweek.php';

if(!isset($_SERVER['HTTPS']) && $onlyHttps || $_SERVER['HTTP_HOST'] != $host)
{
    header("Location:".$siteUrl);
    die();
}

session_cache_limiter(false);
session_start();

$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$currentUser = null;
if(!isset($_SESSION['uid']) && $requestPath != $basePath && $requestPath != $basePath.'login' && $requestPath != $basePath.'forgotpassword' && !startsWith($_SERVER['REQUEST_URI'],$basePath.'resetpassword')  && !startsWith($_SERVER['REQUEST_URI'],$basePath.'/api/billingreport')) {
    logHttpRequest(null);
    header("Location:".$siteUrl."?redir=".$requestPath);
    die();
}
$timeout = 60 * 30;
$fingerprint = md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'].'kasdflkqlskdjf');
if (    (isset($_SESSION['last_active']) && $_SESSION['last_active']<(time()-$timeout))
     || (isset($_SESSION['fingerprint']) && $_SESSION['fingerprint']!=$fingerprint)
     || isset($_GET['logout']) || $_SERVER['REQUEST_URI'] == $basePath.'logout'
    ) {
    logHttpRequest(null);
    setcookie(session_name(), '', time()-3600, '/');
    session_destroy();
    header("Location:".$siteUrl);
    die();
} else {
    //session_regenerate_id(); 
    $_SESSION['last_active'] = time();
    $_SESSION['fingerprint'] = $fingerprint;
    if(isset($_SESSION['uid'])) {
        if ($db) {
            $currentUser = \Models\User::fetch($db, $_SESSION['uid']);
        }
    }
}

logHttpRequest($currentUser != null ? $currentUser->id : null);

$view = new custom_view();
if($requestPath != $basePath &&
    $requestPath != $basePath.'login' &&
    $requestPath != $basePath.'dashboard' &&
    $requestPath != $basePath.'home' &&
    $requestPath != $basePath.'entry/create' &&
    $requestPath != $basePath.'entry/start' &&
    strpos($requestPath, $basePath.'entry/') !== 0 &&
    $requestPath != $basePath.'mileage/create' &&
    strpos($requestPath, $basePath.'mileage') !== 0 &&
    $requestPath != $basePath.'forgotpassword' &&
    strpos($requestPath, $basePath.'expense') !== 0 &&
    strpos($requestPath, $basePath.'slstime') !== 0 &&
    strpos($requestPath, $basePath.'rate3') !== 0 &&
    strpos($requestPath, $basePath.'slsindividual') !== 0 &&
    $requestPath != $basePath.'users' &&
    strpos($requestPath, $basePath.'users/') !== 0 &&
    strpos($requestPath, $basePath.'clients') !== 0 &&
    strpos($requestPath, $basePath.'entry/finalize') !== 0 &&
    strpos($requestPath, $basePath.'reports') !== 0 ||
    $requestPath == $basePath.'entry/all' ||
    $requestPath == $basePath.'entry/fssupervisor' ||
    $requestPath == $basePath.'mileage/all' ||
    $requestPath == $basePath.'mileage/sls' ||
    $requestPath == $basePath.'mileage/rate' ||
    strpos($requestPath, $basePath.'mileage/finalize') === 0) {
    $view->set_layout('base.php');
} else {
    $view->set_layout('base2.php');
}

$app = new Slim(
    array(
        'debug' => false,
        'view' => $view
    ));


$app->error(function($e) {
    $msg = "CODE\r\n".$e->getCode()."\r\n";
    $msg .= "MESSAGE\r\n".$e->getMessage()."\r\n";
    $msg .= "FILE\r\n".$e->getFile()."\r\n";
    $msg .= "LINE\r\n".$e->getLine()."\r\n";
    $msg .= "TRACE\r\n".$e->getTraceAsString()."\r\n";
    mail("scott.heckel@gmail.com", "ptc website error", $msg);
    die("<h1>Oops. Something went terribly wrong.</h1><p>Specifically, I hear the issue is \"<strong>".$e->getMessage()."</strong>\", which sounds pretty complicated.  Luckily, I hear the issue is <strong>on line ".$e->getLine()." in ".$e->getFile()."</strong>.</p><p>We are sorry, but do not worry as it is not your fault. We will look into this ASAP, <em>but</em> you should probably <strong>tell <a href='mailto:finance@pathwaystocommunity.com'>finance@pathwaystocommunity.com</a></strong> about it too just in case the error does not get to the right people.</p>");
});

require 'routes/login.php';
require 'routes/dashboard.php';
require 'routes/user.php';
require 'routes/timesheet.php';
require 'routes/mileage.php';
require 'routes/client.php';
require 'routes/fsIndividuals/defaultHoursHandlers.php';
require 'routes/reports.php';
require 'routes/car.php';
require 'routes/agreement.php';
require 'routes/expenses.php';
require 'routes/slsindividual.php';
require 'routes/slstimesheet.php';
require 'routes/slsafterhours/slsAfterHoursHandlers.php';

$app->run();

function getCurrentUser() {
	global $currentUser;

	return $currentUser;
}

function getDb() {
    global $db;
    return $db;
}

function getPtcSettings() {
    return parse_ini_file('./d/ptc.ini');
}

function savePtcSettings($settings) {
    write_php_ini($settings, './d/ptc.ini');
}

function write_php_ini($array, $file)
{
    $res = array();
    foreach($array as $key => $val)
    {
        if(is_array($val))
        {
            $res[] = "[$key]";
            foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
        }
        else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
    }
    safefilerewrite($file, implode("\r\n", $res));
}

function safefilerewrite($fileName, $dataToSave)
{    if ($fp = fopen($fileName, 'w'))
    {
        $startTime = microtime();
        do
        {            $canWrite = flock($fp, LOCK_EX);
           // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
           if(!$canWrite) usleep(round(rand(0, 100)*1000));
        } while ((!$canWrite)and((microtime()-$startTime) < 1000));

        //file was locked so now we can store information
        if ($canWrite)
        {            fwrite($fp, $dataToSave);
            flock($fp, LOCK_UN);
        }
        fclose($fp);
    }

}

function ptcDebug($user, $message) {
    if($user->username == 'ptc' || $user->username == 'scottheckel') {
        die($message);
    }
}

function getBaseUrl() {
    global $baseUrl;
    return $baseUrl;
}

function getBaseContentUrl() {
    global $baseUrl;
    global $baseContentPath;
    return $baseUrl.$baseContentPath;
}

function getSiteUrl() {
    global $siteUrl;
    return $siteUrl;
}

function getFSTimeUrl($path = 'home') {
    global $fsTimeSiteUri;
    return $fsTimeSiteUri.$path;
}

function getBaseServerPath() {
    global $baseServerPath;
    return $baseServerPath;
}

function curPageURL() {
    global $onlyHttps;
 $pageURL = 'http';
 if ($onlyHttps || (isset( $_SERVER["HTTPS"] ) && strtolower($_SERVER["HTTPS"] ) == "on")) {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

function isMobile() {
 $useragent=$_SERVER['HTTP_USER_AGENT'];
 return preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4));
}