<?php
date_default_timezone_set("Asia/Bangkok");
define('APP', 'mybot');


function _connectDB(){
	$host = "public.05z3l.bkk1.database-hosting.webstarterz.com";
	$username = "05z3l_linebot2";
	$password = "@Anont0811045107";
	$database = '05z3l_linebot';
	// $host = "localhost";
	// $username = "mybot2";
	// $password = "@mybot51724666";
	// $database = "mybot";
	$connect = mysqli_connect($host,$username,$password,$database);
	return $connect;
}

//สำคัญ-------------------------------------------------
function encode($string,$key) {
    $key = sha1($key);
    $strLen = strlen($string);
    $keyLen = strlen($key);
    $j=0;$hash = '';
    for ($i = 0; $i < $strLen; $i++) {
        $ordStr = ord(substr($string,$i,1));
        if ($j == $keyLen) { $j = 0; }
        $ordKey = ord(substr($key,$j,1));
        $j++;
        $hash .= strrev(base_convert(dechex($ordStr + $ordKey),16,36));
    }
    return $hash;
}
//สำคัญ
function decode($string,$key) {
    $key = sha1($key);
    $strLen = strlen($string);
    $keyLen = strlen($key);
    $j=0;$hash = '';
    for ($i = 0; $i < $strLen; $i+=2) {
        $ordStr = hexdec(base_convert(strrev(substr($string,$i,2)),36,16));
        if ($j == $keyLen) { $j = 0; }
        $ordKey = ord(substr($key,$j,1));
        $j++;
        $hash .= chr($ordStr - $ordKey);
    }
    return $hash;
}
//---------------------------------------------------

function get_notify(){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM notify ";//WHERE n_id=101";
	$result = $con->query($sql);
	$json = [];
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       array_push($json, $row);
	    }
	} else {
	    echo "ยังไม่มีห้อง";
	}
	$con->close();
	return $json;
}

function get_notify_find($token){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM notify WHERE n_cliend_id= '".$token."'";
	$result = $con->query($sql);
	$n_client_secret = '';
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       $n_client_secret = $row['n_client_secret'];
	    }
	} else {
	    echo "ไม่มีข้อมูล";
	}
	$con->close();
	return $n_client_secret;
}


function update_notify_bot($token){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "UPDATE `05z3l_linebot`.`notify` SET `n_online`=`n_online`+1  WHERE n_cliend_id= '".$token."'";
	$result = $con->query($sql);
	$con->close();
	return $result;
}


function add_notify_token($token){
	$con = _connectDB();
	$ID='';
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = " SET @nf_key = 1 ;
			 SELECT nf_key INTO @nf_key FROM notify_token ORDER BY nf_key DESC  LIMIT 1;
			 INSERT INTO notify_token (nf_key,nf_code,nf_token,nf_client_id) VALUES (@nf_key+1, '3216', '32165', '654654');
			 SELECT @nf_key+1;
			 ";
	if ($con -> multi_query($sql)) {
	  do {
	    if ($result = $con->store_result()) {
	      while ($row = $result->fetch_row()) {
	        $ID = $row[0];
	      }$result->free_result();
	    }
	    if ($con->more_results()) {  }
	  } while ($con->next_result());
	}
	$con->close();
	return $ID;
}



// SN 16.01.63 AP
function insert_notify_temp($name,$code,$token){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "INSERT INTO `05z3l_linebot`.`notify_temp` (n_name,`n_code`, `n_token`) VALUES ('".$name."','".$code."', '".$token."');";
	$result = $con->query($sql);
	$con->close();
	return $result;
}
// EN 16.01.63 AP


// SN 16.01.63 AP
function get_unregister(){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM notify_login WHERE n_register ='UNREGISTER' Order By n_no desc;";
	$result = $con->query($sql);
	$json = [];
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       array_push($json, $row);
	    }
	} else {
	    echo "ยังไม่มีห้อง";
	}
	$con->close();
	return $json;
}
// EN 16.01.63 AP



// SN 18.01.63 AP
function insert_notify_all($groupid,$name,$token,$code,$state){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "UPDATE  notify_login SET n_name='".$name."',n_notify_token='".$token."',n_code='".$code."',n_state='".$state."',n_register='REGISTER' WHERE n_groupid='".$groupid."';";
	$result = $con->query($sql);

	$sql_2 = "INSERT INTO groupline (groupline_name,groupline_api_key,groupline_key_notify,groupline_products,groupline_version)
	VALUES ('".$name."','".$groupid."','".$token."','ALL','V1')";
	$con->query($sql_2);
	
	$con->close();
	return $result;
}
// EN 18.01.63 AP


function testToken_show($TOKEN){
	$URL = 'https://notify-api.line.me/api/notify';
	$MESSAGE = $_POST['msg'];
	$query = http_build_query(['message' => $MESSAGE], '', '&');
	$header = [
	    'http' => [
	        'method' => 'POST',
	        'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL
	            . 'Authorization: Bearer ' . $TOKEN . PHP_EOL
	            . 'Content-Length: ' . strlen($query) . PHP_EOL,
	        'content' => $query
	    ]
	];
	$context = stream_context_create($header);
	$output = file_get_contents($URL, false, $context);
	$result = json_decode($output);
	if($result->status == 200){
	?>
		<div class="alert alert-success" role="alert">
  			ส่งข้อความสำเร็จ
		</div>
	<?php
	}else{
		?>
		<div class="alert alert-danger" role="alert">
  			ไม่สำเร็จ กรุณาดึงบอทเข้ากลุ่มก่อน
  			<br><a href="https://line.me/R/ti/p/%40linenotify">บอท Notify</a>
		</div>		
		<?php
	}
}


// SN 21.01.63 AP
function update_notify_time($post){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$category = $post['category'];
	$access_token = $_SESSION['access_token'];
	$License = date('ymd').rand(1234,9876);// create license
	$sql = "UPDATE groupline SET groupline_alldate=".$category.",groupline_countdown=".$category.",groupline_keycode='".$License."'  WHERE groupline_api_key= '".$_SESSION['groupId']."'";
	$result = $con->query($sql);
	$con->close();
	return $result;
}
// EN 21.01.63 AP


// SN 21.01.63 AP
function get_last_item(){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM groupline WHERE groupline_api_key='".$_SESSION['groupId']."'";
	$result = $con->query($sql);
	$json = [];
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       array_push($json, $row);
	    }
	} else {
	    echo "ยังไม่มีห้อง";
	}
	$con->close();
	return $json;
}
// EN 21.01.63 AP

// SN 21.01.63 AP
function get_last_item_all(){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM groupline WHERE groupline_api_key != '' ORDER BY groupline_id DESC LIMIT 20";
	$result = $con->query($sql);
	$json = [];
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       array_push($json, $row);
	    }
	} else {
	    echo "ยังไม่มีห้อง";
	}
	$con->close();
	return $json;
}
// EN 21.01.63 AP

// SN 21.01.63 AP
function get_last_item_find($search){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM groupline  WHERE (groupline_encode LIKE '%".$search."%' OR groupline_keycode LIKE '%".$search."%') AND groupline_api_key != '' ORDER BY groupline_id DESC LIMIT 50";
	$result = $con->query($sql);
	$json = [];
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       array_push($json, $row);
	    }
	} else {
	    echo "ยังไม่มีห้อง";
	}
	$con->close();
	return $json;
}
// EN 21.01.63 AP

// EN 22.01.63 AP
function _users_renew($mid,$renew){
	$con = _connectDB();
	// Check connection
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "UPDATE groupline SET groupline_countdown=(groupline_countdown+".$renew."),groupline_alldate=".$renew." WHERE groupline_api_key='".$mid."'";
	$result = $con->query($sql);
	$res = ['status'=>true];
	return $res;
}
// EN 22.01.63 AP

// EN 22.01.63 AP
function _users_modify($mid,$end){
	$con = _connectDB();
	// Check connection
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "UPDATE groupline SET groupline_countdown=".$end." WHERE groupline_api_key='".$mid."'";
	$result = $con->query($sql);
	$res = ['status'=>true];
	return $res;
}
// EN 22.01.63 AP



// SN 22.01.63 AP list_detail.php | require [GET mid]
function get_last_item_mid($mid){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM groupline  WHERE groupline_api_key = '".$mid."'";
	$result = $con->query($sql);
	$json = [];
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       array_push($json, $row);
	    }
	}
	$con->close();
	return $json;
}
// EN 22.01.63 AP


// SN 01.02.63 AP
function get_keynote(){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM keynote Order By k_id desc limit 20;";
	$result = $con->query($sql);
	$json = [];
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       array_push($json, $row);
	    }
	} else {
	    echo "ว่าง";
	}
	$con->close();
	return $json;
}
// EN 01.02.63 AP

// SN 01.02.63 AP
function get_keynote_item($id){
	$con = _connectDB();
	if ($con->connect_error) {
	    die("Connection failed: " . $con->connect_error);
	}
	$sql = "SELECT * FROM keynote WHERE k_id =".$id.";";
	$result = $con->query($sql);
	$json = [];
	if ($result->num_rows > 0) {
	    while($row = $result->fetch_assoc()) {
	       array_push($json, $row);
	    }
	} else {
	    echo "ว่าง";
	}
	$con->close();
	return $json;
}
// EN 01.02.63 AP

// EN 01.02.63 AP

// SN 01.02.63 AP
function insert_keynote($k_title,$k_text){
	$con = _connectDB();
	if ($con->connect_error) {die("Connection failed: " . $con->connect_error);}
	$sql = "INSERT INTO keynote (k_title,k_text) VALUES ('".$k_title."', '".$k_text."')";
	$result = $con->query($sql);
	$res = ['status'=>true];
	return $res;
}
// EN 01.02.63 AP

// SN 01.02.63 AP
function update_keynote($k_id,$k_title,$k_text){
	$con = _connectDB();
	if ($con->connect_error) {die("Connection failed: " . $con->connect_error);}
	$sql = "UPDATE keynote SET k_title='".$k_title."',k_text='".$k_text."' WHERE k_id=".$k_id.";";
	$result = $con->query($sql);
	$res = ['status'=>true];
	return $res;
}
// EN 01.02.63 AP
