<?php

include('core/function.php');

$input = input('ma');

if($input)
{
	# 到数据库中查询有没有这个防伪码吧
	$db = db();

	$result = $db->field('id,company,pass,code,num')
	    ->order('id desc')
	    ->where('pass = ' . $input)
	    ->limit(1,1)
	    ->select('data');

	if($result && isset($result[0]) && isset($result[0]['id']))
	{
		# 搜索到了
		# 查询次数+1
		$sql = 'update data set num = num+1 where id = ' . $result[0]['id'];
		$db->doSql($sql);

		$pass = sp($result[0]['pass'], 1);
		$code = sp($result[0]['code'], 1);

		$i = 0;
		foreach($pass as $k => $v)
		{
			$result[0]['txt'][$i] = color($v, $code[$k], $i);
			$i++;
		}

		$result[0]['txt'] = implode('', $result[0]['txt']);
	}

	$company = $db->field('*')
	    ->order('id desc')
	    ->where('id = 1')
	    ->limit(1,1)
	    ->select('company');

	if($company)
	{
		$result[0]['ts1'] = $company[0]['ts1'];
		$result[0]['ts2'] = $company[0]['ts2'];
	}
	else
	{
		$result[0]['ts1'] = '该防伪码存在！';
		$result[0]['ts2'] = '该防伪码不存在！';
	}
	
	$result[0]['next'] = '';
	
	$time = time()+3600*24*365;
	
	$key = 'numv1_' . $input;
	$key_time = $key . '_time';

	if(isset($_COOKIE[$key]) && $_COOKIE[$key] > 1)
	{
		$first = $_COOKIE[$key_time];
		if($first > 0)
		{
			$first = date('Y/m/d H:i:s', $first);
			$result[0]['ts1'] = '该防伪码已于' . $first . '第一次被查询，本次为第' . $_COOKIE[$key] . '次查询，谨防假冒！The first time to query ' . $first;
		} 
		else
		{
			$result[0]['ts1'] = '本次是您第'.$_COOKIE[$key].'次查询。';
		}
		
	}
	elseif(!isset($_COOKIE[$key]))
	{
		$_COOKIE[$key] = 1;
		setcookie($key_time, time(), $time);
	}
	
	setcookie($key, $_COOKIE[$key]+1, $time);
	
	$result[0]['search'] = $input;

	template('search', $result[0]);
	die;
}

template('index');