<?php

$nv_root = dirname(__FILE__).'/';
$logFile = $nv_root.'log.txt';
include($nv_root.'Smses.php');

header("Content-Type: text/html;charset=UTF-8");

$nv_config = include($nv_root.'config.php');
sleep(2);
if(isset($_POST['nv_params']))
{
	$nv_params = $_POST['nv_params'];
	$nv_errors = array();
	$nv_success = '';
	
	$nv_result = array(
		'success'=>'',
		'error'=>array(),
	);
	
	if(isset($_POST['submit_callback']))
	{
		$nv_successMsg = $nv_config['success_msg_callback'];
		
		$nv_lastSend = intval($_COOKIE['lst']);
		
		if(time()-$nv_lastSend>=$nv_config['next_callback_time'])
		{
			if(validateParams($nv_params, 'callback'))
			{
				$nv_text = replaceParams($nv_params, 'callback');
			}
		}
		else
			$nv_errors[] = $nv_config['next_callback_msg'];
		
		
	}
	elseif(isset($_POST['submit_bpc']))
	{
		$nv_successMsg = $nv_config['success_msg_bpc'];
		
		if(validateParams($nv_params, 'bpc'))
		{
			$nv_text = replaceParams($nv_params, 'bpc');
		}
	}
	else
	{
		$nv_errors[] = 'неверный действие';
	}
	
	if(!$nv_errors)
	{
		if(sendSms($nv_text))
		{
			$nv_result['success'] = $nv_successMsg;
		}
	}
	
	$nv_result['error'] = $nv_errors;
	
	die(json_encode($nv_result));
}

if($_GET['action']=='cb')
{
	include($nv_root.'tpl_cb.php');	
}
elseif($_GET['action']=='bpc')
{
	include($nv_root.'tpl_bpc.php');
}


function validateParams($params, $type)
{
	global $nv_errors;
	
	if(empty($params['name']))
		$nv_errors[] = 'укажите имя';
	
	if(empty($params['phone']))
		$nv_errors[] = 'укажите телефон';
	
	if($type=='callback')
	{
		
	}
	elseif($type=='bpc')
	{
		if(empty($params['prod_name']))
			$nv_errors[] = 'не указано название товара';
		
		if(empty($params['prod_price']))
			$nv_errors[] = 'не указана цена товара';
	}
	
	if(!$nv_errors)
		return true;
}

function replaceParams($params, $type)
{
	global $nv_config;
	
	$text = '';
	
	if($type=='callback')
	{
		$text = str_replace(array('{name}', '{phone}'), array($params['name'], $params['phone']), $nv_config['text_cb']);
	}
	elseif($type=='bpc')
	{
		
		$text = str_replace(array('{name}', '{phone}'), array($params['name'], $params['phone']), $nv_config['text_bpc']);
		$text = str_replace(array('{prod_name}', '{prod_price}'), array($params['prod_name'], $params['prod_price']), $text);
	}
	
	return $text;	
}

function sendSms($text)
{
	global $nv_config, $nv_errors;
	
	$sms = new Smses( $nv_config['sms_login'], $nv_config['sms_pass'] );
	
	if($nv_config['debug'])
			$sms->debug = true;
	
	$sendResult = json_decode($sms->send( $nv_config['phone_admin'], $text, $nv_config['sender_id'] ), 1);
	
	if($sendResult['status']=='fail')
	{
		toLog($sendResult['error']);
		$nv_errors[] = $nv_config['smses_error'];
	}
	else
		return true;	
}

function toLog($text)
{
	global $logFile;
	
	$maxFileSize = 2*1024*1024;

	if(filesize($logFile)>$maxFileSize)
		$content = '';
  	else
  		$content = file_get_contents($logFile);
        	
    $time = date("d/m/y H:i:s",time());
    $content = "\r\n".$time.'  '.str_replace(array("\r", "\n"),' ', $text);
    
    if(file_put_contents($logFile, $content)===false)
    	die(json_encode(array('error'=>array('файл '.$logFile.' недоступен для записи'))));
    
}
?>