<?php
// cms/api/login/recover.php

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    
    // parametros obligatorios
    $parmsob = array("hash","pwd");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Definimos las variables y guardamos los datos recibidos por GET
    $hash = $_GET["hash"];
    $pwd = $_GET["pwd"];
    $out = new stdClass();
    
    $sql = "SELECT id, name, usr FROM cmsusers WHERE sessionid = '".mysqli_real_escape_string($db, $hash)."'";
    if (!$rs=$db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    $user = $rs->fetch_assoc();
    
    $sql =  "UPDATE cmsusers " .
            "SET    pwd = '".mysqli_real_escape_string($db, $pwd)."', ".
            "       sessionid = NULL ".
            "WHERE  sessionid='".mysqli_real_escape_string($db, $hash)."'";
    if (!$db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    if ($db->affected_rows == 0){
        badEnd("401", array("msg"=>"Hash incorrecto"));
    }
    
    // Retornamos mensaje de que todo fue exitoso
    $out->msg = "Contraseña cambiada satisfactoriamente";

    // Consultamos los datos del mensaje
    $sql = "SELECT * FROM cmsmessages WHERE id = 11";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $data = $rs->fetch_assoc();
    
    $subject = $data['name_esp'];
    $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
    $body = 
    "       <div style='background-color: #F8F8FA;padding: 20px;'>".
    "           <img style='margin: auto; display: block;margin-bottom:10px;' width='110' height='110' src='".$homeurlCMS."./settings/img/logo-email.png'/>".
    "           <div style='margin: auto; display: block;background-color: #FFF;border-radius: 22px;width: 60%;padding:30px;'>".
    "               <h1 class='goodText' style='color:#474C58;text-align:center;font-size: 20px;font-weight: bold;'>Hola ".$user['name']."</h1>".
    "               <p class='goodText' style='font-size: 18px;color: #474C58;text-align:center;margin-bottom:30px;margin-left:20px;margin-right:20px;'>".$data['dsc_esp']."</p>".
    "           </div>".
    "           <p class='copy' style='margin-top:40px; color: #767E93;text-align:center;font-family: Roboto, sans-serif;font-weight: 400;font-size: 12px;'>&copy; 2020 - ".$globname."</p>".
    "       </div>";
    
    enviarCorreo2($fromeMail, strtolower($user['usr']), $subject, $body);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>

