<?php
    @session_start();
    @header( "Content-type: text/html; charset=utf-8" );
    if (!isset($_SESSION["admin"]["id"])) {
        echo "<script>location.href='index.php';</script>";
    }
?>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" src="js/https://apis.google.com/js/platform.js"></script>
<h1 class="page-header">
    
    	<div class="row">
    		<div class="col-md-7 col-sm-6">
    			Relatórios de Envios
            </div>

    	</div>
    
</h1>

<div class="container" style="width: 90%">

<form name="form1" method="post" class="form-inline text-center">
    <label for="parceiro_id">Parceiro:
    <select name="parceiro_id" class="form-control" required>
        <option value="">Todos</option>
        <?php
            $sql = "select * from parceiro order by nome";
            $res = $db->prepare($sql);
            $res->execute();
            while ( $dados = $res->fetch(PDO::FETCH_OBJ)) {
                echo "<option value='$dados->id'>$dados->nome</option>";
            }
        ?>
    </select>
    </label>

    <label for="mes">Mês:
    <select name="mes" class="form-control" required>
        <option value=""></option>
        <?php
            $i = date("m")+1;
            while ( $i > 0 ) {
                $i--;
                echo "<option value='$i'>$i</option>";
            }
        ?>
    </select></label>

    <button type="submit" class="btn btn-success">
        <i class="glyphicon glyphicon-search"></i> Listar
    </button>

</form>



<table class="table table-bordered table-hover table-striped" id="tabela">
	<thead>
		<tr>	
			<td>Data</td>
			<td>Empresa</td>
			<td>CNPJ</td>
			<td>Arquivo</td>
            <td>Opções</td>
		</tr>
	</thead>
    <?php
    if ( $_POST ) {
        $parceiro_id = $_POST["parceiro_id"];
        $mes = $_POST["mes"];

        if ( $mes < 10 ) $mes = "0$mes";
        $ano = date("Y");
        $data = "$ano-$mes%";

        $sql = "select c.*, c.id cid, a.id aid from cliente c
            inner join arquivo a on (c.id = a.cliente_id)
            left join envio e on (e.arquivo_id = a.id)
            where e.data like '$data' 
            AND c.parceiro_id = ".(int)$parceiro_id."
            order by c.nome";

        $consulta = $db->prepare($sql);
        $consulta->execute();

        while ( $dados = $consulta->fetch(PDO::FETCH_OBJ)) {

            echo "<tr>
                <td>$data</td><td>$dados->nome</td><td>$dados->cnpj</td><td>
                <a href=\"javascript:window.open('downloads.php?id=$dados->aid&cliente_id=$dados->cid')\" class='btn btn-success'>
                    <i class='glyphicon glyphicon-save'></i>
                </a>
                </td><td>

                </td></tr>";

        }

    }
?>
</table>
