<?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 );
  $f = 'autoload/' . implode( '/', $q ) . '/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/phpmailer/class.phpmailer.php';
require_once 'libraries/phpmailer/class.smtp.php';
require_once 'libraries/rb.php';

session_start();

$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 );
} );

// dodawanie domeny przez API
if ( \S::get( 'action' ) == 'domain_tester_add' )
{
  if ( !$mdb -> count( 'domain_tester', [ 'AND' => [ 'url' => \S::get( 'domain' ), 'hidden' => 0 ] ] ) )
  {
    $mdb -> insert( 'domain_tester', [
      'url' => \S::get( 'domain' )
    ] );
  }

  echo json_encode( ['result' => 'ok'] );
  exit;
}

// Open Page Rank - pobieranie domeny
if ( \S::get( 'action' ) == 'domain_opr_check' )
{
  $mdb -> delete( 'domain_tester', [ 'url' => '' ] );

  $domain = $mdb -> get( 'domain_tester', '*', [ 'opr' => null, 'ORDER' => [ 'date_add' => 'DESC' ] ] );
  if ( $domain )
  {
    $result['id'] = $domain['id'];
    $result['url'] = $domain['url'];
    $result['domains_left'] = $mdb -> count( 'domain_tester', [ 'opr' => null ] );
    $result['result'] = 'ok';

    echo json_encode( $result );
  }
  else
    echo json_encode( ['result' => 'bad'] );
  exit;
}

// Open Page Rank - zapis
if ( \S::get( 'action' ) == 'domain_opr_save' )
{
  $mdb -> update( 'domain_tester', [
    'opr' => str_replace( ',', '.', \S::get( 'page_rank' ) ),
    'opr_date' => date( 'Y-m-d H:i:s' )
  ], [
    'id' => \S::get( 'domain_id' )
  ] );

  echo json_encode( ['result' => 'ok'] );
  exit;
}