<?php
session_start();
$dbFile = dirname(__file__) . "/includes/db.php";
include($dbFile);
if ($isInstalled && $dbIsLatest) {
  header("Location: index.php");
  exit;
}
if (isset($_POST['install'])) {
  session_destroy();
  session_start();
  $queryList = array();
  $queryList[] = array('version' => 1, 'query' => "CREATE TABLE `ads` ( `id` int(11) NOT NULL AUTO_INCREMENT, `path` varchar(100) DEFAULT NULL, `active` tinyint(1) DEFAULT NULL, `name` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;");
  $queryList[] = array('version' => 1, 'query' => "CREATE TABLE `dns` ( `id` int(11) NOT NULL AUTO_INCREMENT, `url` varchar(255) DEFAULT NULL, `active` tinyint(1) DEFAULT NULL, `name` varchar(100) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `username` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;");
  $queryList[] = array('version' => 1, 'query' => "CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) DEFAULT NULL, `password_hash` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;");
  $queryList[] = array('version' => 1, 'query' => "CREATE TABLE `config` (`dbversion` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
  $queryList[] = array('version' => 1, 'query' => "INSERT INTO `config` VALUES (2);");
  $queryList[] = array('version' => 1, 'query' => "ALTER TABLE config ADD panel_root varchar(255) NULL;");
  $queryList[] = array('version' => 2, 'query' => "CREATE TABLE `ibo_settings` ( `welcome_header` varchar(255) DEFAULT NULL, `welcome_text` varchar(255) DEFAULT NULL, `theme1_name` varchar(100) DEFAULT NULL, `theme1_background` varchar(255) DEFAULT NULL, `theme2_name` varchar(100) DEFAULT NULL, `theme2_background` varchar(255) DEFAULT NULL, `theme3_name` varchar(100) DEFAULT NULL, `theme3_background` varchar(255) DEFAULT NULL, `theme4_name` varchar(100) DEFAULT NULL, `theme4_background` varchar(255) DEFAULT NULL, `theme5_name` varchar(100) DEFAULT NULL, `theme5_background` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
  $queryList[] = array('version' => 2, 'query' => "CREATE TABLE `ibo_users` ( `dns_id` int(11) NOT NULL, `mac_address` varchar(100) NOT NULL, `username` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, PRIMARY KEY (`dns_id`,`mac_address`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
  $queryList[] = array('version' => 2, 'query' => "INSERT INTO ibo_settings (welcome_header, welcome_text, theme1_name, theme1_background, theme2_name, theme2_background, theme3_name, theme3_background, theme4_name, theme4_background, theme5_name) VALUES('', '', '', '', '', '', '', '', '', '', '');");
  $queryList[] = array('version' => 3, 'query' => "CREATE TABLE `hax_sports_categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `league_id` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ");
  $queryList[] = array('version' => 3, 'query' => "CREATE TABLE `hax_sports_event_channels` ( `id` int(11) NOT NULL AUTO_INCREMENT, `event_id` int(11) NOT NULL, `channel_name` varchar(255) DEFAULT NULL, `channel_epg` varchar(255) DEFAULT NULL, `channel_logo` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ");
  $queryList[] = array('version' => 3, 'query' => "CREATE TABLE `hax_sports_events` ( `id` int(11) NOT NULL AUTO_INCREMENT, `team_a_id` int(11) DEFAULT NULL, `team_b_id` int(11) DEFAULT NULL, `backdrop` varchar(255) DEFAULT NULL, `start_timestamp` varchar(255) DEFAULT NULL, `end_timestamp` varchar(255) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `created_at` varchar(255) DEFAULT NULL, `updated_at` varchar(255) DEFAULT NULL, `category_id` int(11) DEFAULT NULL, `channel_id` varchar(255) DEFAULT NULL, `league_id` int(11) DEFAULT NULL, `update_hash` varchar(100) DEFAULT NULL, `event_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ");
  $queryList[] = array('version' => 3, 'query' => "CREATE TABLE `hax_sports_teams` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `flag` varchar(255) DEFAULT NULL, `created_at` varchar(255) DEFAULT NULL, `updated_at` varchar(255) DEFAULT NULL, `league_id` int(11) DEFAULT NULL, `update_hash` varchar(100) DEFAULT NULL, `team_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
  
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad1_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad2_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad3_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad4_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad5_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad6_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad7_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad8_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad9_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad10_image varchar(255) NULL;");
  $queryList[] = array('version' => 4, 'query' => "ALTER TABLE ibo_settings ADD ad_duration int(11) NULL;");
  $queryList[] = array('version' => 4, 'query' => "UPDATE ibo_settings SET ad_duration = 10");
  
  $queryList[] = array('version' => 100000, 'query' => "UPDATE config SET dbversion = " . $expectedVersion . ";");
  $randPass = randomPassword();
  $hash = password_hash($randPass, PASSWORD_DEFAULT);
  $queryList[] = array('version' => 1, 'query' => "INSERT INTO `users` (username, password_hash) VALUES ('admin', '" . $hash  . "');");
  if (!$isInstalled) {
    $_SESSION['installmessage'] = "OnePanel has been installed. You can log in with the username <b>admin</b> and the password <b>" . $randPass . "</b><br/>Please make a note of this password now as it will disappear if the page is refreshed. You should change this once logged in";
  } else {
    $_SESSION['installmessage'] = "OnePanel has been updated";
  }
  //execute queries
  foreach ($queryList as $query) {
    if ($query['version'] > $insVersion) {
      $mysqli->query($query['query']);
    }
  }
  $query = $mysqli->prepare("UPDATE config SET panel_root = ?");
  $query->bind_param("s", $_POST['onepanel_root']);
  $query->execute();
  
  
  header("Location: index.php");
  exit;
}
function randomPassword()
{
  $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  $pass = array();
  $alphaLength = strlen($alphabet) - 1;
  for ($i = 0; $i < 10; $i++) {
    $n = rand(0, $alphaLength);
    $pass[] = $alphabet[$n];
  }
  return implode($pass);
}
$showButton = false;
if ($dbConnected) {
	 if (!$isInstalled) {
		$headerText = "Install";
		$message = "OnePanel is ready to install to database <b>$dbname</b>, click GO to build the database";
	 }
	 else
	 {
		$headerText = "Upgrade";
		$message = "OnePanel is ready to upgrade database <b>$dbname</b>, click GO to update the database. Your existing data will <b>not</b> be lost.";
	 }
	 $showButton = true;
} else {
  $message = "OnePanel cannot connect to the database, please create an empty database and edit the <b>includes/db.php</b> file with the details, then refresh this page.";
}
?>
<!--
=========================================================
* Material Dashboard 2 - v3.0.4
=========================================================

* Product Page: https://www.creative-tim.com/product/material-dashboard
* Copyright 2022 Creative Tim (https://www.creative-tim.com)
* Licensed under MIT (https://www.creative-tim.com/license)
* Coded by Creative Tim

=========================================================

* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="apple-touch-icon" sizes="180x180" href="assets/fav/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="assets/fav/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="assets/fav/favicon-16x16.png">
  <link rel="manifest" href="site.webmanifest">
  <link rel="mask-icon" href="assets/fav/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#da532c">
  <meta name="theme-color" content="#ffffff">
  <title>
    OnePanel IM 
  </title>
  <!--     Fonts and icons     -->
  <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,900|Roboto+Slab:400,700" />
  <!-- Nucleo Icons -->
  <link href="assets/css/nucleo-icons.css" rel="stylesheet" />
  <link href="assets/css/nucleo-svg.css" rel="stylesheet" />
  <!-- Font Awesome Icons -->
  <script src="https://kit.fontawesome.com/42d5adcbca.js" crossorigin="anonymous"></script>
  <!-- Material Icons -->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons+Round" rel="stylesheet">
  <!-- CSS Files -->
  <link id="pagestyle" href="assets/css/material-dashboard.min.css?v=3.0.4" rel="stylesheet" />
</head>

<body class="bg-gray-200">
  <main class="main-content  mt-0">
    <div class="page-header align-items-start min-vh-100" style="background-image: url('assets/img/bg.jpg');">
      <span class="mask bg-gradient-dark opacity-6"></span>
      <div class="container my-auto">
        <div class="row">
          <div class="col-lg-4 col-md-8 col-12 mx-auto">
            <div class="card z-index-0 fadeIn3 fadeInBottom">
              <div class="card-header p-0 position-relative mt-n4 mx-3 z-index-2">
                <div class="bg-gradient-secondary shadow-dark border-radius-lg py-3 pe-1">
                  <h4 class="text-white font-weight-bolder text-center mt-2 mb-0"><?php echo $headerText; ?></h4>
                </div>
              </div>
              <div class="card-body">
                <form action="" method="post" role="form" class="text-start">
                  <p class="mt-4 text-sm text-center">
                    <?php echo $message; ?>
                  </p>

                  <input type="hidden" id="onepanel_root" name="onepanel_root" class="form-control">
                  <?php
                  if ($showButton) {
                  ?>
                    <div class="text-center">
                      <button type="submit" name="install" type="button" class="btn bg-gradient-secondary w-100 my-4 mb-2">Go</button>
                    </div>
                  <?php
                  }
                  ?>

                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
      <footer class="footer position-absolute bottom-2 py-2 w-100">
        <div class="container">
          <div class="row align-items-center justify-content-lg-between">
            <div class="col-12 col-md-6 my-auto">
              <div class="copyright text-center text-sm text-white text-lg-start">
                © <script>
                  document.write(new Date().getFullYear())
                </script>,
                AndyHax
              </div>
            </div>

          </div>
        </div>
      </footer>
    </div>
  </main>
  <!--   Core JS Files   -->
  <script src="assets/js/core/popper.min.js"></script>
  <script src="assets/js/core/bootstrap.min.js"></script>
  <script src="assets/js/plugins/perfect-scrollbar.min.js"></script>
  <script src="assets/js/plugins/smooth-scrollbar.min.js"></script>
  <script>
    var win = navigator.platform.indexOf('Win') > -1;
    if (win && document.querySelector('#sidenav-scrollbar')) {
      var options = {
        damping: '0.5'
      }
      Scrollbar.init(document.querySelector('#sidenav-scrollbar'), options);
    }
  </script>
  <!-- Github buttons -->
  <script async defer src="https://buttons.github.io/buttons.js"></script>
  <!-- Control Center for Material Dashboard: parallax effects, scripts for the example pages etc -->
  <script src="assets/js/material-dashboard.min.js?v=3.0.4"></script>
</body>
<script>
  var href = window.location.href;
  var dir = href.substring(0, href.lastIndexOf('/')) + "/";
  document.getElementById("onepanel_root").value = dir;
</script>

</html>