#!/usr/bin/php
<?php
/******************************************************************
* Copyright © 2011 ICT Innovations Pakistan All Rights Reserved   *
* Developed By: Nasir Iqbal                                       *
*             : Tahir Almas                                       *
* Website : http://www.ictinnovations.com/                        *
* Mail : info@ictinnovations.com                                  *
******************************************************************/

use ICT\Broadcast\Integration;

$root_dir = dirname(dirname(__FILE__));
include_once($root_dir.'/wwwroot/lib/lib.php');

/* ######################## LOG FILE ######################### */
$log_path = "$root_dir/logs";
$log_file = "$log_path/integration.log";
$log_file_common = $log_file; // override default log file for mssgLog
 
exec("mkdir -p '$log_path'"); // initialize run directory
exec("touch '$log_file'");    // initialize log file

$error_leval = (0
                | E_ERROR
                | E_WARNING
                | E_PARSE
                // | E_NOTICE
                | E_CORE_ERROR
                | E_CORE_WARNING
                | E_COMPILE_ERROR
                | E_COMPILE_WARNING
                | E_USER_ERROR
                | E_USER_WARNING
                | E_USER_NOTICE
                // | E_STRICT
                // | E_ALL
               );

set_error_handler("log_handler", $error_leval);

/* ################## START INTEGRATION SCRIPT ################ */
log_handler(0, "--------------[ INTEGRATION REQUEST ]--------------");

$script_name    = array_shift($argv); // $argv[0] is script name
$integration_id = array_shift($argv); // $argv[1] is integration id
$aParameters    = $argv;  // anything remaining is arguments / paramters for integration

$input_data = print_r($aParameters, true);
$input_data = preg_replace(array("/\n/", '/\s+/'), array(',', ' '), $input_data);
log_handler(0, "Integration request received with id: $integration_id and data: $input_data");

/* #################### PROGRAM START HERE ################### */

// GET DESIRED RECORD FROM CAMPAIGN TABLE
try {
  $oIntegration = Integration::load($integration_id);
} catch (Exception $ex) {
  log_handler(0, "No such integration found with id $integration_id");
  exit(1);
}

$result = $oIntegration->execute($aParameters);
$output_data = print_r($result, true);
$output_data = preg_replace(array("/\n/", '/\s+/'), array(',', ' '), $output_data);
log_handler(0, "Integration request output is: $output_data");

exit(0);

function log_handler($errno=0, $errmsg='', $filename='', $linenum='', $vars='') {
    global $log_file;

    // timestamp for the error entry
    $dt  = gmdate("Y-m-d H:i:s (T)");

    $err = "[$dt] $errmsg\n";
    if ($errno > 0) {
        $err .= "Error # $errno; file name: $filename; line #: $linenum;\n";
    }
    if ($vars) {
        $err .= print_r($vars, true)."\n";
    }
    error_log($err, 3, $log_file);
}
