<?php
header('Content-type: application/json; charset=utf-8');
require_once("config.php");
//error_reporting(E_ERROR);
function toCSV(array $data, array $colHeaders = array(), $asString = false)
{
    $stream = ($asString)
        ? fopen("php://temp/maxmemory", "w+")
        : fopen("php://output", "w");

    if (!empty($colHeaders)) {
        fputcsv($stream, $colHeaders);
    }

    foreach ($data as $record) {
        fputcsv($stream, $record);
    }

    if ($asString) {
        rewind($stream);
        $returnVal = stream_get_contents($stream);
        fclose($stream);
        return $returnVal;
    } else {
        fclose($stream);
    }
}

$action = strtolower($_GET['action']);

$dbLink = new mysqli(DB_HOST, DB_USER, DB_PWD, DB_NAME, DB_PORT);
if ($dbLink->connect_error) {
    if (isset($_GET["showerror"])) {
        die("连接失败：" . $dbLink->connect_error);
    }
}

switch ($action) {
    case "userinfo": {
            $page = $_GET['page'];
            $pageSize = $_GET['limit'];
            $min = ($page - 1) * $pageSize;
            $activityID = $_GET['activityID'];
            $sql = "SELECT  `user_id`, `user_name`, `user_number`, `um`, `options`, `custom_input`, `status`, `prize` FROM `pingan_user_info` WHERE `activity_id` = $activityID limit " . $min . ',' . $pageSize;

            $queryResult = $dbLink->query($sql);
            $userInfo = array();
            $resultCount = 0;
            if ($queryResult != false) {
                $userInfo = $queryResult->fetch_all(MYSQLI_ASSOC);
                $queryResult->free();
            }

            //获取奖品列表
            $prizeCfg = [];
            $prizeSql = "SELECT `order`, `prize_name` FROM `pingan_prize_config` WHERE `activity_id` = $activityID ORDER BY `order` ASC";
            //echo $prizeSql;
            $prizeResult = $dbLink->query($prizeSql);
            while ($prizeData = $prizeResult->fetch_assoc()) {
                $prizeCfg[$prizeData['order']] = $prizeData['prize_name'];
            }
            $prizeResult->free();

            for ($i = 0; $i < count($userInfo); ++$i) {
                $userInfo[$i]['prize'] = intval($userInfo[$i]['prize']) > 0 ? $prizeCfg[$userInfo[$i]['prize']] : "未抽奖";
            }
            $sqlCount = "SELECT  COUNT(*) as cnt FROM `pingan_user_info` WHERE `activity_id` = $activityID";
            $queryResult = $dbLink->query($sqlCount);
            if ($queryResult != false) {
                $resultCount = $queryResult->fetch_assoc();
                $queryResult->free();
            }

            $data = [
                'code' => 0,
                'msg' => "",
                "count" => $resultCount['cnt'],
                'data' => $userInfo
            ];
            echo json_encode($data);
        }
        break;

    case "prizeconfig": {
            $page = $_GET['page'];
            $pageSize = $_GET['limit'];
            $min = ($page - 1) * $pageSize;

            $activityID = $_GET['activityID'];
            $sql = "SELECT  `id`, `order`, `prize_type`, `prize_name`, `prize_img`, `prize_rate`, `sum`, `cur` FROM `pingan_prize_config` WHERE `activity_id` = $activityID limit " . $min . ',' . $pageSize;

            $queryResult = $dbLink->query($sql);
            $userInfo = array();
            $resultCount = 0;
            if ($queryResult != false) {
                $userInfo = $queryResult->fetch_all(MYSQLI_ASSOC);
                $queryResult->free();
            }

            $sqlCount = "SELECT  COUNT(*) as cnt FROM `pingan_prize_config` WHERE `activity_id` = $activityID";
            $queryResult = $dbLink->query($sqlCount);
            if ($queryResult != false) {
                $resultCount = $queryResult->fetch_assoc();
                $queryResult->free();
            }

            $data = [
                'code' => 0,
                'msg' => "",
                "count" => $resultCount['cnt'],
                'data' => $userInfo
            ];
            echo json_encode($data);
        }
        break;

    case "modifyitem": {
            $itemID = $_POST['itemID'];
            $sum = $_POST['sum'];
            $rate = $_POST['rate'];
            $type = $_POST['type'];
            $name = $_POST['name'];

            $updateSql = 'UPDATE `pingan_prize_config` SET `sum` = ?, `prize_rate` = ?, `prize_name` = ?, `prize_type` = ? WHERE `id` = ?';
            if (!($stmt = $dbLink->prepare($updateSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("idssi", $sum, $rate, $name, $type, $itemID);
            $stmt->execute();

            echo json_encode(array("code" => 200));
        }
        break;

    case "getconfig": {
            $sql = "SELECT  `id`, `key`, `value` FROM `pingan_config` ";

            $queryResult = $dbLink->query($sql);
            $userInfo = array();
            $resultCount = 0;
            if ($queryResult != false) {
                $userInfo = $queryResult->fetch_all(MYSQLI_ASSOC);
                $queryResult->free();
            }

            echo json_encode(array("code" => 200, "data" => $userInfo));
        }
        break;

    case "modifyconfig": {
            $key = $_POST['key'];
            $value = $_POST['value'];

            $updateSql = 'UPDATE `pingan_config` SET `value` = ? WHERE `key` = ?';
            if (!($stmt = $dbLink->prepare($updateSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("ss", $value, $key);
            $stmt->execute();

            echo json_encode(array("code" => 200));
        }
        break;

    case "export": {
            $activityID = $_GET['activityID'];
            $sql = "SELECT  `user_id`, `user_name`, `user_number`, `options`, `custom_input`, `prize` FROM `pingan_user_info` WHERE `activity_id` = $activityID";
            $queryResult = $dbLink->query($sql);
            $userInfo = array();
            if ($queryResult != false) {
                $userInfo = $queryResult->fetch_all(MYSQLI_ASSOC);
                $queryResult->free();
            }

            header("Content-type:text/csv");
            header("Content-Disposition:attachment;filename=用户列表.csv");
            header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
            header('Expires:0');
            header('Pragma:public');
            toCSV($userInfo, ['用户ID', '员工姓名', '员工工号', '选择题', '问答题', '中奖奖品ID']);
        }
        break;
	
	case "getallusers": {
            $activityID = $_GET['activityID'];
            $sql = "SELECT  `user_id`, `user_name`, `user_number`, `um`, `options`, `custom_input`, `prize` FROM `pingan_user_info` WHERE `activity_id` = $activityID";
            $queryResult = $dbLink->query($sql);
            $userInfo = array();
            if ($queryResult != false) {
                $userInfo = $queryResult->fetch_all(MYSQLI_ASSOC);
                $queryResult->free();
            }

			//获取奖品列表
            $prizeCfg = [];
            $prizeSql = "SELECT `order`, `prize_name` FROM `pingan_prize_config` WHERE `activity_id` = $activityID ORDER BY `order` ASC";
            //echo $prizeSql;
            $prizeResult = $dbLink->query($prizeSql);
            while ($prizeData = $prizeResult->fetch_assoc()) {
                $prizeCfg[$prizeData['order']] = $prizeData['prize_name'];
            }
            $prizeResult->free();

            for ($i = 0; $i < count($userInfo); ++$i) {
                $userInfo[$i]['prize'] = intval($userInfo[$i]['prize']) > 0 ? $prizeCfg[$userInfo[$i]['prize']] : "未抽奖";
            }
           echo json_encode(array("code" => 200, 'data'=>$userInfo));
        }
        break;
		
    case "resetdata": {
            $activityID = $_GET['activityID'];
            $sql = "UPDATE `pingan_prize_config` SET `cur` = 0 WHERE `activity_id` = $activityID";
            $dbLink->query($sql);

            $sql = "UPDATE `pingan_user_info` SET `status` = 0, `options` = NULL, `custom_input` = NULL, `prize` = 0  WHERE `activity_id` = $activityID";
            $dbLink->query($sql);
            echo json_encode(array("code" => 200, "msg" => $sql));
        }
        break;

    case "activitylist": {
            $page = $_GET['page'];
            $pageSize = $_GET['limit'];
            $min = ($page - 1) * $pageSize;

            $sql = "SELECT  `id`, `activity_name`, `activity_tips`, `bg_img`, `title_img` FROM `pingan_activity_list` limit " . $min . ',' . $pageSize;

            $queryResult = $dbLink->query($sql);
            $userInfo = array();
            $resultCount = 0;
            if ($queryResult != false) {
                $userInfo = $queryResult->fetch_all(MYSQLI_ASSOC);
                $queryResult->free();
            }

            $sqlCount = "SELECT  COUNT(*) as cnt FROM `pingan_activity_list` ";
            $queryResult = $dbLink->query($sqlCount);
            if ($queryResult != false) {
                $resultCount = $queryResult->fetch_assoc();
                $queryResult->free();
            }

            $data = [
                'code' => 0,
                'msg' => "",
                "count" => $resultCount['cnt'],
                'data' => $userInfo
            ];
            echo json_encode($data);
        }
        break;

    case "modifyactivity": {
            $activityID = $_POST['activityID'];
            $activityName = $_POST['activityName'];
            $activityTips = $_POST['activityTips'];

            $updateSql = 'UPDATE `pingan_activity_list` SET `activity_name` = ?, `activity_tips` = ? WHERE `id` = ?';
            if (!($stmt = $dbLink->prepare($updateSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("ssi", $activityName, $activityTips, $activityID);
            $stmt->execute();

            echo json_encode(array("code" => 200));
        }
        break;

    case "delactivity": {
            $activityID = $_POST['activityID'];

            $delSql = 'DELETE FROM `pingan_activity_list` WHERE `id` = ?';
            if (!($stmt = $dbLink->prepare($delSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("i", $activityID);
            $stmt->execute();

            $delSql = 'DELETE FROM `pingan_prize_config` WHERE `activity_id` = ?';
            if (!($stmt = $dbLink->prepare($delSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("i", $activityID);
            $stmt->execute();
            echo json_encode(array("code" => 200));
        }
        break;

    case "addactivity": {
            $activityName = $_POST['activityName'];
            $activityTips = $_POST['activityTips'];

            $insertSql = 'INSERT INTO `pingan_activity_list`(`activity_name`, `activity_tips`) VALUES (?, ?)';
            if (!($stmt = $dbLink->prepare($insertSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("ss", $activityName, $activityTips);
            $stmt->execute();

            $activityID = mysqli_insert_id($dbLink);

            $insertSql = "";
            for ($i = 1; $i <= 8; $i++) {
                $prize = "奖品" . $i;
				$type = "奖项" . $i;
                $insertSql = "INSERT INTO `pingan_prize_config`(`order`, `activity_id`, `prize_name`, `prize_type`) VALUES ($i, $activityID, '$prize', '$type')";
                $dbLink->query($insertSql);
            }

            echo json_encode(array("code" => 200));
        }
        break;

    case "getquestionlist": {
            $page = $_GET['page'];
            $pageSize = $_GET['limit'];
            $min = ($page - 1) * $pageSize;
            $activityID = intval($_GET['activityID']);
            $sql = "SELECT  `id`, `order`, `activity_id`, `type`, `question`, `options`, `answer` FROM `pingan_question_list` WHERE `activity_id` = $activityID limit " . $min . ',' . $pageSize;

            $queryResult = $dbLink->query($sql);
            $userInfo = array();
            $resultCount = 0;
            if ($queryResult != false) {
                $userInfo = $queryResult->fetch_all(MYSQLI_ASSOC);
                $queryResult->free();
            }

            $sqlCount = "SELECT  COUNT(*) as cnt FROM `pingan_question_list` WHERE `activity_id` = $activityID";
            $queryResult = $dbLink->query($sqlCount);
            if ($queryResult != false) {
                $resultCount = $queryResult->fetch_assoc();
                $queryResult->free();
            }

            $data = [
                'code' => 0,
                'msg' => "",
                "count" => $resultCount['cnt'],
                'data' => $userInfo
            ];
            echo json_encode($data);
        }
        break;

    case "addquestion": {
            $activityID = intval($_POST['activityID']);
            $order = intval($_POST['order']);
            $curQuestionType = intval($_POST['type']);
            $question = strval($_POST['question']);
            $options = strval($_POST['options']);
            $answers = strval($_POST['answers']);

            $options = $options == "" ? null : $options;
            $answers = $answers == "" ? null : $answers;

            $insertSql = 'INSERT INTO `pingan_question_list`(`order`, `activity_id`, `type`, `question`, `options`, `answer`) VALUES (?, ?, ?, ?, ?, ?)';
            if (!($stmt = $dbLink->prepare($insertSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("iiisss", $order, $activityID, $curQuestionType, $question, $options, $answers);
            $ret = $stmt->execute();

            echo json_encode(array("code" => 200, 's' => $answers));
        }
        break;

    case "modifyquestion": {
            $questionID = intval($_POST['questionID']);
            $activityID = intval($_POST['activityID']);
            $order = intval($_POST['order']);
            $type = intval($_POST['type']);
            $question = strval($_POST['question']);
            $options = strval($_POST['options']);
            $answers = strval($_POST['answers']);

            $options = $options == "" ? null : $options;
            $answers = $answers == "" ? null : $answers;
            $updateSql = 'UPDATE `pingan_question_list` SET `order` = ?, `type` = ?, `question` = ?, `options` = ?, `answer` = ? WHERE `id` = ?';
            if (!($stmt = $dbLink->prepare($updateSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("iisssi", $order, $type, $question, $options, $answers, $questionID);
            $stmt->execute();

            echo json_encode(array("code" => 200, 'options' => $options, 'answers' => $answers));
        }
        break;

    case "delquestion": {
            $questionID = $_POST['questionID'];

            $delSql = 'DELETE FROM `pingan_question_list` WHERE `id` = ?';
            if (!($stmt = $dbLink->prepare($delSql))) {
                echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
            }
            $stmt->bind_param("i", $questionID);
            $stmt->execute();

            echo json_encode(array("code" => 200));
        }
        break;

	case "uploadimg": {
			$data = array(
				"code" => 200,
				"msg" => ""
			);
			$activityID = intval($_POST['activityID']);
			$prizeID = intval($_POST['id']);
			$imgFile = $_FILES["prizeImg"];
			$imgType = $_POST['img'];
			$upType = $_POST['type'];
			
			if(empty($imgFile)){
				$data['code'] = 1;
				$data['msg'] = "未获取到上传文件";
				exit(json_encode($data));
			}
			
			$picname = $imgFile["name"];
			$picsize = $imgFile["size"];
			
			if($picsize > 1*1024*1024){
				$data['code'] = 1;
				$data['msg'] = "图片大小不能超过1MB 请重新选择";
				exit(json_encode($data));
			}
			
			$type = strstr($picname, ".");
			if($type!=".png"){
				$data['code'] = 2;
				$data['msg'] = "请上传png格式的图片";
				exit(json_encode($data));
			}
			
			$rootDir = 'LotteryCustomImg';
			if($upType == "prize")
			{
				$newPicName = $activityID . '_' . $prizeID . '_' . time() . '_' . rand(1,9999).$type;//1970-1-1
			}
			else{
				$newPicName = $activityID . '_' . $imgType . '_' . time() . '_' . rand(1,9999).$type;//1970-1-1
			}
			
			$dateFolderName = date("Y_m_d");
			$targetDir = SAVE_ROOT_PATH . $rootDir . '/' . $dateFolderName . '/';
			if(!is_dir($targetDir))
			{
				$succ = mkdir($targetDir, 0755, true);
				if(!$succ)
				{
					$data['code'] = 3;
					$data['msg'] = "创建目录" . $targetDir . "失败";
					exit(json_encode($data));
				}
			}
			
			$targetFile = $targetDir . $newPicName;
			$saveRet = move_uploaded_file($imgFile['tmp_name'], $targetFile);
			
			if($saveRet == true) {
				$dbPath = $rootDir . '/' . $dateFolderName . '/' . $newPicName;
				
				if($upType == "prize")
				{
					$updateSql = 'UPDATE `pingan_prize_config` SET `prize_img` = ? WHERE `id` = ?';
					if (!($stmt = $dbLink->prepare($updateSql))) {
						echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
					}
					$stmt->bind_param("si", $dbPath, $prizeID);
					$stmt->execute();
				}
				else{
					$updateSql = 'UPDATE `pingan_activity_list` SET `bg_img` = ? WHERE `id` = ?';
					if($imgType == 'title')
					{
						$updateSql = 'UPDATE `pingan_activity_list` SET `title_img` = ? WHERE `id` = ?';
					}
					if (!($stmt = $dbLink->prepare($updateSql))) {
						echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
					}
					
					$stmt->bind_param("si", $dbPath, $activityID);
					$stmt->execute();
				}
			
				$data['code'] = 200;
				$data['msg'] = "上传成功";
				$data['url'] = URL_FOR_SAVE_PATH . $dbPath;
			}else{
				$data['code'] = 4;
				$data['msg'] = "保存图片失败：" . $targetFile;
			}
			echo json_encode($data);
		}
		break;
	
	case "delimg": {
			$activityID = intval($_POST['activityID']);
			$prizeID = intval($_POST['itemID']);
			$type = ($_POST['type']);
			
			$data = array(
				"code" => 200,
				"msg" => ""
			);

			if($type == 'prize')
			{
				$updateSql = 'UPDATE `pingan_prize_config` SET `prize_img` = ? WHERE `id` = ?';
				if (!($stmt = $dbLink->prepare($updateSql))) {
					echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
				}
				
				$c = null;
				$stmt->bind_param("si", $c, $prizeID);
				$stmt->execute();
			}
			else
			{
				$imgIdx = intval($_POST['imgIdx']);
				$updateSql = 'UPDATE `pingan_activity_list` SET `bg_img` = ? WHERE `id` = ?';
				if($imgIdx == 2)
				{
					$updateSql = 'UPDATE `pingan_activity_list` SET `title_img` = ? WHERE `id` = ?';
				}
				if (!($stmt = $dbLink->prepare($updateSql))) {
					echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
				}
				
				$img = null;
				$stmt->bind_param("si", $img, $activityID);
				$stmt->execute();
			}
			
			echo json_encode($data);
		}
		break;
		
    default:
        echo 'failed';
        break;
}
