<?php use App\Core\Auth; ?>
<!-- Hero Section -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0"><i class="fas fa-building me-2"></i>Clients</h1>
            </div>
            <div class="col-sm-6">
                <?php $cu = Auth::user(); $role = $cu['role'] ?? ($cu['role_key'] ?? ''); ?>
                <?php if (in_array($role, ['admin','agent'])): ?>
                <button type="button" class="btn btn-primary float-end" data-bs-toggle="modal" data-bs-target="#clientCreateModal">
                    <i class="fas fa-plus me-1"></i>Nouveau Client
                </button>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        
                <?php if (isset($_GET['success']) || isset($_GET['error'])): ?>
                    <!-- Toasts Bootstrap pour feedback pro -->
                    <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index:1080;">
                        <?php if (isset($_GET['success'])): ?>
                            <div id="toastSuccess" class="toast align-items-center text-bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
                                <div class="d-flex">
                                    <div class="toast-body">
                                        <i class="fas fa-check-circle me-2"></i>
                                        <?php if ($_GET['success'] === 'created'): ?>Client créé avec succès !<?php endif; ?>
                                        <?php if ($_GET['success'] === 'updated'): ?>Client mis à jour avec succès !<?php endif; ?>
                                        <?php if ($_GET['success'] === 'deleted'): ?>Client supprimé avec succès !<?php endif; ?>
                                        <?php if ($_GET['success'] === 'toggled'): ?>Statut du client modifié avec succès !<?php endif; ?>
                                    </div>
                                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                                </div>
                            </div>
                        <?php endif; ?>
                        <?php if (isset($_GET['error'])): ?>
                            <div id="toastError" class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive" aria-atomic="true">
                                <div class="d-flex">
                                    <div class="toast-body">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        <?php if ($_GET['error'] === 'has_incidents'): ?>Impossible de supprimer ce client : <?= $_GET['count'] ?? 0 ?> incident(s) associé(s).<?php endif; ?>
                                        <?php if ($_GET['error'] === 'database'): ?>Une erreur est survenue. Veuillez réessayer.<?php endif; ?>
                                    </div>
                                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                    <script>
                    (function(){
                        try {
                            var s = document.getElementById('toastSuccess');
                            var e = document.getElementById('toastError');
                            if (s) { bootstrap.Toast.getOrCreateInstance(s, { delay: 3500 }).show(); }
                            if (e) { bootstrap.Toast.getOrCreateInstance(e, { delay: 5000 }).show(); }
                        } catch(_){ /* Fallback si Bootstrap JS indisponible: afficher des alerts */ }
                    })();
                    </script>
                <?php endif; ?>
        
        <!-- Filtres -->
        <div class="card">
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-5">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" name="search" placeholder="Rechercher un client..." value="<?= htmlspecialchars($search) ?>">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" name="status">
                            <option value="">Tous les statuts</option>
                            <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Actifs</option>
                            <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>Inactifs</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-filter me-1"></i>Filtrer
                        </button>
                        <a href="/clients" class="btn btn-secondary">
                            <i class="fas fa-undo me-1"></i>Réinitialiser
                        </a>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Tableau des clients -->
        <div class="card mt-4">
            <div class="card-header">
                <h3 class="card-title">Liste des clients (<?= count($clients) ?>)</h3>
            </div>
            <div class="card-body p-0">
                <?php if (empty($clients)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-building fa-3x text-muted mb-3"></i>
                        <p class="text-muted">Aucun client trouvé.</p>
                        <a href="/clients/create" class="btn btn-primary">
                            <i class="fas fa-plus me-1"></i>Créer le premier client
                        </a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Client</th>
                                    <th>Contact</th>
                                    <th>Localisation</th>
                                    <th class="text-center">Sites</th>
                                    <th class="text-center">Incidents</th>
                                    <th class="text-center">Statut</th>
                                    <th class="text-end">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($clients as $client): ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="avatar-circle bg-primary text-white me-2">
                                                    <?= strtoupper(substr($client['name'], 0, 1)) ?>
                                                </div>
                                                <div>
                                                        <a href="<?= htmlspecialchars(base_url('/clients/show')) ?>?id=<?= $client['id'] ?>" class="fw-bold text-decoration-none">
                                                        <?= htmlspecialchars($client['name']) ?>
                                                    </a>
                                                    <?php if ($client['contact_person']): ?>
                                                        <br><small class="text-muted">Contact: <?= htmlspecialchars($client['contact_person']) ?></small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if ($client['email']): ?>
                                                <div><i class="fas fa-envelope text-muted me-1"></i><?= htmlspecialchars($client['email']) ?></div>
                                            <?php endif; ?>
                                            <?php if ($client['phone']): ?>
                                                <div><i class="fas fa-phone text-muted me-1"></i><?= htmlspecialchars($client['phone']) ?></div>
                                            <?php endif; ?>
                                            <?php if ($client['contact_phone'] && $client['contact_phone'] !== $client['phone']): ?>
                                                <div><i class="fas fa-mobile text-muted me-1"></i><?= htmlspecialchars($client['contact_phone']) ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($client['city']): ?>
                                                <div><i class="fas fa-map-marker-alt text-muted me-1"></i><?= htmlspecialchars($client['city']) ?></div>
                                            <?php endif; ?>
                                            <?php if ($client['country'] && $client['country'] !== 'Côte d\'Ivoire'): ?>
                                                <small class="text-muted"><?= htmlspecialchars($client['country']) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-info"><?= $client['locations_count'] ?></span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-<?= $client['incidents_count'] > 0 ? 'warning' : 'secondary' ?>">
                                                <?= $client['incidents_count'] ?>
                                            </span>
                                        </td>
                                        <td class="text-center">
                                            <?php if ($client['active']): ?>
                                                <span class="badge bg-success"><i class="fas fa-check me-1"></i>Actif</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary"><i class="fas fa-times me-1"></i>Inactif</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="btn-group">
                                                <a href="/clients/show?id=<?= $client['id'] ?>" class="btn btn-sm btn-info" title="Voir">
                                                                                                    <a href="<?= htmlspecialchars(base_url('/clients/show')) ?>?id=<?= $client['id'] ?>" class="btn btn-sm btn-info" title="Voir">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <a href="/clients/edit?id=<?= $client['id'] ?>" class="btn btn-sm btn-warning" title="Modifier">
                                                                                                    <a href="<?= htmlspecialchars(base_url('/clients/edit')) ?>?id=<?= $client['id'] ?>" class="btn btn-sm btn-warning" title="Modifier">
                                                                            <a href="<?= htmlspecialchars(base_url('/clients')) ?>" class="btn btn-secondary">
                                                                            <a href="<?= htmlspecialchars(base_url('/clients/create')) ?>" class="btn btn-primary">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <?php 
                                                $currentUser = Auth::user();
                                                if (($currentUser['role'] ?? '') === 'admin'): 
                                                ?>
                                                    <button type="button" class="btn btn-sm btn-danger" onclick="confirmDelete(<?= $client['id'] ?>, '<?= htmlspecialchars($client['name']) ?>')" title="Supprimer">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
    </div>
</section>

<!-- Modal Création Client (Bootstrap 5) -->
<?php $cu = $cu ?? (Auth::user()); $role = $role ?? ($cu['role'] ?? ($cu['role_key'] ?? '')); ?>
<?php if (in_array($role, ['admin','agent'])): ?>
<div class="modal fade" id="clientCreateModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content shadow-lg">
            <div class="modal-header border-0" style="background: linear-gradient(135deg, #0d6efd 0%, #6610f2 100%); color: #fff;">
                <h5 class="modal-title"><i class="fas fa-building me-2"></i>Nouveau client</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" action="<?= htmlspecialchars(base_url('/clients/create')) ?>" id="createClientForm" novalidate>
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Nom du client<span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control" placeholder="Ex: NOVALINK" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control" placeholder="contact@client.com">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Téléphone</label>
                            <input type="text" name="phone" class="form-control" placeholder="01 23 45 67 89">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Personne de contact</label>
                            <input type="text" name="contact_person" class="form-control" placeholder="Nom et prénom">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Téléphone contact</label>
                            <input type="text" name="contact_phone" class="form-control" placeholder="07 00 00 00 00">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Adresse</label>
                            <input type="text" name="address" class="form-control" placeholder="Adresse complète">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Ville</label>
                            <input type="text" name="city" class="form-control" placeholder="Abidjan">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Pays</label>
                            <input type="text" name="country" class="form-control" value="Côte d'Ivoire">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Notes</label>
                            <textarea name="notes" class="form-control" rows="3" placeholder="Informations complémentaires"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light border-0">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Enregistrer</button>
                </div>
            </form>
        </div>
    </div>
    </div>
<?php endif; ?>

<style>
/* Flou de l'arrière-plan sur ouverture de la modale */
.modal-backdrop.show { backdrop-filter: blur(6px); background-color: rgba(33,37,41,0.35); }
.modal-content { border: 0; border-radius: .75rem; }
.modal .form-label { font-weight: 600; }
</style>

<script>
(function(){
    // Validation côté client simple
    const form = document.getElementById('createClientForm');
    if (form) {
        form.addEventListener('submit', function(e){
            if (!form.checkValidity()) {
                e.preventDefault(); e.stopPropagation();
                form.classList.add('was-validated');
            }
        });
    }
    // Reset du formulaire à la fermeture
    const modalEl = document.getElementById('clientCreateModal');
    if (modalEl) {
        modalEl.addEventListener('hidden.bs.modal', function(){
            form?.reset();
            form?.classList.remove('was-validated');
        });
    }
})();
</script>

<?php $cuFab = Auth::user(); $roleFab = $cuFab['role'] ?? ($cuFab['role_key'] ?? ''); ?>
<?php if (in_array($roleFab, ['admin','agent'])): ?>
<button type="button" class="btn btn-primary shadow fab-create" title="Nouveau client" data-bs-toggle="modal" data-bs-target="#clientCreateModal" aria-label="Nouveau client">
    <i class="fas fa-plus"></i>
    <span class="visually-hidden">Nouveau client</span>
    </button>
<style>
.fab-create{ position:fixed; right:24px; bottom:24px; width:56px; height:56px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:1.1rem; z-index:1056; }
.fab-create i{ pointer-events:none }
@media (max-width: 576px){ .fab-create{ right:16px; bottom:16px } }
</style>
<?php endif; ?>

<!-- Modal de suppression -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>Confirmer la suppression</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Êtes-vous sûr de vouloir supprimer le client <strong id="clientName"></strong> ?</p>
                <p class="text-danger"><i class="fas fa-info-circle me-1"></i>Cette action est irréversible.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                <form method="post" action="<?= htmlspecialchars(base_url('/clients/delete')) ?>" id="deleteForm">
                    <input type="hidden" name="id" id="deleteId">
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash me-1"></i>Supprimer
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
.avatar-circle {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.2rem;
}
</style>

<script>
function confirmDelete(id, name) {
    document.getElementById('clientName').textContent = name;
    document.getElementById('deleteId').value = id;
    
    try {
        const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
        modal.show();
    } catch (e) {
        if (confirm(`Êtes-vous sûr de vouloir supprimer le client "${name}" ?`)) {
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteForm').submit();
        }
    }
}
</script>
