<?php
session_start();
require '../conexao.php';

// 1. SEGURANÇA
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

$user_name = $_SESSION['user_name'];

// --- CONFIGURAÇÃO DE FILTROS ---
$filtro_ordem = $_GET['ordem'] ?? 'valor_desc'; // Padrão: Maior valor primeiro
$filtro_dono = $_GET['dono'] ?? 'todos';        // Padrão: Ver todos
$paginaAtual = isset($_GET['pagina']) ? max(1, intval($_GET['pagina'])) : 1;
$itensPorPagina = 10; // Solicitado: 10 itens

// Construção da Query Dinâmica
$where_sql = "WHERE 1=1";
$params = [];

// 1. Filtro de Dono (Propriedade)
if ($filtro_dono == 'ocultar_meus') {
    $where_sql .= " AND user != :eu";
    $params[':eu'] = $user_name;
} elseif ($filtro_dono == 'somente_meus') {
    $where_sql .= " AND user = :eu";
    $params[':eu'] = $user_name;
}

// 2. Filtro de Ordenação
$order_sql = "ORDER BY ";
switch ($filtro_ordem) {
    case 'valor_desc': $order_sql .= "valor DESC"; break; // Maior Valor
    case 'valor_asc':  $order_sql .= "valor ASC"; break;  // Menor Valor
    case 'data_asc':   $order_sql .= "dataehora ASC"; break; // Mais Antiga
    case 'data_desc': 
    default:           $order_sql .= "dataehora DESC"; break; // Mais Recente
}

// --- PAGINAÇÃO (Contagem Total com Filtros) ---
$stmtCount = $pdo->prepare("SELECT COUNT(*) FROM ordens_compra $where_sql");
$stmtCount->execute($params);
$totalItens = $stmtCount->fetchColumn();
$totalPaginas = ceil($totalItens / $itensPorPagina);

// Ajuste de offset
$offset = ($paginaAtual - 1) * $itensPorPagina;

// --- BUSCA FINAL DE DADOS ---
$sql = "SELECT * FROM ordens_compra $where_sql $order_sql LIMIT :offset, :limit";
$stmt = $pdo->prepare($sql);

// Bind dos parâmetros de filtro
foreach ($params as $key => $val) {
    $stmt->bindValue($key, $val);
}
// Bind dos parâmetros de paginação
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $itensPorPagina, PDO::PARAM_INT);
$stmt->execute();
$ordens = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Função auxiliar para gerar links mantendo os filtros
function linkPagina($pag) {
    global $filtro_ordem, $filtro_dono;
    return "?pagina=$pag&ordem=$filtro_ordem&dono=$filtro_dono";
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ordens de Compra - Mavilla</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/dashboard.css">
    
    <style>
        /* === ESTILOS ESPECÍFICOS (NEON + TRANSPARÊNCIA) === */
        html, body { background: none !important; background-color: transparent !important; }
        body {
            background: url('../rpg-login-background.jpg') no-repeat center center fixed !important;
            background-size: cover !important;
            color: white;
            min-height: 100vh;
        }

        .container { max-width: 1000px; margin: 0 auto; padding: 20px; }

        /* Filtros Neon */
        .filter-card {
            background-color: rgba(0, 5, 30, 0.9);
            border: 2px solid var(--primary);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 0 15px rgba(0, 0, 255, 0.2);
            display: flex;
            gap: 15px;
            align-items: end;
            flex-wrap: wrap;
            justify-content: center;
        }
        
        .filter-group { display: flex; flex-direction: column; gap: 5px; flex-grow: 1; max-width: 300px; }
        .filter-group label { color: #ccc; font-size: 0.8rem; font-weight: bold; }
        
        select.neon-input {
            background: #000; color: #fff; border: 1px solid var(--primary);
            padding: 10px; border-radius: 5px; outline: none; width: 100%;
            cursor: pointer;
        }
        
        .btn-filter {
            background: var(--primary); color: #fff; border: none; padding: 10px 25px;
            border-radius: 5px; cursor: pointer; font-weight: bold; text-transform: uppercase;
            height: 40px;
        }
        .btn-filter:hover { background: #000; border: 1px solid var(--primary); box-shadow: 0 0 10px var(--neon-bright); }

        /* Tabela Neon */
        .table-container {
            overflow-x: auto;
            border: 2px solid var(--primary);
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,255,0.2);
            background: rgba(0, 0, 0, 0.85);
        }

        table { width: 100%; border-collapse: collapse; color: white; min-width: 600px; }
        thead { background-color: rgba(0, 0, 255, 0.2); border-bottom: 2px solid var(--primary); }
        th { padding: 15px; text-align: center; text-transform: uppercase; font-size: 0.9rem; color: var(--neon-bright); text-shadow: 0 0 5px var(--primary); }
        td { padding: 12px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); font-size: 1rem; }
        tr:last-child td { border-bottom: none; }
        tr:hover { background-color: rgba(255,255,255,0.05); }

        /* Tags e Botões */
        .price-tag { color: #28a745; font-weight: bold; font-size: 1.1rem; text-shadow: 0 0 5px rgba(40,167,69,0.5); }
        .date-tag { color: #aaa; font-size: 0.8rem; font-style: italic; }
        .qty-tag { font-weight: bold; color: #00f3ff; font-size: 1.1rem; }
        .buyer-tag { font-weight: bold; color: #fff; }

        .btn-delete {
            padding: 6px 15px; border-radius: 4px; font-weight: bold; text-transform: uppercase;
            font-size: 0.8rem; cursor: pointer; border: 1px solid #ff2222; background: transparent; color: #ff2222; transition: 0.3s;
        }
        .btn-delete:hover { background: #ff2222; color: #fff; box-shadow: 0 0 15px #ff2222; }

        .status-available {
            color: #28a745; font-weight: bold; text-transform: uppercase; font-size: 0.8rem;
            border: 1px solid #28a745; padding: 5px 10px; border-radius: 4px; background: rgba(40, 167, 69, 0.1);
        }

        /* Paginação */
        .pagination { display: flex; justify-content: center; gap: 5px; margin-top: 30px; flex-wrap: wrap; }
        .page-link {
            padding: 8px 12px; background: #000; border: 1px solid var(--primary); color: var(--primary);
            text-decoration: none; border-radius: 4px; font-weight: bold; font-size: 0.9rem;
        }
        .page-link:hover { background: var(--primary); color: #fff; box-shadow: 0 0 10px var(--primary); }
        .page-link.active { background: var(--primary); color: #fff; box-shadow: 0 0 15px var(--neon-bright); }
        .page-link.disabled { opacity: 0.5; pointer-events: none; border-color: #555; color: #555; }

        .btn-back {
            display: inline-block; padding: 10px 30px; background: #000; border: 2px solid var(--primary); color: #fff;
            border-radius: 8px; font-weight: bold; text-transform: uppercase; cursor: pointer; transition: 0.3s; text-decoration: none;
        }
        .btn-back:hover { background: var(--primary); color: #000; box-shadow: 0 0 15px var(--neon-bright); }
        
        .msg-box {
            background: rgba(0,0,0,0.8); border: 1px solid #ccc; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center;
        }
    </style>
</head>
<body>

    <div class="container">
        
        <div class="listing-header-centered" style="text-align:center; margin-bottom:30px;">
            <h1 style="font-size: 2.5rem; color:var(--primary); text-shadow:0 0 15px var(--primary); margin-bottom: 20px;">
                ORDENS DE COMPRA
            </h1>
            <a href="mercado.php">
                <button class="btn-back">Voltar ao Mercado</button>
            </a>
        </div>

        <?php if (isset($_SESSION['msg']) && !empty($_SESSION['msg'])): ?>
            <div class="msg-box">
                <?= htmlspecialchars($_SESSION['msg']) ?>
            </div>
            <?php $_SESSION['msg'] = ''; ?>
        <?php endif; ?>

        <form method="GET" class="filter-card">
            <div class="filter-group">
                <label>Ordenar Por:</label>
                <select name="ordem" class="neon-input">
                    <option value="valor_desc" <?= $filtro_ordem == 'valor_desc' ? 'selected' : '' ?>>Maior Valor (R$)</option>
                    <option value="valor_asc" <?= $filtro_ordem == 'valor_asc' ? 'selected' : '' ?>>Menor Valor (R$)</option>
                    <option value="data_desc" <?= $filtro_ordem == 'data_desc' ? 'selected' : '' ?>>Mais Recentes</option>
                    <option value="data_asc" <?= $filtro_ordem == 'data_asc' ? 'selected' : '' ?>>Mais Antigas</option>
                </select>
            </div>

            <div class="filter-group">
                <label>Exibir:</label>
                <select name="dono" class="neon-input">
                    <option value="todos" <?= $filtro_dono == 'todos' ? 'selected' : '' ?>>Todas as Ordens</option>
                    <option value="ocultar_meus" <?= $filtro_dono == 'ocultar_meus' ? 'selected' : '' ?>>Ocultar as Minhas</option>
                    <option value="somente_meus" <?= $filtro_dono == 'somente_meus' ? 'selected' : '' ?>>Somente as Minhas</option>
                </select>
            </div>

            <button type="submit" class="btn-filter"><i class="fas fa-filter"></i> Filtrar</button>
        </form>

        <?php if (count($ordens) > 0): ?>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>Qtd</th>
                            <th>Comprador</th>
                            <th>Valor Unitário</th>
                            <th>Data Publicação</th>
                            <th>Ação / Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($ordens as $row): 
                            $isMine = ($row['user'] == $user_name);
                        ?>
                            <tr>
                                <td><span class="qty-tag"><?= $row['quantidade'] ?></span></td>
                                <td><span class="buyer-tag"><?= htmlspecialchars($row['user']) ?></span></td>
                                <td><span class="price-tag">R$ <?= number_format($row['valor'], 2, ',', '.') ?></span></td>
                                <td><span class="date-tag"><?= date('d/m/Y H:i', strtotime($row['dataehora'])) ?></span></td>
                                <td>
                                    <?php if ($isMine): ?>
                                        <a href="apagarordemc.php?id=<?= $row['id'] ?>">
                                            <button class="btn-delete" onclick="return confirm('Tem certeza que deseja cancelar esta ordem de compra?');">
                                                <i class="fas fa-trash"></i> Apagar
                                            </button>
                                        </a>
                                    <?php else: ?>
                                        <span class="status-available">Disponível</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($totalPaginas > 1): ?>
                <div class="pagination">
                    
                    <?php if ($paginaAtual > 1): ?>
                        <a href="<?= linkPagina(1, $filtro_ordem) ?>" class="page-link">« Primeira</a>
                        <a href="<?= linkPagina($paginaAtual - 1, $filtro_ordem) ?>" class="page-link">‹ Anterior</a>
                    <?php else: ?>
                        <span class="page-link disabled">« Primeira</span>
                        <span class="page-link disabled">‹ Anterior</span>
                    <?php endif; ?>

                    <span class="page-link active">Página <?= $paginaAtual ?> de <?= $totalPaginas ?></span>

                    <?php if ($paginaAtual < $totalPaginas): ?>
                        <a href="<?= linkPagina($paginaAtual + 1, $filtro_ordem) ?>" class="page-link">Próxima ›</a>
                        <a href="<?= linkPagina($totalPaginas, $filtro_ordem) ?>" class="page-link">Última »</a>
                    <?php else: ?>
                        <span class="page-link disabled">Próxima ›</span>
                        <span class="page-link disabled">Última »</span>
                    <?php endif; ?>
                    
                </div>
            <?php endif; ?>

        <?php else: ?>
            <div style="text-align:center; padding:50px; color:#aaa; font-style:italic; background:rgba(0,0,0,0.6); border:1px dashed #555; border-radius:10px;">
                <i class="fas fa-shopping-basket fa-3x"></i><br><br>
                Nenhuma ordem de compra encontrada com estes filtros.
            </div>
        <?php endif; ?>

    </div>

</body>
</html>