<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_STRICT ^ E_WARNING ^ E_DEPRECATED );

function __autoload_my_classes( $classname )
{
  $q = explode( '\\', $classname );
  $c = array_pop( $q );
  $base_path = 'autoload/' . implode( '/', $q ) . '/';
  $f = $base_path . $c . '.php';

  if ( !file_exists( $f ) )
    $f = $base_path . 'class.' . $c . '.php';

  if ( file_exists( $f ) )
    require_once( $f );
}
spl_autoload_register( '__autoload_my_classes' );
date_default_timezone_set( 'Europe/Warsaw' );

require_once 'config.php';
require_once 'libraries/medoo/medoo.php';
require_once 'libraries/grid/config.php';
require_once 'libraries/rb.php';

session_start();

if ( !isset( $_SESSION['check'] ) )
{
  session_regenerate_id();
  $_SESSION['check'] = true;
  $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}

if ( $_SESSION['ip'] !== $_SERVER['REMOTE_ADDR'] )
{
  session_destroy();
  header( 'Location: /' );
  exit;
}

$mdb = new medoo( [
    'database_type' => 'mysql',
    'database_name' => $database['name'],
    'server'        => $database['host'],
    'username'      => $database['user'],
    'password'      => $database['password'],
    'charset'       => 'utf8'
  ] );

\R::setup( 'mysql:host=' . $database['host'] . ';dbname=' . $database['name'], $database['user'], $database['password'] );
\R::ext( 'xdispense', function( $type )
{
  return R::getRedBean() -> dispense( $type );
} );

/* import zadan z email */
$response = \Cron::import_tasks_from_email();
if ( $response['status'] == 'ok' )
{
  echo json_encode( $response );
  exit;
}
if ( $response['status'] == 'error' )
{
  echo json_encode( $response );
  exit;
}


if ( date( 'G' ) > 6 )
{
  /* wysyłanie przypomnnień do zadań */
  $response = \Cron::tasks_emails();
  if ( $response['status'] == 'ok' )
  {
    echo json_encode( $response );
    exit;
  }
}

/* dodawanie zadań rekursywnych */
$response = \Cron::recursive_tasks();
if ( $response['status'] == 'ok' )
{
  echo json_encode( $response );
  exit;
}

echo json_encode( ['status' => 'empty'] );
?>
