<?php
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/auth.php';
require_role(['admin', 'handlowiec', 'supplier']);

$clients = [];
$error_message = '';
$pdo = null;

try {
    $pdo = db();
    $role = get_user_role();

    if ($role === 'supplier') {
        $supplier_id = $_SESSION['user_id'];
        $stmt_clients = $pdo->prepare('
            SELECT DISTINCT c.*
            FROM clients c
            JOIN orders o ON c.id = o.client_id
            JOIN order_items oi ON o.id = oi.order_id
            JOIN products p ON oi.product_id = p.id
            WHERE p.supplier_id = :supplier_id
            ORDER BY c.name ASC
        ');
        $stmt_clients->execute(['supplier_id' => $supplier_id]);
    } else {
        $stmt_clients = $pdo->query('SELECT * FROM clients ORDER BY name ASC');
    }
    $clients = $stmt_clients->fetchAll();
} catch (PDOException $e) {
    error_log('DB Error in admin/clients.php: ' . $e->getMessage());
    $error_message = 'Błąd podczas pobierania klientów.';
}

$page_title = 'Klienci';
?>
<?php require_once __DIR__ . '/../includes/html_head.php'; ?>
<body>
<?php require_once __DIR__ . '/menu.php'; ?>

<main class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h2"><?php echo $page_title; ?></h1>
        <?php if (get_user_role() !== 'supplier'): ?>
        <a href="edit_client.php" class="btn btn-primary">
            <i class="bi bi-plus-lg"></i> Dodaj klienta
        </a>
        <?php endif; ?>
    </div>

    <div class="card">
        <div class="card-body">
            <?php if ($error_message): ?>
                <div class="alert alert-danger" role="alert">
                    <?php echo htmlspecialchars($error_message); ?>
                </div>
            <?php elseif ($pdo): ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Nazwa</th>
                                <th>NIP</th>
                                <th>Miasto</th>
                                <th>Przypisani użytkownicy</th>
                                <th>Akcje</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($clients)): ?>
                                <tr>
                                    <td colspan="6" class="text-center">Nie znaleziono klientów.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($clients as $client): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($client['id']); ?></td>
                                        <td><?php echo htmlspecialchars($client['name']); ?></td>
                                        <td><?php echo htmlspecialchars($client['nip']); ?></td>
                                        <td><?php echo htmlspecialchars($client['city']); ?></td>
                                        <td>
                                            <?php
                                            $assignedUsersLabel = '—';
                                            try {
                                                $stmtUsers = $pdo->prepare("SELECT email FROM users WHERE client_id = :client_id");
                                                $stmtUsers->execute(['client_id' => $client['id']]);
                                                $assignedUsers = $stmtUsers->fetchAll(PDO::FETCH_COLUMN);
                                                if ($assignedUsers) {
                                                    $assignedUsersLabel = implode(', ', array_map('htmlspecialchars', $assignedUsers));
                                                }
                                            } catch (PDOException $e) {
                                                error_log('DB Error in admin/clients.php for client ID ' . $client['id'] . ': ' . $e->getMessage());
                                                $assignedUsersLabel = '<span class="text-danger font-italic">Błąd ładowania</span>';
                                            }
                                            echo $assignedUsersLabel;
                                            ?>
                                        </td>
                                        <td>
                                            <a href="edit_client.php?id=<?php echo $client['id']; ?>" class="btn btn-sm btn-secondary">
                                                <i class="bi bi-pencil-fill"></i> Edytuj
                                            </a>
                                            <?php if (get_user_role() !== 'supplier'): ?>
                                            <a href="client_prices.php?client_id=<?php echo $client['id']; ?>" class="btn btn-sm btn-info">
                                                <i class="bi bi-tag-fill"></i> Cennik
                                            </a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>
