<?php
/**
 * Url relocator
 *
 * Track a client click on a specific url (from email or html page)
 * The url parameters can be as plain GET request or base64 encoded request
 * The following url are equivalents:
 *
 * - http://path/to/out.php?id=1234&contact=50827&company=1198&url=http://mediatel.co.uk/some/path#anchor
 * - http://path/to/out.php?aWQ9MTIzNCZjb250YWN0PTUwODI3JmNvbXBhbnk9MTE5OCZ1cmw9aHR0cCUzQSUyRiUyRm1lZGlhdGVsLmNvLnVrJTJGc29tZSUyRnBhdGglMjNhbmNob3I=
 *
 * Mandatory parameters:
 * id: resource [email|link] id
 * contact: ContactID from tblContacts in mtinfo database
 * company: the contact CompanyID from tblCompanies in mtinfo database
 * url: full url (http[s]://website/path/to/something) where the client will be redirected
 */

// Autoload function
require dirname(dirname(__DIR__)) . '/email-tracker/autoload.php';

// Set env
$env = getenv('APPLICATION_ENVIRONMENT') ?: 'dev';

// Init Request
$request = MailTracker\Request::createFromGlobals();

// Medaitel IPs
$mediatelIps = ['192.168.0.0/16', '10.0.0.0/8'];

// Load mediatel ZF configuration file
$configFile = dirname(dirname(__DIR__)) . '/application/application.ini';
$config = MailTracker\IniConfigReader::parse($configFile, $env);

// Set Db connection params
$dsn = sprintf(
    'dblib:host=%s:%d;dbname=%s;charset=%s;',
    $config['resources.multidb.classic_mtinfo.host'],
    $config['resources.multidb.classic_mtinfo.port'],
    $config['resources.multidb.classic_mtinfo.dbname'],
    $config['resources.multidb.classic_mtinfo.charset']
);

$username = $config['resources.multidb.classic_mtinfo.username'];
$password = $config['resources.multidb.classic_mtinfo.password'];

// Init Storage
$storage = new MailTracker\Storage\MsSqlStorage(
    new \PDO($dsn, $username, $password)
);

// Init Logger
$logger = new \MailTracker\Logger\SystemLogger();

try {
    // Tracker
    $clickTracker = new MailTracker\ClickTracker($request, $storage);

    // If the client IP isn't in Mediatel IP ranges, register click
    if (! MailTracker\Component\IpUtils::inRanges($request->getClientIp(), $mediatelIps)) {
        $clickTracker->track();
    }

    // Redirect to 'url' page
    header('Location: ' . $clickTracker->getRedirectUrl());
} catch (Exception $e) {
    $logger->logError('invalid relocation request: "' . $request->getQueryString() . '"');
}
