<?php

/*===============================================*\
|| ############################################# ||
|| # JAKWEB.CH / Version 2.1.4                 # ||
|| # ----------------------------------------- # ||
|| # Copyright 2023 JAKWEB All Rights Reserved # ||
|| ############################################# ||
\*===============================================*/

// Check if the file is accessed only via index.php if not stop the script from running
if (!defined('JAK_ADMIN_PREVENT_ACCESS')) die('You cannot access this file directly.');

// Change for 1.0.3
use JAKWEB\JAKsql;

// Already logged in, don't load it again
if (JAK_USERID) jak_redirect(BASE_URL_ADMIN);

// Login IN
if (!empty($page1) && !empty($page2) && is_numeric($page1) && is_numeric($page2)) {

    if ($jakdb->has("user_confirm", ["confirmcode" => $page2])) {

        // Ok, already activated
        $_SESSION["infomsg"] = $jkl['i8'];
        jak_redirect(BASE_URL_ADMIN);

    } else {

        // Database connection to the main site
        $jakdb1 = new JAKsql([
            // required
            'database_type' => JAKDB_MAIN_DBTYPE,
            'database_name' => JAKDB_MAIN_NAME,
            'server' => JAKDB_MAIN_HOST,
            'username' => JAKDB_MAIN_USER,
            'password' => JAKDB_MAIN_PASS,
            'charset' => 'utf8',
            'port' => JAKDB_MAIN_PORT,
            'prefix' => JAKDB_MAIN_PREFIX,
         
            // [optional] driver_option for connection, read more from http://www.php.net/manual/en/pdo.setattribute.php
            'option' => [PDO::ATTR_CASE => PDO::CASE_NATURAL]
            ]);

        // Now get the user information
        $activeuser = $jakdb1->get("users", ["id", "email", "username", "businessname", "businessurl", "password"], ["AND" => ["id" => $page1, "active" => 0, "confirm" => $page2]]);

        // We get the settings because we need them
        $sett = array();
        $settings = $jakdb1->select("settings", ["varname", "used_value"]);
        foreach ($settings as $v) {
            $sett[$v["varname"]] = $v["used_value"]; 
        }

        if (isset($activeuser) && !empty($activeuser) && !$jakdb->has("user", ["OR" => ["username" => $activeuser["username"]], "email" => $activeuser["email"]])) {

            $jakdb->insert("user", [ 
                "password" => $activeuser["password"],
                "username" => $activeuser["username"],
                "name" => $activeuser["username"],
                "email" => $activeuser["email"],
                "access" => 1,
                "permissions" => "leads,leads_all,off_all,ochat,ochat_all,support,faq,blog,statistic,statistic_all,files,proactive,usrmanage,client,billing,responses,departments,settings,answers,widget,groupchat,blacklist,blocklist",
                "time" => $jakdb->raw("NOW()")]);

            $lastid = $jakdb->id();
        
            if ($lastid) {

                $newuserpath = APP_PATH.JAK_FILES_DIRECTORY.'/'.$lastid;
                
                if (!is_dir($newuserpath)) {
                    mkdir($newuserpath, 0755);
                    copy(APP_PATH.JAK_FILES_DIRECTORY."/index.html", $newuserpath."/index.html");
                }

                // Get the settings for this location
                $opsett = array();
                $opsettings = $jakdb1->select("opsettings", ["varname", "used_value"], ["locid" => JAK_MAIN_LOC]);
                foreach ($opsettings as $v) {
                    $opsett[$v["varname"]] = $v["used_value"]; 
                }

                // Update the user language
                $jakdb->update("user", ["language" => $opsett["lang"]], ["id" => $lastid]);

                // Create the settings for the operator
                $jakdb->query("INSERT INTO ".JAKDB_PREFIX."settings (`opid`, `varname`, `used_value`, `default_value`) VALUES
                (".$lastid.", 'crating', '1', '0'),
                (".$lastid.", 'dateformat', '".$opsett["dateformat"]."', 'd.m.Y'),
                (".$lastid.", 'email', '".$activeuser["email"]."', '@jakbusiness'),
                (".$lastid.", 'emailcc', '', '@jakcc'),
                (".$lastid.", 'facebook', '', ''),
                (".$lastid.", 'ip_block', '', ''),
                (".$lastid.", 'email_block', '', ''),
                (".$lastid.", 'facebook_big', '', ''),
                (".$lastid.", 'lang', '".$opsett["lang"]."', '".$opsett["lang"]."'),
                (".$lastid.", 'msg_tone', 'new_message', 'new_message'),
                (".$lastid.", 'openop', '1', '1'),
                (".$lastid.", 'register', '1', '1'),
                (".$lastid.", 'pro_alert', '1', '1'),
                (".$lastid.", 'ring_tone', 'ring', 'ring'),
                (".$lastid.", 'send_tscript', '1', '1'),
                (".$lastid.", 'show_ips', '1', '1'),
                (".$lastid.", 'smtp_sender', '".$activeuser["email"]."', ''),
                (".$lastid.", 'smtphost', '', ''),
                (".$lastid.", 'smtppassword', '', ''),
                (".$lastid.", 'smtpport', '25', '25'),
                (".$lastid.", 'smtpusername', '', ''),
                (".$lastid.", 'smtp_alive', '0', '0'),
                (".$lastid.", 'smtp_auth', '0', '0'),
                (".$lastid.", 'smtp_mail', '0', '0'),
                (".$lastid.", 'smtp_prefix', '', ''),
                (".$lastid.", 'oauth_provider', '', ''),
                (".$lastid.", 'oauth_clientid', '', ''),
                (".$lastid.", 'oauth_secret', '', ''),
                (".$lastid.", 'oauth_tenantid', '', ''),
                (".$lastid.", 'oauth_refresh', '', ''),
                (".$lastid.", 'timeformat', '".$opsett["timeformat"]."', 'g:i a'),
                (".$lastid.", 'timezoneserver', '".$opsett["timezoneserver"]."', '".$opsett["timezoneserver"]."'),
                (".$lastid.", 'title', '".$activeuser["businessname"]."', '".$activeuser["businessname"]."'),
                (".$lastid.", 'twilio_nexmo', '1', '1'),
                (".$lastid.", 'twitter', '', ''),
                (".$lastid.", 'twitter_big', '', ''),
                (".$lastid.", 'tw_msg', '".$opsett["tw_msg"]."', '".$opsett["tw_msg"]."'),
                (".$lastid.", 'tw_phone', '', ''),
                (".$lastid.", 'tw_sid', '', ''),
                (".$lastid.", 'tw_token', '', ''),
                (".$lastid.", 'useravatheight', '".$opsett["useravatheight"]."', '250'),
                (".$lastid.", 'useravatwidth', '".$opsett["useravatwidth"]."', '250'),
                (".$lastid.", 'holiday_mode', '0', '0'),
                (".$lastid.", 'client_push_not', '1', '1'),
                (".$lastid.", 'engage_sound', 'sound/new_message3', 'sound/new_message3'),
                (".$lastid.", 'client_sound', 'sound/hello', 'sound/hello'),
                (".$lastid.", 'chat_upload_standard', '0', '0'),
                (".$lastid.", 'billing_mode', '0', '0'),
                (".$lastid.", 'ticket_close_r', '0', '0'),
                (".$lastid.", 'ticket_inform_r', '0', '0'),
                (".$lastid.", 'ticket_guest', '0', '0'),
                (".$lastid.", 'ticket_account', '0', '0'),
                (".$lastid.", 'ticket_limit', '0', '0'),
                (".$lastid.", 'ticket_reminder', '0', '0'),
                (".$lastid.", 'ticket_close_c', '0', '0'),
                (".$lastid.", 'ticket_reopen', '0', '0'),
                (".$lastid.", 'ticket_attach', '0', '0'),
                (".$lastid.", 'ticket_duedate_format', 'F d, Y:#:LL', 'F d, Y:#:LL'),
                (".$lastid.", 'ticket_duedate_preset', '1', '1'),
                (".$lastid.", 'ticket_duedate', '0', '0'),
                (".$lastid.", 'ticket_similar', '1', '1'),
                (".$lastid.", 'ticket_rating', '0', '0'),
                (".$lastid.", 'faq_a', '1', '1'),
                (".$lastid.", 'faq_home', '4', '4'),
                (".$lastid.", 'faq_footer', '3', '3'),
                (".$lastid.", 'faq_page', '5', '5'),
                (".$lastid.", 'faq_pagination', '10', '10'),
                (".$lastid.", 'blog_a', '1', '1'),
                (".$lastid.", 'blog_home', '3', '3'),
                (".$lastid.", 'blog_footer', '2', '2'),
                (".$lastid.", 'blog_page', '5', '5'),
                (".$lastid.", 'blog_pagination', '10', '10'),
                (".$lastid.", 'standard_chat_dep', '0', '0'),
                (".$lastid.", 'standard_support_dep', '0', '0'),
                (".$lastid.", 'standard_faq_cat', '0', '0'),
                (".$lastid.", 'front_template', '".$opsett["front_template"]."', 'business'),
                (".$lastid.", 'offline_cms_page', '10', '10'),
                (".$lastid.", 'facebook_app_id', '', ''),
                (".$lastid.", 'stripe_publish_key', '', ''),
                (".$lastid.", 'stripe_secret_key', '', ''),
                (".$lastid.", 'paypal_client', '', ''),
                (".$lastid.", 'paypal_secret', '', ''),
                (".$lastid.", 'yookassa_id', '', ''),
                (".$lastid.", 'yookassa_secret', '', ''),
                (".$lastid.", 'paystack_secret', '', ''),
                (".$lastid.", 'twoco', '', ''),
                (".$lastid.", 'twoco_secret', '', ''),
                (".$lastid.", 'authorize_id', '', ''),
                (".$lastid.", 'authorize_key', '', ''),
                (".$lastid.", 'sandbox_mode', '1', '1'),
                (".$lastid.", 'blogpostapprove', '', ''),
                (".$lastid.", 'standard_ticket_priority', '0', '0'),
                (".$lastid.", 'standard_ticket_option', '0', '0'),
                (".$lastid.", 'ticket_private', '0', '0'),
                (".$lastid.", 'ticket_private_show', '1', '1'),
                (".$lastid.", 'ticket_guest_web', '0', '0'),
                (".$lastid.", 'calendar_tickets', '0', '0'),
                (".$lastid.", 'calendar_chats', '0', '0'),
                (".$lastid.", 'calendar_offline', '0', '0'),
                (".$lastid.", 'calendar_purchases', '0', '0'),
                (".$lastid.", 'emailtpllogo', '/template/business/img/logo_email.png', '/template/business/img/logo_email.png'),
                (".$lastid.", 'emailtplcopy', 'My HelpDesk Copyright', 'Cloud Desk 3<br>Made in Switzerland'),
                (".$lastid.", 'client_url', '".$opsett["client_url"]."', 'client'),
                (".$lastid.", 'blog_url', '".$opsett["blog_url"]."', 'blog'),
                (".$lastid.", 'faq_url', '".$opsett["faq_url"]."', 'faq'),
                (".$lastid.", 'search_url', '".$opsett["search_url"]."', 'search'),
                (".$lastid.", 'support_url', '".$opsett["support_url"]."', 'support'),
                (".$lastid.", 'contact_url', '".$opsett["contact_url"]."', 'get-in-touch'),
                (".$lastid.", 'api_url', '', ''),
                (".$lastid.", 'chatwidget_id', '0', '0'),
                (".$lastid.", 'envato_api_token', '', ''),
                (".$lastid.", 'api_profile', '', ''),
                (".$lastid.", 'envato_token', '', ''),
                (".$lastid.", 'dsgvo_contact', '', ''),
                (".$lastid.", 'engage_icon', 'fa fa-bell', 'fa fa-bell'),
                (".$lastid.", 'openai_chatgpt', '0', '0'),
                (".$lastid.", 'openai_apikey', '', '')");

                // Insert the chat widget
                $opcw = $jakdb1->select("chatwidget", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opcw as $rowcw) {
                    # code...
                    $jakdb->insert("chatwidget", ["opid" => $lastid, "title" => $rowcw["title"], "lang" => $opsett["lang"], "hidewhenoff" => 0, "template" => $rowcw["template"], "created" => $jakdb->raw("NOW()")]);
                }

                // Group Chat
                $opgc = $jakdb1->select("groupchat", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opgc as $rowgc) {
                    # code...
                    $jakdb->insert("groupchat", ["opid" => $lastid, "title" => $rowgc["title"], "description" => $rowgc["description"], "opids" => 0, "maxclients" => 10, "lang" => $opsett["lang"], "buttonimg" => "colour_on.png", "floatpopup" => 0, "floatcss" => "bottom:20px;left:20px", "active" => 0, "created" => $jakdb->raw("NOW()")]);
                }

                // Insert the chat department
                $opdep = $jakdb1->select("departments", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opdep as $rowod) {
                    # code...
                    $jakdb->insert("departments", ["opid" => $lastid, "title" => $rowod["title"], "description" => $rowod["description"], "active" => $rowod["active"], "dorder" => $rowod["dorder"], "time" => $jakdb->raw("NOW()")]);
                }

                // Insert the support_department
                $opsdep = $jakdb1->select("support_departments", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opsdep as $rowsd) {
                    # code...
                    $jakdb->insert("support_departments", ["opid" => $lastid, "title" => $rowsd["title"], "description" => $rowsd["description"], "active" => $rowsd["active"], "dorder" => $rowsd["dorder"], "time" => $jakdb->raw("NOW()")]);
                }

                // First FAQ category and entry
                $opfaqc = $jakdb1->select("faq_categories", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opfaqc as $rowfc) {
                    # code...
                    $jakdb->insert("faq_categories", ["opid" => $lastid, "title" => $rowfc["title"], "description" => $rowfc["description"], "active" => $rowfc["active"], "dorder" => $rowfc["dorder"], "time" => $jakdb->raw("NOW()")]);

                    $lastfaqid = $jakdb->id();

                    // We will need to write the FAQ articles
                    $opfaqarticle = $jakdb1->select("faq_article", '*', ["locid" => JAK_MAIN_LOC]);
                    foreach ($opfaqarticle as $rowfca) {
                        # code...
                        $jakdb->insert("faq_article", ["opid" => $lastid, "catid" => $lastfaqid, "lang" => $opsett["lang"], "title" => $rowfca["title"], "content" => $rowfca["content"], "active" => $rowfca["active"], "dorder" => $rowfca["dorder"], "time" => $jakdb->raw("NOW()")]);

                        // Update the numbers on the category
                        $jakdb->update("faq_categories", ["articles[+]" => 1], ["id" => $lastfaqid]);
                    }
                }

                // Ticket priorities
                $optp = $jakdb1->select("ticketpriority", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($optp as $rowtp) {
                    # code...
                    $jakdb->insert("ticketpriority", [["opid" => $lastid, "title" => $rowtp["title"], "class" => $rowtp["title"], "oponly" => $rowtp["oponly"], "dorder" => $rowtp["dorder"], "edited" => $jakdb->raw("NOW()"), "created" => $jakdb->raw("NOW()")]]);

                }

                // Ticket options
                $opto = $jakdb1->select("ticketoptions", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opto as $rowto) {
                    # code...
                    $jakdb->insert("ticketoptions", [["opid" => $lastid, "title" => $rowto["title"], "icon" => $rowto["icon"], "oponly" => $rowto["oponly"], "dorder" => $rowto["dorder"], "edited" => $jakdb->raw("NOW()"), "created" => $jakdb->raw("NOW()")]]);
                }

                // Support responses
                $opsr = $jakdb1->select("support_responses", ["title", "message"], ["locid" => JAK_MAIN_LOC]);
                foreach ($opsr as $rowsr) {
                    # code...
                    $jakdb->insert("support_responses", ["opid" => $lastid, "title" => $rowsr["title"], "message" => $rowsr["message"]]);
                }

                // Support responses
                $ots = $jakdb1->select("support_status", ["title", "class", "reminder", "closed", "dorder"], ["locid" => JAK_MAIN_LOC]);
                foreach ($ots as $rowots) {
                    # code...
                    $jakdb->insert("support_status", ["opid" => $lastid, "title" => $rowots["title"], "class" => $rowots["class"], "reminder" => $rowots["reminder"], "closed" => $rowots["closed"], "dorder" => $rowots["dorder"], "edited" => $jakdb->raw("NOW()"), "created" => $jakdb->raw("NOW()")]);
                }

                $jakdb->insert("customfields", ["id" => NULL, "opid" => $lastid, "fieldlocation" => 3, "depid" => 0, "title" => "Phone", "val_slug" => "phone", "fieldtype" => 1, "mandatory" => 1, "onregister" => 0, "dorder" => 1, "active" => 1, "time" => $jakdb->raw("NOW()")]);

                // Insert the answers
                $opa = $jakdb1->select("answers", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opa as $rowa) {
                    # code...
                    $jakdb->insert("answers", [["opid" => $lastid, "department" => 0, "lang" => $opsett["lang"], "title" => $rowa["title"], "message" => $rowa["message"], "fireup" => $rowa["fireup"], "msgtype" => $rowa["msgtype"], "created" => $jakdb->raw("NOW()")]]);
                }

                // Add the translations for the front end
                $opt = $jakdb1->select("translations", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opt as $rowt) {
                    # code...
                    $jakdb->insert("translations", [["opid" => $lastid, "lang" => $opsett["lang"], "cmsid" => $rowt["cmsid"], "cmsslug" => $rowt["cmsslug"], "title" => $rowt["title"], "description" => $rowt["description"], "time" => $jakdb->raw("NOW()")]]);
                }

                // CMS Pages
                $opcms = $jakdb1->select("cms_pages", '*', ["locid" => JAK_MAIN_LOC]);
                foreach ($opcms as $rowcms) {
                    # code...
                    $jakdb->insert("cms_pages", [["opid" => $lastid, "lang" => $opsett["lang"], "title" => $rowcms["title"], "url_slug" => $rowcms["url_slug"], "external_url" => $rowcms["external_url"], "previmg" => $rowcms["previmg"], "meta_keywords" => $rowcms["meta_keywords"], "meta_description" => $rowcms["meta_description"], "dorder" => $rowcms["dorder"], "showheader" => $rowcms["showheader"], "ishome" => $rowcms["ishome"], "showfooter" => $rowcms["showfooter"], "prepage" => $rowcms["prepage"], "custom2" => $rowcms["custom2"], "custom4" => $rowcms["custom4"], "header_tpl" => $rowcms["header_tpl"], "main_tpl" => $rowcms["main_tpl"], "footer_tpl" => $rowcms["footer_tpl"], "access" => $rowcms["access"], "hits" => $rowcms["hits"], "active" => $rowcms["active"], "edited" => $jakdb->raw("NOW()"), "created" => $jakdb->raw("NOW()")]]);

                    // Get the page id
                    $pageid = $jakdb->id();

                    // Update the translation accordingly to the id
                    $jakdb->update("translations", ["cmsid" => $pageid], ["AND" => ["opid" => $lastid, "cmsid" => $rowcms["id"]]]);
                }

                // Get the trial in the correct format
                $trialunix = strtotime("+".$sett["trialdays"]." day");
                $trialtime = $paidtill = date('Y-m-d H:i:s', $trialunix);

                // Insert into the local subscription table
                $jakdb->insert("subscriptions", ["opid" => $lastid, "business" => $activeuser["businessurl"], "validfor" => $sett["trialdays"], "paidwhen" => $jakdb->raw("NOW()"), "paidtill" => $trialtime, "registered" => $jakdb->raw("NOW()")]);


                // Now let's check if we have a standard package after sign up.
                if ($jakdb1->has("packages", ["AND" => ["locationid" => JAK_MAIN_LOC, "supackage" => 1, "active" => 1]])) {

                    // First we need the old subscriptions
                    $subs = $jakdb->get("subscriptions", ["id", "packageid", "operators", "departments", "files", "phpimap", "chathistory", "paygateid", "subscribeid", "subscribed"], ["opid" => $lastid]);

                    // Get the package
                    $pack = $jakdb1->get("packages", ["id", "title", "amount", "currency", "operators", "departments", "files", "copyfree", "tickets", "blog", "faq", "chatwidgets", "groupchats", "operatorchat", "activechats", "chathistory", "phpimap", "clients", "islc3", "ishd3", "validfor"], ["AND" => ["locationid" => JAK_MAIN_LOC, "supackage" => 1, "active" => 1]]);

                    // Paid unix
                    $paidunix = strtotime("+".$pack["validfor"]." days");
                    // get the nice time
                    $paidtill = date('Y-m-d H:i:s', $paidunix);
                    // Price
                    $couponprice = $pack['amount'];
                    // zero
                    $subscribed = $paygateid = $subscribeid = 0;

                    // We collect the customer id from stripe
                    $paygateid = $subs["paygateid"];
                    $subscribeid = $subs["subscribeid"];

                    // We set the current currency and amount
                    $amountopay = $pack['amount'];
                    $currencytopay = $pack['currency'];

                    // Nasty stuff starts
                    if (isset($subs) && isset($pack)) {

                        // Update the main operator subscription
                        update_main_operator($subs, $pack, $currencytopay, $couponprice, $paygateid, $subscribeid, 0, 0, "Standard User Plan", $lastid, JAK_MAIN_LOC);

                    }

                    // finally update the main database
                    $jakdb1->update("users", ["paidtill" => $paidtill], ["AND" => ["opid" => $lastid, "locationid" => JAK_MAIN_LOC]]);

                    // We insert the subscription into the main table for that user.
                    $jakdb1->insert("subscriptions", ["packageid" => $pack["id"],
                        "locationid" => JAK_MAIN_LOC,
                        "userid" => $lastid,
                        "amount" => $couponprice,
                        "currency" => $currencytopay,
                        "paidfor" => $pack["title"],
                        "paidhow" => "Standard User Plan",
                        "subscribed" => 0,
                        "paygateid" => $paygateid,
                        "subscribeid" => "",
                        "paidwhen" => $jakdb->raw("NOW()"),
                        "paidtill" => $paidtill,
                        "freeplan" => 1,
                        "active" => 1,
                        "success" => 1]);

                    // Set the correct trialtime because it is none
                    $trialtime = "1980-05-06 00:00:00";

                }

                // finally update the main database
                $jakdb1->update("users", [ 
                    "opid" => $lastid,
                    "trial" => $trialtime,
                    "paidtill" => $paidtill,
                    "welcomemsg" => 1,
                    "active" => 1,
                    "confirm" => 0], ["id" => $activeuser["id"]]);

                // So we do not need to connect to main database all the time the user clicks the link
                $jakdb->insert("user_confirm", ["opid" => $lastid, "confirmcode" => $page2, "created" => $jakdb->raw("NOW()")]);

            }

            // All good, let's rock
            $_SESSION["successmsg"] = $jkl['i9'];
            jak_redirect(BASE_URL_ADMIN);

        } else {
            // Something went wrong
            $_SESSION["errormsg"] = $jkl['i3'];
            jak_redirect(BASE_URL_ADMIN);
        }
  }
}

// Something went wrong
$_SESSION["errormsg"] = $jkl['i3'];
jak_redirect(BASE_URL_ADMIN);
?>
