<?php
session_start();
require_once __DIR__ . '/../includes/auth.php';
require_role('admin');
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../includes/helpers.php';

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

try {
    $pdo = db();
    $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.';
}

$pageTitle = 'Klienci';
?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Panel Administracyjny</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<?php require_once __DIR__ . '/menu.php'; ?>

<main class="container mt-4">
    <div class="card">
        <div class="card-header">
            <div class="d-flex justify-content-between align-items-center">
                <h1><?php echo $pageTitle; ?></h1>
                <a href="edit_client.php" class="btn btn-success">+ Dodaj klienta</a>
            </div>
        </div>
        <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>
                            <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-primary">Edytuj</a>
                                            <a href="client_prices.php?client_id=<?php echo $client['id']; ?>" class="btn btn-sm btn-info">Cennik</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
