<?php
    header("Content-Type:application/json");
    include("../connection.php");
    $errMsg = "";
    if (!isset($_REQUEST["sessid"])     || empty($_REQUEST["sessid"]) ) { $errMsg .= "No se recibio el Parametro sessid. "; }
    if (!isset($_REQUEST["records"])    || empty($_REQUEST["records"])) { $errMsg .= "No se recibio el Parametro records. "; }
    

    $sessid  = preg_replace("/[^a-zA-Z0-9]/", "", $db->real_escape_string($_REQUEST["sessid"]));
    $records = preg_replace("/[^0-9\|]/", "", $db->real_escape_string($_REQUEST["records"]));
    
    $salida = new stdClass();
    
    if(!empty($errMsg)){
        http_response_code(401);
        $salida->rsp = false ;
        $salida->msg = $errMsg;
        echo (json_encode($salida));
        return;
    }
        
    mysqli_query($db, "SET lc_time_names = 'es_ES'");
    
    /* Se valida el usuario y la session */
    $sql =  "SELECT id, accs_approve FROM users ".
            "WHERE  sessionid = ? AND IF(CURDATE()<sessionvalidthru, 1, 0)" ;
    
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("s", $sessid);

    //Validamos la ejecución
    if (!($stmt->execute())){
        http_response_code(500);
        $salida->rsp = false ;
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }
    
    //Obtenemos los resultados y recorremos
    $result = $stmt->get_result();
    if (!($rs = mysqli_fetch_array($result))){
        switch (mysqli_errno($db)){
        case 0:
            http_response_code(401);
            $salida->rsp = false ;
            $salida->msg = "Sesión invalida o terminada";
            echo (json_encode($salida));
            return;
            break;
        default:
            http_response_code(500);
            $salida->rsp = false ;
            $salida->msg = mysqli_error($db);
            echo (json_encode($salida));
            return;
            break;
        }
    }

    // Se verifica si tiene permiso
    if ($rs["accs_approve"]*1 < 1){
        http_response_code(401);
        $salida->rsp = false ;
        $salida->msg = "No tiene los privilegios para aprobación";
        $salida->name = $rs["name"];
        $salida->accs = $rs["accs_approve"]*1;
        $salida->sessid = $sessid;
        echo (json_encode($salida));
        return;
    }


    $lista = str_replace("|", ",", $records);
    
    $records = explode("|", $records);
    $no_recs = count($records);
    $success = array();
    
    
    //$sql = "UPDATE retislr SET status = 1 WHERE (repdate IS NULL OR repdate='0000-00-00 00:00:00' ) AND documentid IN (?)";
    $sql = "UPDATE retislr SET status = 1 WHERE (repdate IS NULL OR CAST(repdate AS CHAR)='0000-00-00 00:00:00') AND documentid IN (?)";
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("s", $lista);

    //Validamos la ejecución
    if (!($stmt->execute())){
        http_response_code(200);
        $salida->rsp        = false;
        $salida->msg        = "Ocurrió un error al aprobar: " . mysqli_error($db);
        echo (json_encode($salida));    
        return;
    }
    $no_recs = mysqli_affected_rows($db);
    //$sql = "UPDATE retiva SET status = 1 WHERE (repdate IS NULL OR repdate='0000-00-00 00:00:00' ) AND documentid IN (?)";
    $sql = "UPDATE retiva SET status = 1 WHERE (repdate IS NULL OR CAST(repdate AS CHAR)='0000-00-00 00:00:00') AND documentid IN (?)";
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("s", $lista);

    //Validamos la ejecución
    if (!($stmt->execute())){
        http_response_code(200);
        $salida->rsp        = false;
        $salida->msg        = "Ocurrió un error al aprobar: " . mysqli_error($db);
        echo (json_encode($salida));    
        return;
    }
    if (mysqli_affected_rows($db)>$no_recs)
        $no_recs = mysqli_affected_rows($db);
        
    http_response_code(200);
    $salida->rsp        = true;
    $salida->msg        = "Se aprobaron " . $no_recs . " facturas satisfactoriamente";
    echo (json_encode($salida));    
    return;

    

    /*
    for ($i = 0; $i<$no_recs; $i++) {
        $document = $records[$i]*1;
        $sql = "SELECT retislr.id as islr_id, retiva.id as iva_id " .
               "FROM documents ".
               "LEFT JOIN retislr ON retislr.documentid = documents.id ".
               "LEFT JOIN retiva  ON retiva.documentid  = documents.id ". 
               "WHERE documents.id = " . $document;

        
        if (($qry = mysql_query($sql))){
            $rs = mysql_fetch_array($qry);
            $islr_update = true;
            $iva_update  = true;
            $islr_id = $rs["islr_id"]*1;
            $iva_id  = $rs["iva_id"]*1;


            if ($islr_id > 0){
                $sql = "UPDATE retislr SET status = 1 WHERE id = ". $islr_id;
                if ((!$qry = mysql_query($sql))){
                    $islr_update = false;
                }
            }    
            if ($iva_id > 0){
                $sql = "UPDATE retiva SET status = 1 WHERE id = ". $iva_id;
                if ((!$qry = mysql_query($sql))){
                    $islr_update = false;
                }
            }
            if ($islr_update && $iva_update){ 
                unset($records[$i]);                  // Se elimina variable de records
                array_push ( $success , $document );  // Se incluye en success
            } 
        }
    } 
    
    
    if (count($records) > 0){
        header("HTTP/1.1 200");
        $salida->rsp        = false;
        $salida->msg        = "Proceso incompleto, quedando pendiente ".count($records)." registros por actualizar.";
        $salida->records    = $records;
        echo (json_encode($salida));    
        return;
    }else{
        header("HTTP/1.1 200");
        $salida->rsp        = true;
        $salida->msg        = "Proceso completado con Éxito";
        $salida->records    = $success;
        echo (json_encode($salida));    
        return;
    }
    
    */
?>
