<?php
require_once '../config/database.php';
require_once '../config/auth.php';
requireLogin('admin', 'index.php');

$db = Database::getInstance()->getConnection();

// Filtros
$status = $_GET['status'] ?? '';
$where = '';
$params = [];

if ($status && in_array($status, ['pendente', 'aceita', 'coletada', 'entregue', 'cancelada'])) {
    $where = "WHERE e.status = ?";
    $params[] = $status;
}

// Buscar entregas
$sql = "
    SELECT e.*, u.nome as cliente, u.telefone as cliente_tel, 
           ent.nome as entregador, ent.telefone as entregador_tel
    FROM entregas e
    LEFT JOIN usuarios u ON e.usuario_id = u.id
    LEFT JOIN entregadores ent ON e.entregador_id = ent.id
    $where
    ORDER BY e.created_at DESC
";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$entregas = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Ação de cancelar
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancelar'])) {
    $id = intval($_POST['cancelar']);
    $stmt = $db->prepare("UPDATE entregas SET status = 'cancelada' WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: entregas.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Entregas - Admin</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/admin.css">
    <script src="../assets/js/admin-theme.js"></script>
</head>
<body class="admin-panel">
    <header class="header">
        <h1>⚙️ Já EntreGo Admin</h1>
        <nav>
            <a href="dashboard.php">Dashboard</a>
            <a href="entregas.php">Entregas</a>
            <a href="entregadores.php">Entregadores</a>
            <a href="usuarios.php">Usuários</a>
            <a href="parceiros.php">Parceiros</a>
            <a href="configuracoes.php">Configurações</a>
            <a href="perfil.php">Perfil</a>
            <a href="logout.php">Sair</a>
            <div class="theme-toggle">
                <button type="button" id="theme-toggle-btn" class="theme-toggle-btn" onclick="toggleTheme()" title="Alternar tema">🌙</button>
            </div>
        </nav>
    </header>
    
    <div class="container">
        <h2 style="margin-bottom: 20px;">Gerenciar Entregas</h2>
        
        <!-- Filtros -->
        <div class="card">
            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                <a href="entregas.php" class="btn <?= !$status ? 'btn-primary' : '' ?>" style="<?= !$status ? '' : 'background: #e0e0e0; color: #333;' ?>">Todas</a>
                <a href="entregas.php?status=pendente" class="btn <?= $status === 'pendente' ? 'btn-warning' : '' ?>" style="<?= $status === 'pendente' ? '' : 'background: #e0e0e0; color: #333;' ?>">Pendentes</a>
                <a href="entregas.php?status=aceita" class="btn <?= $status === 'aceita' ? 'btn-primary' : '' ?>" style="<?= $status === 'aceita' ? '' : 'background: #e0e0e0; color: #333;' ?>">Aceitas</a>
                <a href="entregas.php?status=coletada" class="btn" style="background: <?= $status === 'coletada' ? '#9c27b0' : '#e0e0e0' ?>; color: <?= $status === 'coletada' ? 'white' : '#333' ?>;">Coletadas</a>
                <a href="entregas.php?status=entregue" class="btn <?= $status === 'entregue' ? 'btn-success' : '' ?>" style="<?= $status === 'entregue' ? '' : 'background: #e0e0e0; color: #333;' ?>">Entregues</a>
                <a href="entregas.php?status=cancelada" class="btn <?= $status === 'cancelada' ? 'btn-danger' : '' ?>" style="<?= $status === 'cancelada' ? '' : 'background: #e0e0e0; color: #333;' ?>">Canceladas</a>
            </div>
        </div>
        
        <!-- Lista -->
        <div class="card">
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Cliente</th>
                        <th>Entregador</th>
                        <th>Origem → Destino</th>
                        <th>Valor</th>
                        <th>Status</th>
                        <th>Data</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($entregas as $e): ?>
                    <tr>
                        <td>#<?= $e['id'] ?></td>
                        <td>
                            <?= htmlspecialchars($e['cliente']) ?>
                            <?php if ($e['cliente_tel']): ?>
                                <br><small><?= htmlspecialchars($e['cliente_tel']) ?></small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?= $e['entregador'] ? htmlspecialchars($e['entregador']) : '<em>-</em>' ?>
                            <?php if ($e['entregador_tel']): ?>
                                <br><small><?= htmlspecialchars($e['entregador_tel']) ?></small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <small>
                                📍 <?= htmlspecialchars(substr($e['origem_endereco'], 0, 40)) ?><br>
                                🎯 <?= htmlspecialchars(substr($e['destino_endereco'], 0, 40)) ?>
                            </small>
                        </td>
                        <td><strong>R$ <?= number_format($e['valor'], 2, ',', '.') ?></strong></td>
                        <td><span class="badge badge-<?= $e['status'] ?>"><?= ucfirst($e['status']) ?></span></td>
                        <td><?= date('d/m/Y H:i', strtotime($e['created_at'])) ?></td>
                        <td>
                            <?php if (!in_array($e['status'], ['entregue', 'cancelada'])): ?>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('Cancelar esta entrega?')">
                                    <button type="submit" name="cancelar" value="<?= $e['id'] ?>" class="btn btn-danger" style="padding: 6px 12px; font-size: 12px;">Cancelar</button>
                                </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <?php if (empty($entregas)): ?>
                <p style="text-align: center; padding: 40px; color: #666;">Nenhuma entrega encontrada</p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
