<?php

$status = array("cancelado", "em espera", "processando", "concluído");
$car_id = 0;
$loc_id = 0;
for ($i = 1; $i <= $_REQUEST["registros"]; $i++) {
    //Campos gerados para a tabela TRANSACTION.
    if ($i % 3 == 0 || $i == 1) {
        $tra_lat = Faker\Geo::latitude(\Faker\Geo\SaoPaulo::bounds());
        $tra_lon = Faker\Geo::longitude(\Faker\Geo\SaoPaulo::bounds());
        $usr_token = md5(uniqid(rand(), true));
        $car_id++;
        $loc_id++;
    }
    $tra_confirmationcode = md5(uniqid(rand(), true));
    $tra_date = (int) (microtime(true) * 1000);
    //$tra_date = (int) (rand(1400965802, microtime(true)) * 1000);
    $tra_status = $status[array_rand($status)];
    $tra_value = number_format(mt_rand() / mt_getrandmax() * 1000, 2);
    try {
        $statement = $connection->queryAsync('INSERT INTO ' . $namespace . ' (
                    usr_token,
                    tra_id,
                    car_id,
                    loc_id,
                    tra_confirmationcode,
                    tra_date,
                    tra_lat,
                    tra_lon,
                    tra_status,
                    tra_value,
    }
    $limite = floor($porcentagem / 100 * count($rows1));
    $response2 = $connection->querySync('SELECT *
                                      FROM ' . $namespace . " WHERE tra_alt = 'n'" . 'LIMIT ' . $limite);
    $rows2 = $response2->fetchAll();
} catch (Cassandra\Exception $e) {
    //echo 'Caught exception: ',  $e->getMessage(), "\n";
    //exit;
}
foreach ($rows2 as $row) {
    $usr_token[] = $row["usr_token"];
    $tra_id[] = $row["tra_id"];
}
$dados = array_combine($tra_id, $usr_token);
$dados = array_unique($dados);
foreach ($dados as $tra_id => $usr_token) {
    //recupera lista de dados alterados no momento
    $ids[] = $tra_id;
    try {
        $statement = $connection->querySync('UPDATE ' . $namespace . ' SET tra_alt = :tra_alt,
                tra_lat = :tra_lat,
                tra_lon = :tra_lon
            WHERE usr_token = ' . "'" . $usr_token . "'" . ' AND tra_id = ' . $tra_id, [new Cassandra\Type\Varchar("s"), new Cassandra\Type\Float(Faker\Geo::latitude(\Faker\Geo\NewYork::bounds())), new Cassandra\Type\Float(Faker\Geo::longitude(\Faker\Geo\NewYork::bounds()))]);
        $update = $statement->fetchAll();
        $tokenAnterior = $row["usr_token"];
    } catch (Cassandra\Exception $e) {
        //echo 'Caught exception: ',  $e->getMessage(), "\n";
        //exit;//if connect failed it may be good idea not to continue
    }
}
$ids = implode(",", $ids);