<?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 (file_exists('config.php')) {
	
$updatemessage=<<<EOT
<div style="margin:0 auto; margin-top:200px; border: 3px solid #aaf; border-radius:3px; box-shadow: 6px 6px 2px 1px rgba(0, 0, 255, .2); height:200px; width:400px; text-align:center; font-family:Sans-Serif; font-size:18px;">
<br><br><br><b>CONGRATULATIONS!</b><br><br>Update Successful.
</div>
EOT;


	@unlink("setup.php");
	@unlink("SETUP_imgup.php");
	echo $updatemessage;
	exit();
}

if (file_exists("img/default_logo.png")){
	if(!file_exists("img/logo.png")){
		@rename("img/default_logo.png","img/logo.png");
	}
}

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=13");
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 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,
  `promptstrict` int(11) DEFAULT 7,
  `language` int(11) NOT NULL DEFAULT 3,
  `audience` text DEFAULT NULL,
  `p1_input` longtext DEFAULT NULL,
  `editor_store` longtext DEFAULT NULL,
  `product_name` text DEFAULT NULL,
  `summary` longtext DEFAULT NULL,
  `s1` longtext DEFAULT NULL,
  `s2` longtext DEFAULT NULL,
  `s3` longtext DEFAULT NULL,
  `s4` longtext DEFAULT NULL,
  `s5` longtext DEFAULT NULL,
  `s6` longtext DEFAULT NULL,
  `s7` longtext DEFAULT NULL,
  `s8` longtext DEFAULT NULL,
  `s9` longtext DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

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_credits` int(11) NOT NULL DEFAULT 0,
 `user_txid_wplus` text,
 `user_txid_jvzoo` text,
 `adnumber` int(11) NOT NULL DEFAULT 1,
 PRIMARY KEY (`user_id`),
 UNIQUE KEY `user_email` (`user_email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


COMMIT;

			";
	$db->exec("SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';");
			
     $db->exec($sql);
	 
    $sql = "
    CREATE TABLE IF NOT EXISTS `sales` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `platform` int(11) NOT NULL COMMENT '0-Internal, 1-warriorplus',
        `internal_product_id` int(11) NOT NULL COMMENT '0=test, 1=Credit',
        `pack_name` text NOT NULL,
        `name` text NOT NULL,
        `email` text NOT NULL,
        `buyer_ip` text NOT NULL,
        `purchase_date` datetime NOT NULL,
        `cancel_date` datetime NOT NULL,
        `txid` text NOT NULL,
        `item_number` text NOT NULL,
        `item_name` text NOT NULL,
        `credits` int(11) NOT NULL,
        `user_id` int(11) NOT NULL,
        `sale_amount` text NOT NULL,
        `sale_currency` text NOT NULL,
		`type` int(11) NOT NULL COMMENT '0=one time sale, 1=recurring sale',
        PRIMARY KEY (`id`)
    ) DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
    ";

    $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='';
\$showreg='1';
\$initial_credits='0';
\$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);
	
	if (!file_exists('configpacks.php')) {
		

$configpacks=<<<EOT
<?php
\$wplus_pack_description_1='';
\$wplus_pack_credits_1='';
\$wplus_pack_cart_url_1='';
\$wplus_pack_product_id_1='';

\$wplus_pack_description_2='';
\$wplus_pack_credits_2='';
\$wplus_pack_cart_url_2='';
\$wplus_pack_product_id_2='';

\$wplus_pack_description_3='';
\$wplus_pack_credits_3='';
\$wplus_pack_cart_url_3='';
\$wplus_pack_product_id_3='';

\$wplus_pack_description_4='';
\$wplus_pack_credits_4='';
\$wplus_pack_cart_url_4='';
\$wplus_pack_product_id_4='';

\$wplus_pack_description_5='';
\$wplus_pack_credits_5='';
\$wplus_pack_cart_url_5='';
\$wplus_pack_product_id_5='';

\$wplus_pack_description_6='';
\$wplus_pack_credits_6='';
\$wplus_pack_cart_url_6='';
\$wplus_pack_product_id_6='';

\$wplus_pack_description_7='';
\$wplus_pack_credits_7='';
\$wplus_pack_cart_url_7='';
\$wplus_pack_product_id_7='';

\$wplus_pack_description_8='';
\$wplus_pack_credits_8='';
\$wplus_pack_cart_url_8='';
\$wplus_pack_product_id_8='';

\$wplus_pack_description_9='';
\$wplus_pack_credits_9='';
\$wplus_pack_cart_url_9='';
\$wplus_pack_product_id_9='';

\$wplus_pack_description_10='';
\$wplus_pack_credits_10='';
\$wplus_pack_cart_url_10='';
\$wplus_pack_product_id_10='';

?>

EOT;



		file_put_contents("configpacks.php",$configpacks);		
		
	}


	$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="icon" type="image/x-icon" href="favicon.ico">
<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>
