<?php
// 1. CONFIGURAÇÕES E ERROS
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Sao_Paulo');

// 2. CONEXÃO
$config_encontrado = false;
$caminhos = ['../loja/config.php', '../config.php', 'config.php'];
foreach ($caminhos as $caminho) {
    if (file_exists($caminho)) {
        include_once($caminho);
        $config_encontrado = true;
        break;
    }
}

// 3. LÓGICA DE AÇÕES (DAR BAIXA OU EXCLUIR)
if ($config_encontrado && isset($_GET['baixa'])) {
    $id_v = (int)$_GET['baixa'];
    $conn->query("UPDATE animais_eventos SET realizado = 1 WHERE id = $id_v");
    header("Location: vacinas.php?msg=sucesso"); exit;
}

if ($config_encontrado && isset($_GET['excluir'])) {
    $id_e = (int)$_GET['excluir'];
    $conn->query("DELETE FROM animais_eventos WHERE id = $id_e");
    header("Location: vacinas.php?msg=excluido"); exit;
}

// 4. PROCESSAR NOVA VACINA (POST)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['btn_salvar'])) {
    $animal_id = (int)$_POST['animal_id'];
    $data_v    = mysqli_real_escape_string($conn, $_POST['data_evento']);
    $tipo      = mysqli_real_escape_string($conn, $_POST['tipo']);
    $desc      = mysqli_real_escape_string($conn, $_POST['descricao']);
    
    $sql = "INSERT INTO animais_eventos (animal_id, data_evento, tipo, descricao, realizado) 
            VALUES ($animal_id, '$data_v', '$tipo', '$desc', 0)";
    $conn->query($sql);
    header("Location: vacinas.php?msg=cadastrado"); exit;
}

// 5. BUSCA DE DADOS
$vacinas = [];
$animais_list = [];
$filtro_animal = isset($_GET['animal_id']) ? (int)$_GET['animal_id'] : 0;

if ($config_encontrado && isset($conn)) {
    // Lista de animais para o SELECT do formulário
    $res_a = $conn->query("SELECT id, nome FROM animais_cadastros ORDER BY nome ASC");
    while($row = $res_a->fetch_assoc()) $animais_list[] = $row;

    // Busca das vacinas/eventos
    $where = $filtro_animal > 0 ? "WHERE e.animal_id = $filtro_animal" : "";
    $sql = "SELECT e.*, a.nome as nome_animal 
            FROM animais_eventos e 
            JOIN animais_cadastros a ON e.animal_id = a.id 
            $where 
            ORDER BY e.realizado ASC, e.data_evento ASC";
    $res = $conn->query($sql);
    if($res) while($row = $res->fetch_assoc()) $vacinas[] = $row;
}
?>

<?php if(file_exists('../header.php')) include_once('../header.php'); ?>

<style>
    .container-vacinas { padding: 10px; }
    .card-vacina { background: #fff; border-radius: 5px; border-top: 5px solid #f57c00; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 15px; margin-bottom: 20px; }
    .tabela-v { width: 100%; border-collapse: collapse; font-size: 11px; }
    .tabela-v th { background: #f8f9fa; padding: 8px; border-bottom: 2px solid #dee2e6; }
    .tabela-v td { padding: 8px; border-bottom: 1px solid #eee; }
    .status-pendente { color: #d32f2f; font-weight: bold; }
    .status-feito { color: #2e7d32; font-weight: bold; text-decoration: line-through; opacity: 0.6; }
    .form-inline-custom { display: flex; flex-wrap: wrap; gap: 10px; background: #fff3e0; padding: 10px; border-radius: 5px; margin-bottom: 15px; align-items: flex-end; }
    .form-group-custom { display: flex; flex-direction: column; }
    .form-group-custom label { font-size: 9px; font-weight: bold; margin-bottom: 2px; }
</style>

<div class="container-vacinas">

    <div class="card-vacina">
        <h5 style="color: #f57c00; font-weight: bold; font-size: 13px;">💉 LANÇAR NOVA VACINA / EVENTO</h5>
        <form method="POST" class="form-inline-custom">
            <div class="form-group-custom">
                <label>ANIMAL</label>
                <select name="animal_id" class="form-control form-control-sm" required style="width: 150px;">
                    <option value="">SELECIONE...</option>
                    <?php foreach($animais_list as $al): ?>
                        <option value="<?php echo $al['id']; ?>" <?php echo $filtro_animal == $al['id'] ? 'selected' : ''; ?>>
                            <?php echo $al['nome']; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group-custom">
                <label>DATA</label>
                <input type="date" name="data_evento" class="form-control form-control-sm" required value="<?php echo date('Y-m-d'); ?>">
            </div>
            <div class="form-group-custom">
                <label>TIPO</label>
                <select name="tipo" class="form-control form-control-sm">
                    <option value="VACINA">VACINA</option>
                    <option value="VERMIFUGO">VERMÍFUGO</option>
                    <option value="CONSULTA">CONSULTA</option>
                    <option value="OUTRO">OUTRO</option>
                </select>
            </div>
            <div class="form-group-custom">
                <label>DESCRIÇÃO (NOME DA VACINA)</label>
                <input type="text" name="descricao" class="form-control form-control-sm" placeholder="EX: V10, RAIVA..." required style="width: 180px;">
            </div>
            <button type="submit" name="btn_salvar" class="btn btn-sm btn-warning" style="font-weight: bold; color: #fff;">GRAVAR</button>
        </form>
    </div>

    <div class="card-vacina" style="border-top-color: #333;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
            <h5 style="margin:0; font-weight: bold; font-size: 13px;">📋 HISTÓRICO / AGENDA</h5>
            <?php if($filtro_animal > 0): ?>
                <a href="vacinas.php" class="btn btn-xs btn-outline-secondary" style="font-size: 9px;">VER TODOS</a>
            <?php endif; ?>
        </div>

        <div class="table-responsive">
            <table class="tabela-v">
                <thead>
                    <tr>
                        <th>DATA</th>
                        <th>ANIMAL</th>
                        <th>TIPO</th>
                        <th>DESCRIÇÃO</th>
                        <th>STATUS</th>
                        <th style="text-align: center;">AÇÕES</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($vacinas)): ?>
                        <tr><td colspan="6" style="text-align:center; padding: 15px;">NENHUM REGISTRO ENCONTRADO.</td></tr>
                    <?php else: ?>
                        <?php foreach($vacinas as $v): ?>
                        <tr>
                            <td><strong><?php echo date('d/m/Y', strtotime($v['data_evento'])); ?></strong></td>
                            <td><?php echo $v['nome_animal']; ?></td>
                            <td><small class="badge badge-light"><?php echo $v['tipo']; ?></small></td>
                            <td><?php echo $v['descricao']; ?></td>
                            <td>
                                <?php if($v['realizado']): ?>
                                    <span class="status-feito">APLICADO</span>
                                <?php else: ?>
                                    <span class="status-pendente">PENDENTE</span>
                                <?php endif; ?>
                            </td>
                            <td style="text-align: center;">
                                <?php if(!$v['realizado']): ?>
                                    <a href="vacinas.php?baixa=<?php echo $v['id']; ?>" class="btn btn-xs btn-success" title="DAR BAIXA" style="font-size: 9px; padding: 1px 5px;">CONCLUIR</a>
                                <?php endif; ?>
                                <a href="javascript:if(confirm('EXCLUIR REGISTRO?')) window.location.href='vacinas.php?excluir=<?php echo $v['id']; ?>'" class="btn btn-xs btn-danger" style="font-size: 9px; padding: 1px 5px;">✖</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>