<?php

/**
 *          ****************************************************************************
 *          **********************||  GO TRADE PANEL ADMINISTRATIVO ||******************
 *          ****************************************************************************
 * 
 *          @date               2019-11-15
 *          @author             Bayman Burton <bayman@burtonservers.com>
 *          @copyright          2019-2020 Burton Technology https://burtonservers.com
 *          @license            https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License (GPL v3)
 *          International Registered Trademark & Property of Burton Technology  https://burtonservers.com
 * 
 *          This source file is subject to the GNU General Public License (GPL v3)
 *          that is bundled with this package in the file LICENSE.txt.
 *          It is also available through the world-wide-web at this URL:
 *          https://www.gnu.org/licenses/gpl-3.0.en.html
 *          If you did not receive a copy of the license and are unable to
 *          obtain it through the world-wide-web, please send an email
 *          to dev@burtonservers.com so we can send you a copy immediately.
 *          This software is built and distributed by Burton Technology https://burtonservers.com
 *          By using this software you are Aware it is strictly prohibited its comercial distribution or 
 *          modification of any aspect of the aplication
 *
 *          Desc:
 *          Custom admin dashboard for easy lightweight SPA deployment.
 * 
 *          WARNING
 *          Please do not edit this file or the aplication could stop working as intended, also
 *          any modifications will be overwritten by newer versions in the future
 *          
 */

//  DEBUG EN PANTALLA   //
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

require '../assets/scripts/utils.php';
require '../assets/scripts/conn.php';

$portal =    broom('url', $_GET['l']);

/** CONFIRMAMOS QUE SE ESTE ENVIANDO LA URL DEL PORTAL A MOSTRAR */
if ($portal == '') {
    $panelTitle = ' Usted debe seleccionar un portal para mostrar';
    $panelLogo = '';
    $panelBG = '1.jpg';
    $form = '';
} else {

    /** LE PEDIMOS A LA DB LOS DATOS DEL PORTAL */
    $query = "  SELECT * FROM gt_portals p 
                INNER JOIN gt_portalDetail pd 
                    ON (p.idPortal = pd.idPortal) 
                WHERE urlPortal = '$portal' 
                ORDER BY pd.idDetail DESC
                LIMIT 1 ";
    $result = $c->query($query);
    $rows = $result->num_rows;

    if ($rows < 1) {
        $panelTitle = ' No pudimos encontrar este portal en el sistema ';
        $panelLogo = '';
        $panelBG = '1.jpg';
        $form = '';
    } else {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        if ($row['statusPortal'] == 'true' || $_GET['preview'] == 'true') {

            /** SI EL PORTAL ESTA ACTIVO MOSTRAMOS LOS DATOS */
            $panelTitle = $row['titlePortal'];
            $panelLogo = '<img src="../assets/img/port/' . $row['imgPortal'] . '" />';
            $panelBG = $row['bgPortal'];
            $panelForm = $row['formPortal'];
            $panelHasFb = $row['hasFbPortal'];
            $panelFavicon = '../assets/img/port/' . $row['imgPortal'];

            if ($panelHasFb == '1') {
                $btnFb = '<fb:login-button scope="public_profile,email" onlogin="checkLoginState();" perms="user_mobile_phone"></fb:login-button>';
                //$btnFb = '<div class="fb-login-button" data-width="" data-size="large" data-button-type="login_with" data-auto-logout-link="false" data-use-continue-as="true"></div>';
            } else {
                $btnFb = '';
            }
            $form = str_replace('___FBBTN___', $btnFb, $panelForm);
        } else {
            $panelTitle = ' Este portal se encuentra temporalmente inactivo ';
            $panelLogo = '';
            $panelBG = '1.jpg';
            $form = '';
        }
    }
}

?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title><?php echo $panelTitle; ?></title>
    <link rel="icon" href="<?php echo $panelFavicon; ?>" type="image/x-icon" />
    <style>
        #content,
        .login,
        .login-card a,
        .login-card h1,
        .login-help {
            text-align: center
        }

        body,
        html {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            display: table
        }

        #content {
            font-family: 'Source Sans Pro', sans-serif;
            display: table-cell;
            vertical-align: middle;
            background: url(../assets/img/portbg/<?php echo $panelBG; ?>) center center no-repeat fixed;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
        }

        .login-card {
            padding: 40px;
            width: 380px;
            background-color: #F7F7F7;
            margin: 0 auto 10px;
            border-radius: 2px;
            box-shadow: 0 2px 2px rgba(0, 0, 0, .3);
            overflow: hidden
        }

        .login-card h1 {
            font-weight: 400;
            font-size: 2.3em;
            color: #1383c6
        }

        .login-card h1 span {
            color: #f26721
        }

        .login-card img {
            width: 70%;
            height: 70%
        }

        .login-card input[type=submit] {
            width: 100%;
            display: block;
            margin-bottom: 10px;
            position: relative
        }

        .login-card input[type=text],
        input[type=password] {
            height: 44px;
            font-size: 16px;
            width: 100%;
            margin-bottom: 10px;
            -webkit-appearance: none;
            background: #fff;
            border: 1px solid #d9d9d9;
            border-top: 1px solid silver;
            padding: 0 8px;
            box-sizing: border-box;
            -moz-box-sizing: border-box
        }

        .login-card input[type=text]:hover,
        input[type=password]:hover {
            border: 1px solid #b9b9b9;
            border-top: 1px solid #a0a0a0;
            -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
            -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1)
        }

        .login {
            font-size: 14px;
            font-family: Arial, sans-serif;
            font-weight: 700;
            height: 36px;
            padding: 0 8px
        }

        .login-submit {
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            border: 0;
            color: #fff;
            text-shadow: 0 1px rgba(0, 0, 0, .1);
            background-color: #4d90fe;
            border-radius: 15px;
            margin: 15px;
        }

        .login-submit:disabled {
            opacity: .6
        }

        .login-submit:hover {
            border: 0;
            text-shadow: 0 1px rgba(0, 0, 0, .3);
            background-color: #357ae8;
        }

        .login-card a {
            text-decoration: none;
            color: #222;
            font-weight: 400;
            display: inline-block;
            opacity: .6;
            transition: opacity ease .5s
        }

        .login-card a:hover {
            opacity: 1
        }

        .login-help {
            width: 100%;
            font-size: 12px
        }

        .list {
            list-style-type: none;
            padding: 0
        }

        .list__item {
            margin: 0 0 .7rem;
            padding: 0
        }

        label {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            text-align: left;
            font-size: 14px;
        }

        input[type=checkbox] {
            -webkit-box-flex: 0;
            -webkit-flex: none;
            -ms-flex: none;
            flex: none;
            margin-right: 10px;
            float: left
        }

        @media screen and (max-width:450px) {
            .login-card {
                width: 70% !important
            }

            .login-card img {
                width: 30%;
                height: 30%
            }
        }

        .anim {
            opacity: 0;
            transition: opacity 4s;
        }

        .anim2 {
            opacity: 0;
        }


        .login-fb {
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            border: 0;
            color: #fff;
            text-shadow: 0 1px rgba(0, 0, 0, .1);
            background-color: #4267B2;
            border-radius: 15px;
            margin: 15px;
        }

        .login-fb:disabled {
            opacity: .6
        }

        .login-fb:hover {
            border: 0;
            text-shadow: 0 1px rgba(0, 0, 0, .3);
            background-color: #304b82;
        }

        .errorInput {
            border-color: #fc5661 !important;
        }
    </style>
</head>

<body>

    <div id="fb-root"></div>

    <script src="../../assets/js/vendors/jquery-3.2.1.min.js"></script>
    <script async defer crossorigin="anonymous" src="https://connect.facebook.net/es_LA/sdk.js#xfbml=1&version=v5.0&appId=527100781228495&autoLogAppEvents=1"></script>
    <div id="content">
        <div class="login-card anim" id="loginCard">
            <?php echo $panelLogo; ?><br>
            <h1><?php echo $panelTitle; ?></h1>
            <?php echo $form; ?>
            <form class="anim2" name="continue_form" method="post">
                <input type="submit" name="accept" class="login login-submit" value="Navegar" id="btnNav" >
            </form>
        </div>
    </div>
    <script>
        var gguid = (Date.now().toString(36) + Math.random().toString(36).substr(2, 5)).toUpperCase(),
            hasID = window.localStorage.getItem("GGUID"),
            portalUrl = '<?php echo $portal; ?>';

        setTimeout(function() {
            if (hasID) {
                gguid = hasID;
            } else {
                window.localStorage.setItem("GGUID", gguid);
            }
            trackVisit(gguid);
            $(document).find('#loginCard').css('opacity', '1');
        }, 1000);

        function disableSubmit(status) {
            if (status) {
                console.log('empty');
                $('#btnLogin').prop("disabled", status);
            } else {
                console.log('marked');
                $('#btnLogin').prop("disabled", status);
            }
        }

        function trackVisit(id) {
            var formData = new FormData();
            formData.append('meth', 'logVisit');
            formData.append('gguid', id);
            formData.append('portal', portalUrl);
            formData.append('leadMeta', window.localStorage.getItem("leadMeta"));
            apiCall(formData, function(data) {
                console.log(data);
            });
        }


        /*           MOSTRAR DATOS DEL PORTAL SELECCIONADO              */
        $(document).off('click', "#btnLogin");
        $(document).on('click', '#btnLogin', function(e) {
            e.preventDefault();

            var username = $(document).find('#nomreUser').val(),
                telephone = $(document).find('#telUser').val(),
                email = $(document).find('#emailUser').val();

            if (username == '') {
                $(document).find('#nomreUser').addClass('errorInput');
                return false;
            } else {
                $(document).find('#nomreUser').removeClass('errorInput');
            }
            if (telephone == '') {
                $(document).find('#telUser').addClass('errorInput');
                return false;
            } else {
                $(document).find('#telUser').removeClass('errorInput');
            }
            if (email == '') {
                $(document).find('#emailUser').addClass('errorInput');
                return false;
            } else {
                $(document).find('#emailUser').removeClass('errorInput');
            }
            var formData = new FormData();
            formData.append('meth', 'saveNewLead');
            formData.append('name', username);
            formData.append('telephone', telephone);
            formData.append('email', email);
            formData.append('guid', gguid);
            formData.append('portal', portalUrl);
            apiCall(formData, function(data) {
                if (data.scriptResp == "match") {
                    window.localStorage.setItem("leadMeta", JSON.stringify(data.leadMeta));
                    welcomeShow();
                }
                console.log(data);
            });
        });

        /** RESUMIMOS LAS LLAMADAS A LA API EN UNA MISMA FUNCION */
        function apiCall(postData, onSuccess) {
            var apiURI = 'https://leads.gotrade.com.ec/api/';
            $.ajax({
                url: apiURI,
                type: 'POST',
                dataType: "json",
                cache: false,
                contentType: false,
                processData: false,
                data: postData,
                success: function(data) {
                    if (data.scriptResp == "done") {
                        onSuccess(data);
                    } else {
                        console.log('hubo un error en al respuesta.');
                        console.log(data);
                    }
                },
                error: function(error) {
                    console.log("Hubo un error de internet, no hubo respuesta de la API");
                    console.log(error);
                }
            });
        }

        function welcomeShow(data) {
            $(document).find('#loginCard form').remove();
            $(document).find('#loginCard h1').html('Bienvenido ' + data.leadMeta.nameLead + ' <br> haz clic para navegar');
        }
    </script>
</body>

</html>