<?php 

include "../../../config.inc.php";


$t = & new_smarty();

/////////////////////////////////////////////////////////////////////////////
$vars = get_input_vars();
$vercode = $vars[vercode];
$res = split(":", $vercode);

$action     = $vars[trn];
$amount     = $vars[amount];
$payment_id = intval($vars[custom1]);
$pnref 	    = $vars[trn_id];
$secret = $res[2];


function get_dump($var){
//dump of array
    $s = "";
    foreach ($var as $k=>$v)
        $s .= "$k => $v<br />\n";
    return $s;
}

function verotel_error($msg){
    global $order_id, $payment_id, $pnref;
    global $vars;
    fatal_error(sprintf(_PLUG_PAY_VEROTEL_FERROR, $msg, $payment_id, '<br />')."\n".get_dump($vars));
}

$db->log_error("VEROTEL DEBUG: " . get_dump($vars));

//////////////////////////////////////////////////////////////////////////////
//
//                           M   A   I   N
//
//////////////////////////////////////////////////////////////////////////////

// Check secret code
global $config;
$this_config = $config[payment][verotel];
if($this_config[secret] != $secret){
    verotel_error("Incorrect secret code!");
}


// add ip protection

switch ($action){
case 'add':
    $err = $db->finish_waiting_payment($payment_id, 'verotel', 
        $pnref, $amount, $vars);
    if ($err) 
        verotel_error("finish_waiting_payment error: $err");
    // set expire date to infinite
    $p = $db->get_payment($payment_id);    
    $product = $db->get_product($p['product_id']);
    if ($product['is_recurring'])
        $p['expire_date'] = '2012-12-31';
    $db->update_payment($payment_id, $p);
    break;
case 'modify':
    $p = $db->get_payment($payment_id);    
    $p['amount'] += $amount;
    $p['data'][] = $vars;
    $db->update_payment($payment_id, $p);
    break;
case 'delete':
    $p = $db->get_payment($payment_id);    
    $p['data'][] = $vars;
    $yesterday = date('Y-m-d', time()-3600*24);
    $product = $db->get_product($p['product_id']);
    if ($product['is_recurring'])
        $p['expire_date'] = $yesterday;
    else {
        $p['completed'] = 0;
//        $p['amount'] -= $amount;
    }        
    $db->update_payment($payment_id, $p);
    break;
    default: print "ERROR"; exit;
}

print "APPROVED";
