<?php
//²¹Áì°ô°ôÌÇ
require 'common.php';

$act=daddslashes($_GET['act']);
$key=isset($_POST['key'])?daddslashes($_POST['key']):exit('{"code":-1}');

$week=strftime("%U");

switch($act){

case 'buy':
	$user=isset($_POST['user'])?daddslashes($_POST['user']):exit('{"code":-2}');
	$pwd=isset($_POST['pass'])?daddslashes($_POST['pass']):exit('{"code":-3}');

	$kmrow=$DB->get_row("SELECT * FROM qiu_kms WHERE km='$key' and kind=2 limit 1");
	if(!$kmrow['id'])
		exit('{"code":-4}');
	if($kmrow['isuse']==1)
		exit('{"code":-5}');

	$row=$DB->get_row("SELECT * FROM qiu_shop WHERE user='$user' and pwd='$pwd' order by id desc limit 1");
	if($row && $row['week']==$week){
		if($row['value']==30 && $row['zt']==4){
			exit('{"code":9}');
		}elseif($row['value']<30 && $row['zt']==4 && $kmrow['value']>$row['value']){
			$DB->query("update qiu_kms set isuse='1',user='$user',usetime='$date' where id='{$kmrow['id']}'");
			if(!$DB->query("update qiu_shop set value='{$kmrow['value']}',`key`='{$key}',zt=1 where id='{$row['id']}'"))exit('{"code":-9}');
			exit('{"count":"'.$kmrow['value'].'","code":0}');
		}else{
			exit('{"code":'.$row['zt'].'}');
		}
	}else{
		$DB->query("update qiu_kms set isuse='1',user='$user',usetime='$date' where id='{$kmrow['id']}'");
		if(!$DB->query("insert into `qiu_shop` (`user`,`pwd`,`value`,`week`,`key`,`addtime`,`zt`) values ('".$user."','".$pwd."','".$kmrow['value']."','".$week."','".$key."','".$date."','1')"))exit('{"code":-9}');
		exit('{"count":"'.$kmrow['value'].'","code":0}');
	}

break;

case 'query':
	$kmrow=$DB->get_row("SELECT * FROM qiu_kms WHERE km='$key' and kind=2 limit 1");
	if(!$kmrow['id'])
		exit('{"code":-4}');

	$row=$DB->get_row("SELECT * FROM qiu_shop WHERE `key`='$key' order by id desc limit 1");
	if(!$row['id'])
		exit('{"code":10}');
	else
		exit('{"code":'.$row['zt'].'}');

break;

default:
	exit('{"code":-9}');
break;
}