<?php
//© Copyright Approcket. All rights reserved.
//Majoris Panel Script is considered a proprietary software.
//To gain information about the laws regarding the use of these script,
//please visit www.approcket.ir



//CHECK IF APPROCKET-MAJORIS DATABASE IS IMPORTED AND IF NOT IMPORT
$tables_exist = db::fetchAll("SHOW TABLES");

$databaseStructureIsMoreThan10 = true;

if (!$tables_exist) {
    //ok, lets import database:
    $sql = file_get_contents('./core/_dist/sql/db10.sql');
    $res = db::exec($sql);
    if(!is_numeric($res)){
        echo "majoris: error importing database with db::exec(sql)";
        exit;
    }
}else{

    //IMPORTANT: dont change this part in database migration times

    $default = db::fetch("SELECT * FROM defaults WHERE `type` = ?",["db_structure_version"]);
    $dbVersion = intval($default['data']);

    //DONT CHANGE
    if($dbVersion < 10) $databaseStructureIsMoreThan10 = false;
    //DONT CHANGE

    //IMPORTANT: dont change db10 in migration time

}


//2. CHECK IF OWNER ADMIN IS EXIST AND IF NOT GOTO INSTALLER
$admins_count = db::rowCount("SELECT * FROM admins");

if ($admins_count < 1) {
    //no admin defined so goto installer.php
    //we use installer with no Router
    header('Location: '.BASE.'/installer.php');
    exit();
}


//3. CHECK IF MAJORIS_SELF_HOSTED_MODE
//   AND ADMIN IS LOGGED-IN
//   AND AES-KEY, API-TOKEN, LICENSE-KEY, RUNTIME-TOKEN IS NOT SET
//   AND IF SO THEN GOTO ACTIVATION PAGE
if(MAJORIS_SELF_HOSTED_MODE){
    $admin_id = (new Loginer) -> loginCheck();
    if($admin_id != -1){
        $appsCount = db::rowCount("SELECT * FROM apps",[]);
        if ($appsCount == 1 && $databaseStructureIsMoreThan10){

            $app = db::fetch("SELECT * FROM apps",[]);
            $panelconfig  = db::fetch("SELECT * FROM panelconfig WHERE `app_id` = ?",[$app['id']]);
            $aes_key      = trim($panelconfig['aes_key']);
            $api_token    = trim($panelconfig['api_token']);
            $license_key   = trim($panelconfig['license_key']);
            $runtime_token = trim($panelconfig['runtime_token']);
            
            if($aes_key == "" || $api_token == "" || $license_key == "" || $runtime_token == ""){
                //we use activation with no Router
                header('Location: '.BASE.'/activation.php');
                exit();
            }

        }
    }
}
