<?php require_once("../../db.php"); ?>
<?php 
	
	try {
		$core = Core::getInstance();
		$stmt_prep = $core->dbh->prepare("SELECT * FROM myclients WHERE client_id = :client_id");
		$stmt_prep -> bindParam("client_id", $_POST["inp_rnd_clientID"]);
		$stmt_prep -> execute();
		$row_count_prep = $stmt_prep -> rowCount();
		
		if ($row_count_prep < 1) {
			die('{"send":"false","reason":"Ne postoji odabrani klijent kojim se šalje. Odaberite korisnika kojem šaljete poruku."}');
		}
	} catch(PDOException $pe) {
		trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);		
	}
	

	if (in_array($_POST["sel_rnd_quantity"], $cf_rnd_select)) {
		for ($i = 0; $i < $_POST["sel_rnd_quantity"]; $i++) {
			$random_string = generateRandomString($cf_rnd_length);
			try {
			
				//sel_rnd_quantity, inp_rnd_clientID
			
				$core = Core::getInstance();
				$stmt = $core->dbh->prepare("INSERT INTO messages (mess_client_id, mess_message, mess_whosent) values (:mess_client_id, :mess_message, :mess_whosent)");
				$mess_whosent = "1";
				$stmt -> bindParam("mess_client_id", $_POST["inp_rnd_clientID"], PDO::PARAM_INT);
				$stmt -> bindParam("mess_message", $random_string, PDO::PARAM_STR);
				$stmt -> bindParam("mess_whosent", $mess_whosent, PDO::PARAM_STR);
				
				
				$stmt -> execute();
				$row_count = $stmt -> rowCount();
				
				if ($row_count > 0) {
					// echo "true";
					$last_insert_id = $core->dbh->lastInsertId();
					$client_number = getClientNumber($_POST["inp_rnd_clientID"]);
					pushSMS($_GET["ag"], $client_number, $random_string, $last_insert_id);
				}
				
				
			} catch(PDOException $pe) {
				
				trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
				
			}
			
			sleep($cf_rnd_sleep);
		}
	} else {
		die('{"send":"false","reason":"Error with input random value"}');
	}
?>