<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!is_https()) {
    echo "Sorry - Setup can't run - You are not using HTTPS. Please switch to HTTPS and run setup again.";
	exit();
}

if (isset($_POST["license_key"])) {

$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
$server_path = dirname($_SERVER['REQUEST_URI']);
$server_path = $server_path === '/' ? $server_path : $server_path . '/';
$server_name = $protocol . "://" . $_SERVER['HTTP_HOST'] . $server_path;
$license_key=trim($_POST['license_key']);
$ch = curl_init("https://eslcore.com/l/r.php?k=".$license_key."&u=".base64_encode($server_name)."&i=2");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$h = curl_exec($ch);
curl_close($ch);

 
if (substr($h, 0, 5)=="ERROR"){
	echo $h; 
	exit();
	}

extract($_POST);

define('USER_DB_HOST', $user_db_host);
define('USER_DB_NAME', $user_db_name);
define('USER_DB_CHARSET', 'utf8mb4');
define('USER_DB_USER', $user_db_user);
define('USER_DB_PASSWORD', $user_db_password);

try {
     $db = new PDO("mysql:dbname=".USER_DB_NAME.";host=".USER_DB_HOST, USER_DB_USER, USER_DB_PASSWORD );
     $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );//Error Handling
     $sql ="CREATE TABLE IF NOT EXISTS `categories` (
 `cat_id` int(11) NOT NULL AUTO_INCREMENT,
 `cat_userid` int(11) NOT NULL,
 `cat_name` text NOT NULL,
 `cat_created` datetime NOT NULL,
 PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `projects` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `project_name` text NOT NULL,
  `date_created` datetime NOT NULL,
  `last_edited` datetime NOT NULL,
  `category` int(11) NOT NULL DEFAULT 0,
  `tone` int(11) NOT NULL,
  `language` int(11) NOT NULL,
  `audience` text,
  `p1_input` text,
  `p1_content` text,
  `p2_input` text,
  `p2_content` text,
  `p3_input` text,
  `p3_content` text,
  `p4_input` text,
  `p4_content` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `users` (
 `user_id` bigint(20) NOT NULL AUTO_INCREMENT,
 `user_name` varchar(255) CHARACTER SET utf8 NOT NULL,
 `user_email` varchar(255) CHARACTER SET utf8 NOT NULL,
 `user_password` varchar(255) CHARACTER SET utf8 NOT NULL,
 `user_logins` bigint(20) NOT NULL,
 `user_apikey` varchar(255) CHARACTER SET utf8 NOT NULL,
 `user_status` int(11) NOT NULL,
 `user_creation` datetime NOT NULL,
 `user_lastlogin` datetime NOT NULL,
 `user_txid_wplus` text,
 `user_txid_jvzoo` text,
 PRIMARY KEY (`user_id`),
 UNIQUE KEY `user_email` (`user_email`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

			";
     $db->exec($sql);
	 $db=null;
} catch(PDOException $e) {
    echo "DATABASE ERROR : ".$e->getMessage();
	die();
}

$configout=<<<EOT
<?php
\$version='1.0';
\$sitename='$sitename';
\$termslink='$termslink';
\$supportlink='$supportlink';
\$supportemail='$supportemail';
\$l1='$license_key';
\$l2='$h';
\$logo='img/logo.png';
\$masterkeymode=$masterkeymode;
\$masterapikey='$masterapikey';
\$logoutredirect='$logoutredirect';
\$adminuser='$adminuser';
\$adminpassword='$adminpassword';
\$aiengine='0';
\$wpluskey='';
\$jvzkey='';
\$supportlinkcode='';
if (\$supportlink!=''){\$supportlinkcode.='Support Link : Click <a href="'.\$supportlink.'" target="_BLANK">HERE</a>';}
if (\$supportlink!='' && \$supportemail!=''){\$supportlinkcode.=' - ';}
if (\$supportemail!=''){\$supportlinkcode.='Support Email : <a href="mailto:'.\$supportemail.'">'.\$supportemail.'</a>';}
\$termscode='';
if(\$termslink!=''){\$termscode='- For terms click <a href="'.\$termslink.'" target="_BLANK">HERE</a>';}
\$footer=<<<EOTFOOTER
<div style="color:#777; font:size:14px; display:block; float:left;">(C)2023 \$sitename \$termscode</div><div style="color:#777; float:right">\$supportlinkcode</div>
EOTFOOTER;

define('USER_DB_HOST', '$user_db_host');
define('USER_DB_NAME', '$user_db_name');
define('USER_DB_CHARSET', 'utf8mb4');
define('USER_DB_USER', '$user_db_user');
define('USER_DB_PASSWORD', '$user_db_password');
?>
EOT;


file_put_contents("config.php",$configout);
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$domainName = $_SERVER['HTTP_HOST'];
	$scriptPath = dirname($_SERVER['PHP_SELF']);

	$urlhere = $protocol . $domainName . $scriptPath . '/';
	$register=$urlhere."register.php";
	$admin=$urlhere."admin.php";
	$login=$urlhere."login.php";
	echo ('<div style="font-family:Sans-Serif; border:2px solid #444; background:#EEE; width:400px; padding:20px; margin:0 auto; border-radius:5px; margin-top:100px;">Congratulations! Your software is ready to use!<br><br>You can create your first user account here : <a href="'.$register.'">'.$register.'</a><br><br>You can login as a user here : <a href="'.$login.'">'.$login.'</a><br><br>You can login to the admin interface here : <a href="'.$admin.'">'.$admin.'</a><br><br></div>');
	@unlink("setup.php");
	@unlink("upgrade.php");
	@unlink("SETUP_imgup.php");
	exit();
	
}

function is_https() {
    if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ||
        (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) {
        return true;
    } else {
        return false;
    }
}

?>
<!doctype HTML>
<html>
<head>
<title></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"> 
<style>
* {
  font-family: 'Roboto', Arial, Helvetica, sans-serif;
  box-sizing: border-box;
  color: #6f6f6f;
  font-size:14px;
}


#notify {
  background: #ffd9e3;
  padding: 10px;
  margin-bottom: 10px;
}


#setup {
  max-width: 900px;
  border: 1px solid #ddd;
  background: #f2f2f2;
  margin: 0 auto;
  padding: 20px;
  margin-top:20px;
  margin-bottom:20px;
}
#setup h2 {
  color: #6f6f6f;
  padding: 0;
  margin: 0 0 10px 0;
}
#setup label, #setup input, #setup textarea, #setup select, #setup button {
  width: 100%;
  margin: 10px 0;
}
#setup input, #setup textarea, #setup select, #setup button {
  padding: 10px;
  border:none;
  outline:1px solid #BBBBBB;
  border-radius:3px;
}
#setup input[type=submit] {
  background: #4f69db;
  color: #fff;
  border: 0;
  cursor: pointer;
}

#setup button {
  background: #1bb3f5;
  color: #fff;
  border: 0;
  width:200px;
  cursor: pointer;
}

.center {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
}	
</style>
</head>
<body>
    <form id="setup" method="post">
    <form id="setup" method="post">
		<div style="text-align:center; margin-top:10px;"><h2 style="font-size:18px" >Setup - Please complete the form / upload your logo and press GO.
		<br><br>
		If you need support please contact us here : <a href="https://inspiredsoft.freshdesk.com/support/home" target="_BLANK">https://inspiredsoft.freshdesk.com/support/home</a>
		</h2></div>
		<br>
		License Key
		<input type="text" name="license_key" value="" placeholder="XXXXX-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" required>
		Upload Logo (PNG only - recommended size 500px X 120px)
		<div style="display: flex; align-items: center;">
			<input type="file" id="fileUpload" name="fileUpload" style="display: none;" />
			<button onclick="document.getElementById('fileUpload').click();">Upload</button>
			<img id="preview" style="cursor:pointer; margin-left:10px; height: 40px; transition: all 0.5s;" src="#" alt="Image preview..." hidden/>
		</div>
		Database Host (usually "localhost")
		<input type="text" name="user_db_host" value="localhost" required>
		Database Name
		<input type="text" name="user_db_name" placeholder="database_name" required>
		Database User
		<input type="text" name="user_db_user" placeholder="database_user" required>
		Database Password
		<input type="text" name="user_db_password" placeholder="database_password" required>
		Site Name (Site Name for your title tag - Letters/Numbers only)
		<input type="text" name="sitename" pattern="[a-zA-Z0-9 ]+" placeholder="Your Site Name">
		Logout Redirect (Link to go to when user logs out - leave at login.php if you want to return to login screen)
		<input type="text" name="logoutredirect" value="login.php">
		Admin Username
		<input type="text" name="adminuser" value="admin" required>
		Admin Password
		<input type="text" name="adminpassword" value="" required>
		Link to your terms (leave blank if you have none)
		<input type="text" name="termslink" placeholder="https://mytermslink.com">
		Link to your support desk (leave blank if you have none)
		<input type="text" name="supportlink" placeholder="https://mysupportlink.com">
		Support email address (leave blank if you have none)
		<input type="text" name="supportemail" placeholder="support@mysupport.com">
		Use My OpenAI API Key (select "No" to make end user enter their own key - recommended)<br>
		<select name="masterkeymode" required style="width:80px">
			<option value="true">Yes</option>
			<option value="false" selected="selected">No</option>
		</select><br>
		OpenAI Key (Enter your key here only if you don't want individual use API keys):
		<input type="text" name="masterapikey" placeholder="Your API Key" >		
		<input type="submit" value="Go">
    </form>

<script>
    document.getElementById('fileUpload').addEventListener('change', uploadFile);
	document.getElementById('preview').addEventListener('mouseover', function() {
	  this.style.height = '160px';
	});
	document.getElementById('preview').addEventListener('mouseout', function() {
	  this.style.height = '40px';
	});		
	function uploadFile() {
		let fileInput = document.getElementById('fileUpload');
		let file = fileInput.files[0];
		let formData = new FormData();
		formData.append('file', file);
		fetch('SETUP_imgup.php', {
			method: 'POST',
			body: formData
		})
		.then(response => response.json())
		.then(data => {
			if (data.status === 'success') {
				alert('Upload successful: ' + data.message);
				let preview = document.getElementById('preview');
				preview.src = URL.createObjectURL(file);
				preview.hidden = false;				
			} else {
				alert('Upload failed: ' + data.message);
			}
		})
		.catch(error => {
			alert('An error occurred: ' + error);
		});
	}
	
</script>
</body>
</html>
