<?php

// ini_set("display_errors", 1);
// ini_set("log_errors", 1);
ini_set("error_log", __DIR__ . "./php_error.log");
require_once "./vendor/autoload.php";
session_start();

?>

<!DOCTYPE html>
<html lang="en" dir="ltr" class="custom-scrollbars">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>EVOSYS POS</title>


    <!-- Favicon -->
    <link rel="icon" href="./assets/images/favicon.ico" type=" image/x-icon" />

    <!-- Global stylesheets -->
    <link href="./assets/css/all.css" rel="stylesheet" type="text/css">
    <link href="./assets/css/pos.css?v=<?= md5(time()) ?>" rel="stylesheet" type="text/css">

    <!-- Tailwaind CSS -->
    <script src="./assets/css/tailwindcss.js"></script>
    <!-- <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script> -->

    <link href="./assets/fonts/inter/inter.css" rel="stylesheet" type="text/css">

    <link href="./assets/icons/phosphor/styles.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/@phosphor-icons/web@2.1.1/src/regular/style.css" />
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/@phosphor-icons/web@2.1.1/src/fill/style.css" />

    <link href="./assets/icons/fontawesome/styles.min.css" rel="stylesheet" type="text/css">
    <link href="./assets/icons/icomoon/styles.min.css" rel="stylesheet" type="text/css">
    <link href="./assets/icons/material/styles.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="./assets/js/intlTelInput/intlTelInput.css">
    <!-- /global stylesheets -->

    <!-- Theme JS files -->
    <script src="./assets/js/jquery/jquery.min.js"></script>
    <script src="./assets/js/bootstrap/bootstrap.bundle.min.js"></script>
    <script src="./assets/js/vendor/ui/moment/moment.min.js"></script>

    <script src="./assets/js/vendor/tables/datatables/datatables.min.js"></script>
    <script src="./assets/js/vendor/tables/datatables/extensions/responsive.min.js"></script>
    <script src="./assets/js/vendor/tables/datatables/extensions/pdfmake/pdfmake.min.js"></script>
    <script src="./assets/js/vendor/tables/datatables/extensions/pdfmake/vfs_fonts.min.js"></script>
    <script src="./assets/js/vendor/tables/datatables/extensions/buttons.min.js"></script>
    <script src="./assets/js/vendor/pickers/datepicker.min.js"></script>
    <script src="./assets/js/vendor/pickers/daterangepicker.js"></script>

    <!-- Alert JS  -->
    <script src="./assets/js/vendor/notifications/noty.min.js"></script>
    <script src="./assets/js/vendor/notifications/sweet_alert.min.js"></script>

    <script src="./assets/js/vendor/forms/selects/select2.min.js"></script>
    <script src="./assets/js/vendor/forms/selects/bootstrap_multiselect.js"></script>
    <script src="./assets/js/vendor/forms/inputs/imask.min.js"></script>
    <script src="./assets/js/intlTelInput/intlTelInput.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>


    <!-- Theme JS files -->

</head>


<style>
    .no-internet {
        width: 100%;
        height: 100%;
        position: fixed;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        text-align: center;
        z-index: 1030;
    }

    .wifiIcon {
        font-size: 100px;
    }

    .screen-lock {
        width: 100%;
        height: 100%;
        position: fixed;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        text-align: center;
        z-index: 1030;
    }

    .lockLeyIcon {
        font-size: 100px;
    }
</style>


<script>
    const swalInit = swal.mixin({
        buttonsStyling: false,
        customClass: {
            confirmButton: 'btn btn-primary',
            cancelButton: 'btn btn-light',
            denyButton: 'btn btn-light',
            input: 'form-control form-control-lg',
        }
    });
</script>

<!-- pace-running pace-top -->

<body>

    <div class="no-internet card" style="display: none;">
        <div>
            <span class="ph-wifi-slash wifiIcon"></span>
            <h1 class="fw-bold fs-1" style="margin-top: -20px;"><span id="spanNetworkError">Network connection Error</span></h1>
            <h4 class="fw-light fs-4"><span id="spanNetworkErrorMessage">Unable to connect to the server. Please check your internet connection.</span>.</h4>
            <div>
                <button type="button" class="btn btn-light btn-lg fs-5" onclick="location.reload()"><span class="ph-arrows-clockwise me-2"></span> <span id="spanNetworkErrorRefresh">Refresh</span></button>
            </div>
        </div>
    </div>

    <?php
    $hide = "hide";
    if (isset($_SESSION["SCREEN_LOCK"]) && $_SESSION["SCREEN_LOCK"] == "LOCKED") {
        $hide = "";
    } ?>

    <div class="screen-lock card <?= $hide; ?>">
        <div style="margin-top: -150px;">
            <span class="ph-lock-key lockLeyIcon mb-0"></span>
            <!-- <h1 class="fw-bold fs-5"><span id="spanScreenLock">Locked screen</span></h1> -->
            <h6 class="fw-bold fs-1" style="margin-top: -10px;"><span id="spanUserFullName">John Doe</span></h6>

            <p><span id="spanScreenLockMessage">Please enter your password to continue</span>.</p>
            <div class="input-group">
                <span class="input-group-text"><i class="ph-lock-key text-muted"></i></span>
                <input type="password" class="form-control fs-1 form-control-xl passwordLockScreen inputScreenLockPassword" required autocomplete="off">
                <span class="input-group-text pointerLockScreen" style="cursor: pointer;"><i class="ph-eye"></i></span>
            </div>
            <div class="btn-group d-flex gap-2 mt-3">
                <a type="button" href="logout" class="btn btn-danger">
                    <i class="ph-sign-out text-white me-1"></i>
                    <span id="spanLogout">Logout</span>
                </a>
                <button type="button" class="btn btn-success btnUnlockScreen">
                    <i class="mi-lock-open text-white me-1"></i>
                    <span id="spanUnlock">Unlock</span>
                </button>
            </div>
        </div>
    </div>

    <?php

    // $_SESSION["EVOSYSPOS_SESSION_ACTIVE"] = "OK";

    if (isset($_SESSION["EVOSYSPOS_SESSION_ACTIVE"]) && $_SESSION["EVOSYSPOS_SESSION_ACTIVE"] == "OK") {

        $entInfo = getEnterpriseData($_SESSION["user_ent_id"]);
        $posInfo = getBranchData($_SESSION["user_pos_id"]);

        $arrayEntInfo = htmlspecialchars(json_encode($entInfo), ENT_QUOTES, 'UTF-8');

        $timeZone = $posInfo['pos_time_zone'] ?? "America/New_York";
        $currentDateTimeByZone = mdlGetDateTimeByZone($timeZone);

        date_default_timezone_set($timeZone);

        $userImagePath = "assets/images/anonymous.png";
        $getLanguage = file_get_contents("lang/en.json");

        $session_user_ent_id = $_SESSION["user_ent_id"];
        $session_user_pos_id = $_SESSION["user_pos_id"];
        $session_user_id = $_SESSION["user_id"];
        $stripe_customer_id = $entInfo["subs_customer_id"];
        $stripe_subscription_id = $entInfo["subs_subscription_id"];
        $ent_subscription_status = $entInfo["ent_stripe_subscription_status"];
        $session_user_profile = $_SESSION["user_profile"];
        $session_user_fullname = $_SESSION["user_fullname"];
        $pos_currency = $posInfo['pos_currency'];
        $business_category = $posInfo['pos_business_category'];
        $currency_symbol = getCurrencySymbolByCode($posInfo['pos_currency'])['currency_symbol'];

        // Include pages
        include "pages/header.php";
        include "pages/common-modals.php";

    ?>

        <!-- Page content -->
        <div class="page-content">

            <?php

            /*======================================
            SIDEBAR
            =============================================*/
            include "pages/left-sidebar.php";

            if (isset($_GET["route"])) {
                $routes = explode("/", $_GET["route"]);
                // $server = "https://".$_SERVER['HTTP_HOST'];
                $variables = explode("-det-", $routes[0]);

                if (isset($variables)) {
                    $route =  $variables[0];
                }

                $userProfile = $_SESSION['user_profile'] ?? null;

                // Define the valid routes for each user profile
                if ($userProfile == "ROOT") $routes = array('pos', 'home', 'dashboard', 'sell', 'sales', 'customers', 'providers', 'categories', 'purchases', 'products', 'stock-adjustment', 'daily-expense', 'fixed-expense', 'sales-report', 'products-report', 'payments-report', 'purchases-report', 'expenses-report', 'users', 'monitoring', 'enterprise', 'enterprises', 'branches', 'branches-adm', 'invoices', 'enterprises-res', 'branches-res', 'invoices-res', 'sale-types', 'payment-types', 'tax-receipt', 'distributors', 'stripe-products-prices', 'stripe-subscriptions', 'stripe-invoices', 'stripe-customers', 'billing', 'logout', '404');

                // Define the valid routes for each user profile
                if ($userProfile === 'Owner') {

                    // Default routes for Owner
                    $routes = array('home', 'dashboard', 'sell', 'sales', 'customers', 'providers', 'categories', 'purchases', 'products', 'stock-adjustment', 'daily-expense', 'fixed-expense', 'sales-report', 'products-report', 'payments-report', 'purchases-report', 'expenses-report', 'users', 'monitoring', 'enterprise', 'branches',  'tax-receipt', 'billing', 'logout', '404');

                    // Restrict routes if subscription is canceled
                    if ($ent_subscription_status === 'canceled') $routes = array('home', 'dashboard', 'sales-report', 'products-report', 'payments-report', 'purchases-report', 'expenses-report', 'billing', 'logout', '404');
                }

                // Define the valid routes for each user profile
                if ($userProfile == "Manager") $routes = array('home', 'sell', 'sales', 'customers', 'providers', 'categories', 'purchases', 'products', 'stock-adjustment', 'daily-expense', 'fixed-expense', 'sales-report', 'products-report', 'payments-report', 'purchases-report', 'expenses-report', 'users', 'monitoring', 'branches',  'tax-receipt', 'logout', '404');

                // Define the valid routes for each user profile
                if ($userProfile == "Cashier") $routes = array('home', 'sell', 'sales', 'customers', 'categories', 'products', 'stock-adjustment', 'daily-expense', 'logout', '404');

                // Define the valid routes for each user profile
                if ($userProfile == "Waiter") $routes = array('home', 'sell', 'sales', 'customers', 'products', 'logout', '404');

                if (in_array($route, $routes)) {
                    $location = ucfirst(str_replace('-', ' ', $route));
                    include "pages/" . $route . ".php";

            ?>

                    <script type="text/javascript">
                        var li_nav_item = $("a[href='<?= $route ?>']").parent().parent().parent();
                        var ul_nav_group_sub = $("a[href='<?= $route ?>']").parent().parent().parent().children();
                        var a_nav_link = $("a[href='<?= $route ?>']").parent().children();

                        li_nav_item.addClass("nav-item-open");
                        ul_nav_group_sub.addClass("show");
                        a_nav_link.addClass("active");

                        // console.log(a_nav_link);
                    </script>

            <?php
                } else {
                    // if route is not found, load 404 page
                    include "pages/404.php";
                }
            } else {
                // if no route is set, load home page
                include "pages/home.php";
            }


            ?>
        </div>
        <!-- /page content -->
    <?php

    } else {
        // if no session, redirect to login page
        include "pages/login.php";
    }

    ?>

    <script src="./assets/js/app.js"></script>
    <script src="./assets/js/template/form_validation_styles.js"></script>
    <script src="./assets/js/template/theme-switcher.js"></script>
    <script src="./assets/js/template/form_select2.js"></script>
    <script src="./assets/js/template/picker_date.js"></script>
    <script src="./assets/js/template/template.js"></script>

</body>

</html>