<?php
error_reporting(0);//Desactiva ver warnings
ini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL);//Activa ver warnings

/*Site generals*/{
$siteName="Optimal Sales";
$logo="./assets/images/logo-dark.png";
$SiteDescription="Administrative tools for takeoffs and quoting";
$favIcon="./assets/images/favicon.ico";
}
/*conectar bdd, smtp y librerias*/{
if($_SERVER["HTTP_HOST"] == 'localhost'){
    $host_name = 'localhost';
    $database = 'test';
    $user_name = 'root';
    $password = '';    
}else{
    $host_name = 'db5006133589.hosting-data.io';
    $database = 'dbs5131681';
    $user_name = 'dbu1136964';
    $password = 'Pruebas123...';
}
$link = mysqli_connect($host_name, $user_name, $password, $database);    
if ($link->connect_error) {die("Connection failed: " . $link->connect_error);}else{ /*echo "Connected successfully";/**/}
/*character set to utf8mb4 */$link->set_charset(" utf8mb4");

$smtp=array();
$smtp['server'] = 'smtp.ionos.mx';// Set the SMTP server to send through
$smtp['user']   = 'no-reply@alexcd2000.com';// SMTP username
$smtp['pwd']    = 'NoResponder.';// SMTP password
$smtp['secure'] = 'tls';// Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$smtp['port']   = 587;// TCP port to connect to, use 465 for PHPMailer::ENCRYPTION_SMTPS` above
    
include_once "./librerias/PHPMailer/EnviarEmail.php";    
}

/*Urls*/{
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === ' on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
$uri = $_SERVER['REQUEST_URI'];
//echo $url.$uri;  if(strpos($uri,'') ){}
//echo $_SERVER[HTTP_HOST];
$pestana = explode("?", $uri);
}
/*Login super basico*/{
    if (session_status() == PHP_SESSION_NONE) {session_start();}//start once
    
    if(isset($_POST['login']) ){
        $sql="SELECT id FROM amr_users WHERE email='".$_POST['email']."' AND pwd='".$_POST['pwd']."' LIMIT 1;"; $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            $row=mysqli_fetch_assoc($ejecutarquery);
            $_SESSION['user']=$row["id"]; // la sesión se guarda como un cookie hasheado en el navegador parece ser    
            $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
        }else{
            header("Location: ./login.php?error=1");
            //echo '<script>window.location.replace("./login.php?error=1");</script>';
            //echo "Sin resultados";
        }
    }

    if(!isset($_SESSION['user']) ){//revisa que estes loggeado
        //echo "Not logged in";//no puedes hacer echo antes de header
        if( !strpos($uri,"login") ){//saca a login excepto en login o pwd recovery
            header("Location: ./login.php");
            //echo "-will redirect";
            //echo '<script>window.location.replace("./login.php");</script>';
        }
    }else{
        $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
        //echo "uR Logged in: ".$_SESSION['user'];
    }

    if (isset($_SESSION['user']) and isset($_SESSION['LAST_ACTIVITY']) and (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {// last request was more than 30 minutes ago
        session_unset();     // unset $_SESSION variable for the run-time 
        session_destroy();   // destroy session data in storage
    }
    if( isset($_SESSION['user']) and strpos($uri,"login.php") ){//destruye sesion siempre en login
        session_unset();//esto las null ea
        session_destroy();//esto las borra 
    }    
}
/*Reset pwd*/{
    if(isset($_POST['reset-pwd']) ){//envia email con token
         $sql="SELECT pwd FROM amr_users WHERE email='".$_POST['reset-pwd']."' LIMIT 1;"; 
        $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            $row=mysqli_fetch_assoc($ejecutarquery);
            $email='Your password is: '.$row["pwd"].'<br /><br />It seems you forgot it or someone else is trying to log in to your account. Remember you can change it in your settings any time.';
            $whtvr = enviarmail($_POST['reset-pwd'],"","no-reply@".$_SERVER['HTTP_HOST'],$siteName,"Password Reset",$email,$smtp);
            //echo $email." - ".$whtvr;
        }       
    }
    if(isset($_GET['token']) ){//crea sesion y en settings resetea su pwd
        //esto en caso le quieras crear un pwd nuevo en el mail... pero mas facil darselo
    }
}
/*Traer datos usuario*/{
if(isset($_SESSION['user']) ){//revisa que estes loggeado    
    $sql="SELECT * FROM amr_users WHERE id='".$_SESSION['user']."' ;"; 
    $ejecutarquery=mysqli_query($link,$sql);
    //no puede fallar, jala datos de usuario
    $row=mysqli_fetch_assoc($ejecutarquery);
    $usuario=array("theme"=>$row["theme"],"name"=>$row["name"],"layout"=>$row["layout"],"email"=>$row["email"],"company"=>$row["company"],"phone"=>$row["phone"],"address"=>$row["address"],"city"=>$row["city"],"state"=>$row["state"],"country"=>$row["country"],"zipcode"=>$row["zipcode"],"type"=>$row["type"],"img"=>$row["img"]);    
}
}
/*menus*/{
$menu='
                    <li class="nav-item dropdown">
                        <a class="nav-link arrow-none" href="./" id="topnav-dashboard" role="button" aria-haspopup="true" aria-expanded="false">
                            <i class="mdi mdi-view-dashboard me-1"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle arrow-none" href="#" id="topnav-apps" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fe-grid me-1"></i> Projects <div class="arrow-down"></div>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="topnav-apps">
                            <a href="project-new.php" class="dropdown-item">Create project</a>
                            <a href="project-view.php" class="dropdown-item">View</a>
                            <a href="project-takeoff.php" class="dropdown-item">Take off</a>
                        </div>
                        <!--<div class="dropdown">
                                <a class="dropdown-item dropdown-toggle arrow-none" href="#" id="topnav-email" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    Email <div class="arrow-down"></div>
                                </a>
                                <div class="dropdown-menu" aria-labelledby="topnav-email">
                                    <a href="email-inbox.html" class="dropdown-item">Inbox</a>
                                    <a href="email-templates.html" class="dropdown-item">Email Templates</a>
                                </div>
                            </div>-->
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle arrow-none" href="#" id="topnav-apps" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fe-user me-1"></i> Contacts <div class="arrow-down"></div>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="topnav-apps">
                            <a href="contact-new.php" class="dropdown-item">Create</a>
                            <a href="contact-view.php" class="dropdown-item">View</a>
                        </div>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link arrow-none" href="calendar-view.php" id="topnav-dashboard" role="button" aria-haspopup="true" aria-expanded="false">
                            <i class="mdi mdi-view-dashboard me-1"></i> Calendar
                        </a>

                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle arrow-none" href="#" id="topnav-apps" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fe-printer me-1"></i> Documents (will view inside projects) <div class="arrow-down"></div>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="topnav-apps">
                            <a href="document-takeoff.php" class="dropdown-item">Takeoff</a>
                            <a href="document-quote.php" class="dropdown-item">Quote</a>
                            <a href="document-po.php" class="dropdown-item">Purchase order</a>
                            <a href="document-bol.php" class="dropdown-item">Bill of lading</a>
                            <a href="document-bom.php" class="dropdown-item">Bill of materials</a>
                        </div>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle arrow-none" href="#" id="topnav-apps" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fe-box me-1"></i> Products <div class="arrow-down"></div>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="topnav-apps">
                            <a href="product-new.php" class="dropdown-item">Create</a>
                            <a href="product-view.php" class="dropdown-item">View</a>
                            <a href="product-category.php" class="dropdown-item">Categories</a>
                            <a href="product-attribute.php" class="dropdown-item">Attributes</a>
                        </div>
                    </li>                    
';
$menuusuario='
                    <a href="?layout=toggle" class="dropdown-item notify-item">
                        <i class="fe-layout"></i>
                        <span>Toggle layout</span>
                    </a>
                    <a href="?theme=toggle" class="dropdown-item notify-item">
                        <i class="fe-circle"></i>
                        <span>Toggle theme color</span>
                    </a>    
                    <a href="./settings.php" class="dropdown-item notify-item">
                        <i class="fe-settings"></i><span>Personal settings</span>
                    </a>
                    <div class="dropdown-divider"></div>
                    <a href="login.php?logout=1" class="dropdown-item notify-item">
                        <i class="fe-log-out"></i>
                        <span>Logout</span>
                    </a>
';    
}
/*Cambiar tema layout y colores*/{
    if(isset($_GET['theme']) ){
        if($usuario["theme"]=="dark"){
            $sql = " UPDATE amr_users SET ultmodif= CURRENT_TIMESTAMP, theme='light'  WHERE id='".$_SESSION['user']."';"; 
        }else{
            $sql = " UPDATE amr_users SET ultmodif= CURRENT_TIMESTAMP, theme='dark'  WHERE id='".$_SESSION['user']."';";             
        }
        $ejecutarquery=mysqli_query($link,$sql);
        //header("Location: ".$pestana[0]);
        echo '<script>window.location.replace("'.$pestana[0].'");</script>';
    }
    if(isset($_GET['layout']) ){
        if($usuario["layout"]=="vertical"){
            $sql = " UPDATE amr_users SET ultmodif= CURRENT_TIMESTAMP, layout='horizontal'  WHERE id='".$_SESSION['user']."';"; 
        }else{
            $sql = " UPDATE amr_users SET ultmodif= CURRENT_TIMESTAMP, layout='vertical'  WHERE id='".$_SESSION['user']."';";             
        }
        $ejecutarquery=mysqli_query($link,$sql);
        //echo '<script>alert(" '.$pestana[0].' ")</script>';
        //header("Location: ".$pestana[0]);
        echo '<script>window.location.replace("'.$pestana[0].'");</script>';
    }    
}
/*funciones*/{
    function TemplateTheme(){
        global $link;
        return $tema;
    }    


$notificaciones='
                    <div class="noti-scroll" data-simplebar>

                        <!-- item-->
                        <a href="javascript:void(0);" class="dropdown-item notify-item active">
                            <div class="notify-icon">
                                <img src="./assets/images/users/user-1.jpg" class="img-fluid rounded-circle" alt="" />
                            </div>
                            <p class="notify-details">Alex</p>
                            <p class="text-muted mb-0 user-msg">
                                <small>Hi, How are you? What about our next meeting</small>
                            </p>
                        </a>

                        <!-- item-->
                        <a href="javascript:void(0);" class="dropdown-item notify-item">
                            <div class="notify-icon bg-primary">
                                <i class="mdi mdi-comment-account-outline"></i>
                            </div>
                            <p class="notify-details">Caleb Flakelar commented on Admin
                                <small class="text-muted">1 min ago</small>
                            </p>
                        </a>

                        <!-- item-->
                        <a href="javascript:void(0);" class="dropdown-item notify-item">
                            <div class="notify-icon">
                                <img src="./assets/images/users/user-4.jpg" class="img-fluid rounded-circle" alt="" />
                            </div>
                            <p class="notify-details">Karen Robinson</p>
                            <p class="text-muted mb-0 user-msg">
                                <small>Wow ! this admin looks good and awesome design</small>
                            </p>
                        </a>

                        <!-- item-->
                        <a href="javascript:void(0);" class="dropdown-item notify-item">
                            <div class="notify-icon bg-warning">
                                <i class="mdi mdi-account-plus"></i>
                            </div>
                            <p class="notify-details">New user registered.
                                <small class="text-muted">5 hours ago</small>
                            </p>
                        </a>

                        <!-- item-->
                        <a href="javascript:void(0);" class="dropdown-item notify-item">
                            <div class="notify-icon bg-info">
                                <i class="mdi mdi-comment-account-outline"></i>
                            </div>
                            <p class="notify-details">Caleb Flakelar commented on Admin
                                <small class="text-muted">4 days ago</small>
                            </p>
                        </a>

                        <!-- item-->
                        <a href="javascript:void(0);" class="dropdown-item notify-item">
                            <div class="notify-icon bg-secondary">
                                <i class="mdi mdi-heart"></i>
                            </div>
                            <p class="notify-details">Carlos Crouch liked
                                <b>Admin</b>
                                <small class="text-muted">13 days ago</small>
                            </p>
                        </a>
                    </div>
';
}
?>