<?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";
$rutamultimedia='/multimedia';
$extensionesValidas=array('png','jpg','gif','pdf');
}
/*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(!isset($_POST['key']) ){//asi deja pasar al Ajax
    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"],"type"=>$row["type"],"img"=>$row["img"],"pwd"=>$row["pwd"]);    
}
}
/*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>
                        </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-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-cat.php" class="dropdown-item">Categories</a>
                            <a href="product-attr.php" class="dropdown-item">Attributes</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-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 contact</a>
                            <a href="contact-view.php" class="dropdown-item">View contacts</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-briefcase me-1"></i> Companies <div class="arrow-down"></div>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="topnav-apps">
                            <a href="company-new.php" class="dropdown-item">Create company</a>
                            <a href="company-view.php" class="dropdown-item">View companies</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>-->
';
$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>';
    }    
}
/*Ajax*/{
//Puede estar en configs, solo pon un isset en el login y puede estar todo en uno
//Ajax JS Functions en footer!!!
if(isset($_POST['key']) ){//segun la key se ejecuta el query segun la bdd por seguridad
    //echo "...<pre>";var_dump($_POST);echo "</pre>...";
    if($_POST['key'] === 'settings.php'){//este es el salvar
        $sql = " UPDATE amr_users SET ultmodif= CURRENT_TIMESTAMP, ".$_POST['columna']."='".$_POST['valor']."'  WHERE id='".$_POST['fila']."';";
        $ejecutarquery=mysqli_query($link,$sql);
    }
    if($_POST['key'] === 'settings'){//esta es la consulta, NO FUNCIONA
        $sql="SELECT * FROM amr_users WHERE id='".$_POST['fila']."' LIMIT 1;"; 
        $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            $row=mysqli_fetch_assoc($ejecutarquery);
            $id=$row[$_POST['que']];
        }else{
            echo "Error retrieving ".$_POST['que'];
        }
    }

    if($_POST['key'] === 'product-view.php'){//este es el salvar
        $sql = " UPDATE amr_products SET ultmodif= CURRENT_TIMESTAMP, ".$_POST['columna']."='".$_POST['valor']."'  WHERE id='".$_POST['fila']."';";
        $ejecutarquery=mysqli_query($link,$sql);
    }
    if($_POST['key'] === 'product-attr.php' or $_POST['key'] === 'product-cat.php'){//este es el salvar
        $sql = " UPDATE amr_products_meta SET ultmodif= CURRENT_TIMESTAMP, ".$_POST['columna']."='".$_POST['valor']."'  WHERE id='".$_POST['fila']."';";
        $ejecutarquery=mysqli_query($link,$sql);
    }
}
}
/*funciones*/{
//echo de las datatable    
function tablaBDD($tabla){
    global $link;
    $html="";
    if(isset($_GET['search']) ){
        if($tabla == 'categoria'){
            $sql='SELECT * FROM `amr_products_meta` WHERE tipo = "categoria" AND id="'.$_GET['search'].'" ORDER BY id ASC;';
        }elseif($tabla == 'atributo'){
            $sql='SELECT * FROM `amr_products_meta` WHERE tipo = "atributo" AND id="'.$_GET['search'].'" ORDER BY id ASC;';
        }else{
            $sql="SELECT * FROM ".$tabla." WHERE id='".$_GET['search']."' ORDER BY id ASC;";             
        }
    }else{
        if($tabla == 'categoria'){
            $sql='SELECT * FROM `amr_products_meta` WHERE tipo = "categoria" ORDER BY id ASC;';
        }elseif($tabla == 'atributo'){
            $sql='SELECT * FROM `amr_products_meta` WHERE tipo = "atributo" ORDER BY id ASC;';
        }else{
            $sql="SELECT * FROM ".$tabla." ORDER BY id ASC;";                             
        }
    }
    $ejecutarquery=mysqli_query($link,$sql); 
    if(mysqli_num_rows($ejecutarquery)>0){
        while($row=mysqli_fetch_assoc($ejecutarquery)){
            if($tabla == 'amr_projects'){
            $html.='<tr fase="'.$row["estatus"].'" last="'.strtotime($row["ultmodif"]).'" nombre="'.$row["nombre"].'" >';
            }else{        
            $html.= "<tr>";
            }
            if($tabla == 'amr_products'){
                $cols=array("id","nombre","descripcion","categoria1","categoria2","categoria3","fabricante","precio","descuento","archivo");
                $i=0; foreach( $cols as $key=>$feach){  
                    //segun el nombre de la columna es un echo normal o un select...
                    $html.='<td ';
                    if($feach == 'id'){
                        $html.='<td>'.$row[$feach].'</td><td><button type="button" class="btn btn-danger waves-effect waves-light btn-xs es-link" onclick="window.location.href=\'./product-view.php?delete='.$row[$feach].'\'"><i class="mdi mdi-close es-link"></i></button></td>';
                    }else{
                        $html.='fila="'.$row['id'].'" columna="'.$feach.'">'.$row[$feach].'</td>';
                    }
                $i++;}

                //echo atributos
                $sql="SELECT * FROM amr_products_meta WHERE producto='".$row['id']."' ORDER BY id ASC;"; 
                $ejecutarquery2=mysqli_query($link,$sql); 
                if(mysqli_num_rows($ejecutarquery2)>0){
                    $attr="";
                    $i=0;
                    while($row2=mysqli_fetch_assoc($ejecutarquery2)){
                        if($i != 0){$attr.=",<br />";}
                        $i++;
                        $attr.='<a href="./product-attr.php?search='.$row2['id'].'" target="_blank" class="es-link">'.$row2['nombre'];
                        if($row2['ajuste']>0){$attr.=" (+".$row2['ajuste'].")";}
                        if($row2['ajuste']<0){$attr.=" (".$row2['ajuste'].")";}
                        $attr.='</a>';    
                    }
                    $html.='<td>'.$attr.'</td>';
                }else{
                    $html.='<td>None</td>';
                }
                                }
            if($tabla == 'atributo'){
                $cols=array("id","nombre","producto","ajuste");
                $i=0; foreach( $cols as $key=>$feach){  
                    //segun el nombre de la columna es un echo normal o un select...
                    $html.='<td ';
                    if($feach == 'id'){
                        $html.='>'.$row[$feach].'</td><td><button type="button" class="btn btn-danger waves-effect waves-light btn-xs es-link" onclick="window.location.href=\'./product-attr.php?delete='.$row[$feach].'\'"><i class="mdi mdi-close es-link"></i></button></td>';
                    }elseif($feach == 'producto'){
                        $sql2="SELECT * FROM amr_products WHERE id='".$row[$feach]."' LIMIT 1;"; 
                        $ejecutarquery2=mysqli_query($link,$sql2); 
                        if(mysqli_num_rows($ejecutarquery2)>0){
                            $row2=mysqli_fetch_assoc($ejecutarquery2);
                            $html.='> <a href="./product-view.php?search='.$row[$feach].'" target="_blank" class="es-link">'.$row2["nombre"].'</a>'.'</td>';
                        }else{
                            $html.= "Deleted product".'</td>';
                        }
                    }else{
                        $html.='fila="'.$row['id'].'" columna="'.$feach.'">'.$row[$feach].'</td>';
                        //$html.=$row[$feach].'</td>';                            
                    }
                    //$html.='</td>';    
                $i++;}    
            }
            if($tabla == 'categoria'){
                $cols=array("id","nombre","padre");
                $i=0; foreach( $cols as $key=>$feach){  
                    //segun el nombre de la columna es un echo normal o un select...
                    $html.='<td ';
                    if($feach == 'id'){
                        $html.='>'.$row[$feach].'</td><td><button type="button" class="btn btn-danger waves-effect waves-light btn-xs es-link" onclick="window.location.href=\'./product-cat.php?delete='.$row[$feach].'\'"><i class="mdi mdi-close es-link"></i></button></td>';
                    }elseif($feach == 'padre'){
                        $sql2="SELECT * FROM amr_products_meta WHERE id='".$row[$feach]."' LIMIT 1;"; 
                        $ejecutarquery2=mysqli_query($link,$sql2); 
                        if(mysqli_num_rows($ejecutarquery2)>0){
                            $row2=mysqli_fetch_assoc($ejecutarquery2);
                            $html.='>'.$row2["nombre"].'</td>';
                        }else{
                            $html.= "Deleted parent".'</td>';
                        }
                    }else{
                        $html.='fila="'.$row['id'].'" columna="'.$feach.'">'.$row[$feach].'</td>';
                        //$html.=$row[$feach].'</td>';                            
                    }
                    //$html.='</td>';    
                $i++;}    
                
                //echo productos
                $sql="SELECT * FROM amr_products WHERE categoria".$row['nivel']."='".$row['id']."' ORDER BY id ASC;"; 
                $ejecutarquery2=mysqli_query($link,$sql); 
                if(mysqli_num_rows($ejecutarquery2)>0){
                    $attr="";
                    $i=0;
                    while($row2=mysqli_fetch_assoc($ejecutarquery2)){
                        if($i != 0){$attr.=",<br />";}
                        $i++;
                        $attr.='<a href="./product-view.php?search='.$row2['id'].'" target="_blank" class="es-link">'.$row2['nombre'];
                        $attr.='</a>';    
                    }
                    $html.='<td>'.$attr.'</td>';
                }else{
                    $html.='<td>None</td>';
                }
            }
            if($tabla == 'amr_projects'){
                $cols=array("id","ultmodif","nombre","descripcion","estatus");
                $i=0; foreach( $cols as $key=>$feach){  
                    //segun el nombre de la columna es un echo normal o un select...
                    $html.='<td ';
                    if($feach == 'id'){
                        $html.='<td style="width:45px; padding-right:0px !important;">'.$row[$feach].'</td>
                        <td style="width:100px;">
                        <button type="button" class="btn btn-danger waves-effect waves-light btn-xs es-link" onclick="window.location.href=\'./project-view.php?delete='.$row[$feach].'\'"><i class="mdi mdi-close es-link"></i></button>
                        <button type="button" class="btn btn-info waves-effect waves-light btn-xs es-link" onclick="window.location.href=\'./project-new.php?edit='.$row[$feach].'\'"><i class="mdi mdi-clipboard-edit-outline es-link"></i></button>
                        </td>';
                    }elseif($feach == 'nombre'){
                        $html.='><a href="./project.php?id='.$row['id'].'" target="_self" class="es-link">'.$row['nombre'].'</a></td>';
                    }elseif($feach == 'estatus'){
                        if($row[$feach]=='Cancelled'){$clase="badge bg-danger";}//tmbn hay  bg-purple -pink etc...
                        if($row[$feach]=='Completed'){$clase="badge bg-success";}
                        if($row[$feach]=='In progress'){$clase="badge bg-warning";}
                        if($row[$feach]=='Draft'){$clase="badge bg-primary";}
                        $html.='><span style="padding: 5px 10px;" class="'.$clase.'">'.$row[$feach].'</span></td>';
                    }else{
                        //$html.='fila="'.$row['id'].'" columna="'.$feach.'">'.$row[$feach].'</td>';
                        $html.='>'.$row[$feach].'</td>';
                    }
                $i++;}

                //echo asignados
                $sql="SELECT * FROM amr_projects_meta WHERE proyecto='".$row['id']."' ORDER BY id ASC;"; 
                $ejecutarquery2=mysqli_query($link,$sql); 
                if(mysqli_num_rows($ejecutarquery2)>0){
                    $attr="";
                    $i=0;
                    while($row2=mysqli_fetch_assoc($ejecutarquery2)){
                        if($row2['meta'] == 'contacto'){
                            $sql="SELECT * FROM amr_contacts WHERE id='".$row2['valor']."' ORDER BY id ASC;";
                            $links="contact";
                        }elseif($row2['meta'] == 'empresa'){
                            $sql="SELECT * FROM amr_companies WHERE id='".$row2['valor']."' ORDER BY id ASC;";                           
                            $links="company";
                        }else{
                            $sql="SELECT * FROM amr_companies WHERE id='QUE HAGA ERROR' ORDER BY id ASC;";                           
                            //$links="company";
                            //$attr.='PRODCTO';    
                        }
                        $ejecutarquery3=mysqli_query($link,$sql); 
                        if(mysqli_num_rows($ejecutarquery3)>0){
                        $row3=mysqli_fetch_assoc($ejecutarquery3);
                            if($i != 0){$attr.=",<br />";}
                            $i++;
                            $attr.='<a href="./'.$links.'-view.php?id='.$row3['id'].'" target="_blank" class="es-link">'.$row3['nombre'].'</a>';    
                        }else{
                            //$attr.=' -Error retrieving- '.$row2['id'].$row2['proyecto'].$row2['meta'].$row2['valor'].$sql;        
                        }
                    }
                    $html.='<td>'.$attr.'</td>';
                }else{
                    $html.='<td>None</td>';
                }
                                }
            $html.= "</tr>";
        }
        return $html;
    }else{
        return "No data";
    }
}    
function tarjetaBDD($tabla,$html){
    global $link;
    $output="";
    if(isset($_GET['search']) ){
        //if($tabla == 'amr_companies'){
            //No sirve pa buscar por id porque da match positivos
        $sql='SELECT * FROM '.$tabla.' WHERE nombre LIKE "%'.$_GET['search'].'%" OR tel LIKE "%'.$_GET['search'].'%" OR mail LIKE "%'.$_GET['search'].'%" OR direccion LIKE "%'.$_GET['search'].'%" OR ciudad LIKE "%'.$_GET['search'].'%" OR estado LIKE "%'.$_GET['search'].'%" OR pais LIKE "%'.$_GET['search'].'%" OR cp LIKE "%'.$_GET['search'].'%" ORDER BY nombre ASC;';
        //}elseif($tabla == 'amr_contacts'){
    }elseif(isset($_GET['id']) ){
            $sql='SELECT * FROM '.$tabla.' WHERE id = "'.$_GET['id'].'" ORDER BY nombre ASC;';
    }else{
        $sql="SELECT * FROM ".$tabla." ORDER BY nombre ASC;";                             
    }
    $ejecutarquery=mysqli_query($link,$sql); 
    if(mysqli_num_rows($ejecutarquery)>0){
        while($row=mysqli_fetch_assoc($ejecutarquery)){
            $output.=$html;//agrega item
            if($tabla == 'amr_contacts'){
                $cols=array("id","nombre","mail","tel","direccion","ciudad","estado","pais","cp","puesto","empresa");
                $i=0; foreach( $cols as $key=>$feach){  
                    //segun el nombre de la columna es un echo normal o un select...
                    $remplazar=strtoupper($feach);
                    $output=str_replace($remplazar, $row[$feach], $output);
                $i++;}
                    $direcc=$row['direccion'].", ".$row['ciudad'].", ".$row['estado'].", ".$row['pais']." ".$row['cp'];
                    $output=str_replace("DIRECC", $direcc, $output);
                    $output=str_replace("DIRURL", urlencode($direcc), $output);

                //echo empresa
                $sql="SELECT * FROM amr_companies WHERE id='".$row["empresa"]."' LIMIT 1;"; 
                $ejecutarquery2=mysqli_query($link,$sql); 
                if(mysqli_num_rows($ejecutarquery2)>0){
                    $row2=mysqli_fetch_assoc($ejecutarquery2);
                    $empre='<a href="./company-view.php?id='.$row2['id'].'" target="_blank" class="es-link">'.$row2['nombre'].'</a>';
                }else{
                    $empre='None';
                    unset($row2);//no jale de otros fotos
                }
                $output=str_replace("EMPRE", $empre, $output);

                //echo img
                if($row["img"] == '' or $row["img"] == 'nothing'){
                    if(!isset($row2) or $row2["img"] == '' or $row2["img"] == 'nothing' ){
                        $img="./multimedia/default-user.png";
                    }else{
                        $img=$row2["img"];
                    }
                }else{
                    $img=$row["img"];
                }
                $output=str_replace("IMG", $img, $output);//si no hay foto usa el logo de la empresa
        
                //echo proyectos
                $sql="SELECT m.*,p.nombre
                    FROM amr_projects_meta m
                    INNER JOIN amr_projects p ON p.id = m.proyecto
                    WHERE meta='contacto' and valor='".$row['id']."' 
                    ORDER BY p.nombre ASC;"; 
                $ejecutarquery2=mysqli_query($link,$sql); 
                $proye="";
                if(mysqli_num_rows($ejecutarquery2)>0){
                    $i=0;
                    while($row2=mysqli_fetch_assoc($ejecutarquery2)){
                        if($i != 0){$proye.=", ";}
                        $proye.='<a href="./contact-view.php?id='.$row2['proyecto'].'" target="_blank" class="es-link">'.$row2['nombre'].'</a>';    
                    $i++;}
                }else{
                    $proye='None';
                }
                $output=str_replace("PROYE", $proye, $output);    
                
                //echo links
                $output=str_replace("LINKDELETE", "?delete=".$row["id"], $output);    
                $output=str_replace("LINKEDIT", "./contact-new.php?edit=".$row["id"], $output);    
                
            }
            if($tabla == 'amr_companies'){
                $cols=array("id","nombre","mail","tel","direccion","ciudad","estado","pais","cp","descripcion");
                $i=0; foreach( $cols as $key=>$feach){  
                    //segun el nombre de la columna es un echo normal o un select...
                    $remplazar=strtoupper($feach);
                    $output=str_replace($remplazar, $row[$feach], $output);
                $i++;}
                    $direcc=$row['direccion'].", ".$row['ciudad'].", ".$row['estado'].", ".$row['pais']." ".$row['cp'];
                    $output=str_replace("DIRECC", $direcc, $output);
                    $output=str_replace("DIRURL", urlencode($direcc), $output);
        
                //echo proyectos
                //echo proyectos
                $sql="SELECT m.*,p.nombre
                    FROM amr_projects_meta m
                    INNER JOIN amr_projects p ON p.id = m.proyecto
                    WHERE meta='empresa' and valor='".$row['id']."' 
                    ORDER BY p.nombre ASC;"; 
                $ejecutarquery2=mysqli_query($link,$sql); 
                $proye="";
                if(mysqli_num_rows($ejecutarquery2)>0){
                    $i=0;
                    while($row2=mysqli_fetch_assoc($ejecutarquery2)){
                        if($i != 0){$proye.=", ";}
                        $proye.='<a href="./contact-view.php?id='.$row2['proyecto'].'" target="_blank" class="es-link">'.$row2['nombre'].'</a>';    
                    $i++;}
                }else{
                    $proye='None';
                }
                $output=str_replace("PROYE", $proye, $output);    
                
                //echo contactos
                $sql="SELECT * FROM amr_contacts WHERE empresa='".$row['id']."' ;"; 
                $ejecutarquery2=mysqli_query($link,$sql); 
                $emple="";
                if(mysqli_num_rows($ejecutarquery2)>0){
                    $i=0;
                    while($row2=mysqli_fetch_assoc($ejecutarquery2)){
                        if($i != 0){$emple.=", ";}
                        $emple.='<a href="./contact-view.php?id='.$row2['id'].'" target="_blank" class="es-link">'.$row2['nombre'].'</a>';    
                    $i++;}
                }else{
                    $emple='None';
                }
                $output=str_replace("EMPLEADOS", $emple, $output);    
                
                //echo tipo en ingles
                if($row["tipo"] == 'cliente'){
                $output=str_replace("TIPO", "Client", $output);}
                if($row["tipo"] == 'fabricante'){
                $output=str_replace("TIPO", "Manufacturer", $output);}
                
                
                //echo imagenes
                if($row["img"] == '' or $row["img"] == 'nothing'){
                    $img="./multimedia/default-user.png";
                }else{
                    $img=$row["img"];
                }
                $output=str_replace("IMG", $img, $output);//si no hay foto usa default

                //echo links
                $output=str_replace("LINKDELETE", "?delete=".$row["id"], $output);    
                $output=str_replace("LINKEDIT", "./company-new.php?edit=".$row["id"], $output);    
            }
        }
        return $output;
    }else{
        return "No match, try again with other search".$sql;
    }
}    
function AsignarContEmpr(){//el multi select para ligar contacto o empresa a proyecto
    global $link;     
    $html='<optgroup label="Contacts">';
        $sql="SELECT * FROM amr_contacts ORDER BY nombre;"; 
        $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            while($row=mysqli_fetch_assoc($ejecutarquery)){
                $html.= '<option value="C'.$row['id'].'">'.$row['nombre'].' - '.$row['puesto'].'</option>';
            }
        }
    $html.='</optgroup><optgroup label="Companies">';
        $sql="SELECT * FROM amr_companies ORDER BY nombre;"; 
        $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            while($row=mysqli_fetch_assoc($ejecutarquery)){
                $html.= '<option value="E'.$row['id'].'">'.$row['nombre'].'</option>';
            }
        }
    $html.='</optgroup>';
    return $html;    
}    
function AsignarCal(){//el multi select para ligar contacto o empresa a proyecto
    global $link;     
    $html='<optgroup label="Projects">';
        $sql="SELECT * FROM amr_projects ORDER BY nombre;"; 
        $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            while($row=mysqli_fetch_assoc($ejecutarquery)){
                $html.= '<option value="P'.$row['id'].'">'.$row['nombre'].'</option>';
            }
        }
    $html.='</optgroup><optgroup label="Contacts">';
        $sql="SELECT * FROM amr_contacts ORDER BY nombre;"; 
        $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            while($row=mysqli_fetch_assoc($ejecutarquery)){
                $html.= '<option value="C'.$row['id'].'">'.$row['nombre'].' - '.$row['puesto'].'</option>';
            }
        }
    $html.='</optgroup><optgroup label="Companies">';
        $sql="SELECT * FROM amr_companies ORDER BY nombre;"; 
        $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            while($row=mysqli_fetch_assoc($ejecutarquery)){
                $html.= '<option value="E'.$row['id'].'">'.$row['nombre'].'</option>';
            }
        }
    $html.='</optgroup>';
    return $html;    
}    
//echo de para usarse en los selects con js
function categosJS(){
    global $link;        
    $html='var categos = [';
    $sql="SELECT * FROM amr_products_meta  WHERE tipo='categoria' ORDER BY nombre ASC;"; 
    $ejecutarquery=mysqli_query($link,$sql); 
    if(mysqli_num_rows($ejecutarquery)>0){
        while($row=mysqli_fetch_assoc($ejecutarquery)){
            $html.= "[".$row['padre'].',"'.$row['nombre'].'",'.$row['id'].','.$row['nivel'].'],';
        }
    }
    $html.='];';
    return $html;
}
function prodsJS(){
    global $link;        
    $html='var prods = [';
    $sql="SELECT * FROM amr_products ORDER BY categoria1 ASC, nombre ASC;"; 
    $ejecutarquery=mysqli_query($link,$sql); 
    if(mysqli_num_rows($ejecutarquery)>0){
        while($row=mysqli_fetch_assoc($ejecutarquery)){
            $html.= '["'.$row['nombre'].'",'.$row['id'].',"'.$row['categoria1'].'"],';
        }
    }
    $html.='];';
    return $html;
}
function fabricanteJS(){
    global $link;        
    $html='var fabricante = [';
    $sql="SELECT * FROM amr_companies WHERE tipo='fabricante' ORDER BY nombre ASC;"; 
    $ejecutarquery=mysqli_query($link,$sql); 
    if(mysqli_num_rows($ejecutarquery)>0){
        while($row=mysqli_fetch_assoc($ejecutarquery)){
            $html.= '["'.$row['id'].'","'.$row['nombre'].'","'.$row['descripcion'].'"],';
        }
    }
    $html.='];';
    return $html;
}
function empreJS(){
    global $link;        
    $html='var empre = [';
    $sql="SELECT * FROM amr_companies ORDER BY nombre ASC;"; 
    $ejecutarquery=mysqli_query($link,$sql); 
    if(mysqli_num_rows($ejecutarquery)>0){
        while($row=mysqli_fetch_assoc($ejecutarquery)){
            $html.= '["'.$row['id'].'","'.$row['nombre'].'","'.$row['descripcion'].'"],';
        }
    }
    $html.='];';
    return $html;
}
function asignJS($proy){//hace el multi select
    global $link;     
    $html='';
    if(isset($proy) and $proy>0 ){        
        $sql="SELECT * FROM amr_projects_meta WHERE (meta='empresa' OR meta='contacto') AND proyecto='".$proy."';"; 
        $ejecutarquery=mysqli_query($link,$sql); 
        if(mysqli_num_rows($ejecutarquery)>0){
            while($row=mysqli_fetch_assoc($ejecutarquery)){
                if($row["meta"] == 'empresa'){$val="E";}else{$val="C";}
                $val.=$row["valor"];
                $html.= '$("select.select2-multiple option[value='.$val.']").prop("selected", true);';
            }
        }
        $html.='$("select.select2-multiple").select2(); /*esto hace refresh de los valores guardados*/';
    }
    return $html;
}
function calJS(){//hace el multi select
    global $link;     
    $html='';        
    $sql="SELECT * FROM amr_calendar;"; 
    $ejecutarquery=mysqli_query($link,$sql); 
    if(mysqli_num_rows($ejecutarquery)>0){
        $i=0;
        while($row=mysqli_fetch_assoc($ejecutarquery)){
            if($i > 0){$html.=", ";}$i++;
            if($row["meta"] == 'empresa'){$sql="SELECT * FROM amr_companies WHERE id='".$row["valor"]."'";$liga="company-view.php";$l="E";}
            if($row["meta"] == 'contacto'){$sql="SELECT * FROM amr_contacts WHERE id='".$row["valor"]."'";$liga="contact-view.php";$l="C";}
            if($row["meta"] == 'proyecto'){$sql="SELECT * FROM amr_projects WHERE id='".$row["valor"]."'";$liga="project.php";$l="P";}
            $ejecutarquery2=mysqli_query($link,$sql); 
            if(mysqli_num_rows($ejecutarquery2)>0){$row2=mysqli_fetch_assoc($ejecutarquery2);
                $html.= '{
                title: "'.$row["titulo"].' - <a href=\"./'.$liga."?id=".$row["valor"].'\" target=\"_blank\">'.$row2["nombre"].'",
                start: "'.$row["empieza"].'",
                end: "'.$row["termina"].'",
                className: "'.$row["estado"].' es-evento id-es-'.$row["id"].' tit-es-'.str_replace(" ", "_",$row["titulo"]).' st-es-'.str_replace(":", "_",$row["empieza"]).' end-es-'.str_replace(":", "_",$row["termina"]).' bg-es-'.$row["estado"].' q-es-'.$l.$row["valor"].'",
                }';
            }
        }
    }
    return $html;
}
//borra elementos DBB
if(isset($_GET['delete']) ){
    global $link;
    if(strpos($uri,'product-view.php') ){$tabla="amr_products";$newurl='product-view.php';}
    if(strpos($uri,'product-cat.php') ){$tabla="amr_products_meta";$newurl='product-cat.php';}
    if(strpos($uri,'product-attr.php') ){$tabla="amr_products_meta";$newurl='product-attr.php';}
    if(strpos($uri,'company-view.php') ){$tabla="amr_companies";$newurl='company-view.php';}
    if(strpos($uri,'contact-view.php') ){$tabla="amr_contacts";$newurl='contact-view.php';}
    if(strpos($uri,'project-view.php') ){$tabla="amr_projects";$newurl='project-view.php';}
    if(strpos($uri,'calendar-view.php') ){$tabla="amr_calendar";$newurl='calendar-view.php';}
 
    $sql="SELECT nombre FROM ".$tabla."  WHERE id='".$_GET['delete']."' LIMIT 1;"; 
    if(strpos($uri,'calendar-view.php') ){$tabla="amr_calendar";$newurl='calendar-view.php';}
    $ejecutarquery=mysqli_query($link,$sql); 
    if(mysqli_num_rows($ejecutarquery)>0){
        $row=mysqli_fetch_assoc($ejecutarquery);
        $nombre=$_GET['delete']." - ".$row["nombre"];
    }else{
        $nombre=$_GET['delete'];
    }
    $sql = " DELETE FROM ".$tabla."  WHERE id='".$_GET['delete']."';"; 
    $ejecutarquery=mysqli_query($link,$sql);
    header("Location: ./".$newurl."?deleted=".urlencode($nombre) );
    //echo '<script>window.location.replace("'.$newurl.'");</script>';
}   
if(isset($_GET['deleted']) ){
    $warning= '<div class="alert alert-primary alert-dismissible fade show" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    Deleted: '.urldecode($_GET['deleted']).'
                </div>';//.$sql;//.json_encode($_POST).
}
//Guarda forms y actualiza tambien
if(isset($_POST['botonnuevo'])){
    $exitosubir = fileupload ($_FILES,$extensionesValidas,(10*1000000),$rutamultimedia); 
    //echo '<script>alert("$$$$$$$$ '.$exitosubir.' ")</script>';//algo se subio
    
    if(strpos($exitosubir, 'No file uploaded') !== false){//nada se subio
        //echo '<script>alert(" '.$exitosubir.' ")</script>';
    }else{//algo paso
        if(strpos($uri, 'product-') !==false ){//solo en nuevos, al cambiar usa el campo texto
            //echo '<script>alert("prod- '.$exitosubir.' ")</script>';
            $_POST["archivo"] = $exitosubir;//cuando guardas en meta, el campo se llama valor
        }
        if(strpos($uri, 'settings') !==false or strpos($uri, 'contact') !==false or strpos($uri, 'company') !==false ){//solo en nuevos, al cambiar usa el campo texto
            //echo '<script>alert("set- '.$exitosubir.' ")</script>';
            $_POST["img"] = $exitosubir;//cuando guardas en meta, el campo se llama valor
        }
        //echo '<script>alert("p- '.$exitosubir.' ")</script>';
    }
    if($_POST['botonnuevo']==='producto' ){$tabla = "amr_products";}
    if($_POST['botonnuevo']==='categoria' ){$tabla = "amr_products_meta";}
    if($_POST['botonnuevo']==='atributo' ){$tabla = "amr_products_meta";}
    if($_POST['botonnuevo']==='contacto' ){$tabla = "amr_contacts";}
    if($_POST['botonnuevo']==='empresa' ){$tabla = "amr_companies";}
    if($_POST['botonnuevo']==='productoImg' ){$tabla = "amr_products";}
    if($_POST['botonnuevo']==='settingImg' ){$tabla = "amr_users";}
    if($_POST['botonnuevo']==='proyecto' ){$tabla = "amr_projects";}
    if($_POST['botonnuevo']==='calendario' ){$tabla = "amr_calendar";}

    if(!isset($_POST['idcambiar']) or empty($_POST['idcambiar']!="") or $_POST['idcambiar']=="" ){//si es nuevo
        $sql = " INSERT INTO ".$tabla."  ("; 
        $sql2=" VALUES (";
        foreach( $_POST as $key=>$feach){
            if($key == 'idcambiar' || $key == 'MAX_FILE_SIZE' || $key == 'file' || $key == 'botonnuevo' || $key == 'asignado' || $key == 'event4' || $key == 'event5' ){
                //boton nuevo no siempre es el ultimo
                //nada esas las tira
            }else{
                $sql .= $key.","; 
                $sql2.= "'".mysqli_real_escape_string($link,$feach)."',";
            }
        }
        $sql=substr($sql, 0, -1);
        $sql2=substr($sql2, 0, -1);//remove last ,
        $sql .= ")"; //cierra
        $sql2.= ")";            

        $sql=$sql.$sql2." ;";
        $warning= '<div class="alert alert-primary alert-dismissible fade show" role="alert">
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        Saved:<br>'.str_replace(",", " - ",str_replace(")", "",str_replace("(", "",str_replace(" VALUES ", "", $sql2)))).'
                    </div>';//.$sql."<br />".json_encode($_POST)."<br />".$uri;   
        $ejecutarquery=mysqli_query($link,$sql);
        $ultid = mysqli_insert_id($link);
    }else{//si es editar
        $sql="";//las suma de todos los updates
        foreach( $_POST as $key=>$feach){
            if($key == 'idcambiar' || $key == 'MAX_FILE_SIZE' || $key == 'file' || $key == 'botonnuevo' || $key == 'asignado' || $key == 'event4' || $key == 'event5' ){
                //boton nuevo no siempre es el ultimo
                //nada esas las tira
            }else{
                $sql2 = " UPDATE ".$tabla."  SET ultmodif= CURRENT_TIMESTAMP, ".$key."='".mysqli_real_escape_string($link,$feach)."'  WHERE id='".$_POST['idcambiar']."';"; 
                $ejecutarquery=mysqli_query($link,$sql2);
                $sql.= $sql2;
            }
        }
        if(isset($_POST['nombre']) ){$nombre=$_POST['nombre'];}elseif(isset($_POST['titulo']) ){$nombre=$_POST['titulo'];}
        $warning= '<div class="alert alert-primary alert-dismissible fade show" role="alert">
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        Updated: '.$_POST['idcambiar']." - ".$nombre.'
                    </div>';//.$sql."<br />".json_encode($_POST)."<br />".$uri;    
        $ultid = $_POST['idcambiar'];
    }
    
    //los selects multiples llevan un valor especial. Que siempre se borra todo y se reescribe de nuevo si es que es editado. Con JQuery los valores del select multiple se guardan en un input hidden e igual de regreso
    if(isset($_POST['asignado']) ){
        $sql = " DELETE FROM amr_projects_meta WHERE proyecto='".$ultid."' AND (meta='contacto' OR meta='empresa');";
        $ejecutarquery=mysqli_query($link,$sql);
        $i=0; foreach( $_POST["asignado"] as $key=>$feach){  
            if($feach!="NINGUNO"){//siempre mandas uno que se llama ninguno para poder borrar todos
                if(strpos($feach, 'C') !== false){$que="contacto";}else{$que="empresa";}
                $cual=str_replace("C", "",str_replace("E", "", $feach));
                $sql = " INSERT INTO amr_projects_meta (proyecto,meta,valor) VALUES ('".$ultid."','".$que."','".$cual."');";
                $ejecutarquery=mysqli_query($link,$sql);                
            }
        $i++;}
        //$warning.="<br />La ult id es: ".$ultid;
    }
    //if(isset($_POST['event5']) ){$_POST['event4']=$_POST['event5'];}
    if(isset($_POST['event4']) ){
                if(strpos($_POST['event4'], 'C') !== false){$que="contacto";}
                if(strpos($_POST['event4'], 'E') !== false){$que="empresa";}
                if(strpos($_POST['event4'], 'P') !== false){$que="proyecto";}
                $cual=str_replace("P", "",str_replace("C", "",str_replace("E", "", $_POST['event4'])));
                $sql = " UPDATE amr_calendar SET ultmodif= CURRENT_TIMESTAMP, meta='".$que."', valor='".$cual."'  WHERE id='".$ultid."';";
                $ejecutarquery=mysqli_query($link,$sql);                
        //$warning.="<br />La ult id es: ".$ultid.$sql;
    }
        
unset($_POST);//para que no siga actualizando cada refresh
}
//sube y borra archivos del ftp    
function fileupload ($files,$ExtensionesValidas,$TamanoMaximo,$ruta){
    if(isset($files['file']) ){
	    $ArchivoNombre=$files['file']['name'];
        $ArchivoTemporal=$files['file']['tmp_name'];
        $ArchivoTamano=$files['file']['size'];
        $ArchivoError=$files['file']['error'];
        $ArchivoTipo=$files['file']['type'];
         
        $PartirNombre= explode('.',$ArchivoNombre);
        $Extension= '.'.end($PartirNombre);
        $Nombre = str_replace($Extension ,'',$ArchivoNombre);
        $ExtensionMinusculas= strtolower(end($PartirNombre));
        
        //Revisa Errores y si no hay lo sube
        if( empty($ExtensionMinusculas) ){
            return 'No file uploaded';	
		}elseif (!in_array($ExtensionMinusculas,$ExtensionesValidas)){//prueba todo el array en la variable
            return 'Invalid file extension';
        }elseif($ArchivoError!=0)//Checa si hubo error al subir el archivo
            {return 'Error while uploading, try again';}
        elseif($ArchivoTamano>$TamanoMaximo)//1000kb=1mb
            {return "File too heavy, it is ".(floor($ArchivoTamano/1000000*100)/100)." mb. Limit is ".($TamanoMaximo/1000000)." MB";}//substr trunca el string del caracter 0 al 3
        else//Exito y se sube el archivo
            {
				//El nombre nuevo debe ser único Si No se Reescribe, pero también debes tener una forma con la BDD SQL de llamarlo 
				//Ya sea guardando la ruta en BDD o renombrando el archivo de cierta manera
				date_default_timezone_set('America/Mexico_City');    // Choose local time
				$FechaHora = date('d.m.Y-G.i', time());              // Get local time //REPLANCHA TODO EN EL MISMO MINUTO
				$NuevoNombre= $Nombre.'-'.$FechaHora.'.'.$ExtensionMinusculas;
				//return $NuevoNombre;

				$RutaArchivo=$_SERVER['DOCUMENT_ROOT'] . $ruta .'/'.$NuevoNombre;//esto cambia de servidor a servidor 
				//$RutaArchivo='archivossubidos/'.$NuevoNombre;
				if (  move_uploaded_file($ArchivoTemporal,$RutaArchivo) ) {
					//return '<script>alert("'.$ArchivoNombre.' uploaded OK!");</script>';
					//Ahora guardas el nombre del archivo en SQL de alguna forma 
					return $ruta .'/'.$NuevoNombre;//si el return no tiene alert, fue exito y ya solo guardas la ruta
				} else {
					return 'Error while uploading, contact site admin and share this:\n Temp:'.$ArchivoTemporal.' \n Final:'.$RutaArchivo.'';
				}
            }
    }else{
            return 'No file uploaded';	        
    }
}    
if(isset($_POST['botonborrarfiles'])){
$warning='<div class="alert alert-primary alert-dismissible fade show" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            '.'Erased ('.$_POST['botonborrarfiles'].')'.'
            </div>'; 
unlink($_POST['botonborrarfiles']);//esto lo borra
unset($_POST);//para que no siga actualizando cada refresh
}
//Esto crea y remplaza la base de datos
function listabackups($path){//es igual a archivos solo cambian los botones y columnas
	$output='';   
    $files = scandir($path);
    $i=0; foreach( $files as $key=>$feach){  
        if($feach !== '..' and $feach !== '.'){
            $output.="<tr>";
            $output.= "<td>".($i+1)."</td><td>        
            <button type='submit' name='botonborrarfiles' class='btn btn-danger waves-effect waves-light btn-xs' value='".$path."/".$feach."'>Delete</button></td><td>
            <button type='submit' name='botonrestore' class='btn btn-info waves-effect waves-light btn-xs' value='".$path."/".$feach."'>Restore</button>
                </td>";
            //<button type='submit' name='botonborrar' class='btn btn-danger' value='".$path."/".$feach."'>Borrar ".$feach."</button>
            $output.=  '<td>'.str_replace(".sql", "", $feach).'
                </td>';	//<a href="'.$path.'/'.$feach.'" target="_blank">'.$path.'/'.$feach.'</a>
                
            $output.="</tr>";
        }else{}
    $i++;}
	return $output;    
}
function creabackupbdd($backupfile,$host_name,$user_name,$password,$database){//La ruta y el nombre del archivo
    $backupfile=$backupfile."".date("Y.m.d")."-". date("Hi").".sql";

    //Export of the database and output of the status
    $command='mysqldump --opt -h' .$host_name .' -u' .$user_name .' -p' .$password .' ' .$database .' > ' .$backupfile;
    exec($command,$output,$worked);
    switch($worked){
        case 0:
            return 'Backup created successfully in '.getcwd().' ' .$backupfile ;
        break;
        case 1:
            return 'Error during backup of '.getcwd().'   ' .$backupfile ;
        break;
        case 2:
            return 'Error, check DB log';
        break;
    }
}
function restaurarbdd($backupfile,$host_name,$user_name,$password,$database){//La ruta y el nombre del archivo
    //Import of the database and output of the status
    $command='mysql -h' .$host_name .' -u' .$user_name .' -p' .$password .' ' .$database .' < ' .$backupfile;
    exec($command,$output,$worked);
    switch($worked){
    case 0:
        return 'Restore of '.$backupfile .' successful to ' .$database ;
    break;
    case 1:
        return 'Error, check DB log and path.';
    break;
    }
}
if(isset($_POST['botonbackup'])){
$warning='<div class="alert alert-primary alert-dismissible fade show" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            '.creabackupbdd('./backups/',$host_name,$user_name,$password,$database).'
            </div>'; 
unset($_POST);//para que no siga actualizando cada refresh
}
if(isset($_POST['botonrestore'])){
$warning='<div class="alert alert-primary alert-dismissible fade show" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            '.restaurarbdd($_POST['botonrestore'],$host_name,$user_name,$password,$database).'<h3 style="color:red">Review your email and password (refresh this page) before logging out, it got restored to that point in time. Do this in order to prevent being locked out (update if necessary).</a></h3>'.'
            </div>'; 
unset($_POST);//para que no siga actualizando cada refresh
}

{
$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>
';}
}

?>