<?php 
ob_start();
$prioriteColors = [
    'basse' => 'bg-gray-100 text-gray-600',
    'normale' => 'bg-blue-100 text-blue-600',
    'haute' => 'bg-orange-100 text-orange-600',
    'urgente' => 'bg-red-100 text-red-600'
];
$statutColors = [
    'nouveau' => 'bg-yellow-100 text-yellow-700',
    'en_cours' => 'bg-blue-100 text-blue-700',
    'traite' => 'bg-green-100 text-green-700',
    'rejete' => 'bg-red-100 text-red-700',
    'cloture' => 'bg-gray-100 text-gray-700'
];
$actionLabels = [
    'creation' => '📝 Création du dossier',
    'changement_statut' => '🔄 Changement de statut',
    'assignation' => '👤 Assignation',
    'ajout_piece' => '📎 Pièce ajoutée',
    'note_interne' => '📋 Note interne',
    'changement_priorite' => '⚡ Priorité modifiée',
    'cloture' => '✅ Clôture du dossier'
];
?>

<div class="space-y-6">
    <!-- En-tête avec numéro dossier -->
    <div class="bg-white rounded-xl p-6 shadow-sm">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div class="flex items-center gap-4">
                <a href="<?= BASE_URL ?>/admin/denonciations" class="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center hover:bg-gray-200">
                    <i class="fas fa-arrow-left text-gray-600"></i>
                </a>
                <div>
                    <div class="flex items-center gap-3">
                        <h1 class="text-xl font-bold text-gray-900">
                            <?= htmlspecialchars($denonciation['numero_dossier'] ?? 'Dossier #' . $denonciation['id']) ?>
                        </h1>
                        <span class="px-3 py-1 rounded-full text-xs font-medium <?= $statutColors[$denonciation['statut']] ?? 'bg-gray-100' ?>">
                            <?= ucfirst(str_replace('_', ' ', $denonciation['statut'])) ?>
                        </span>
                        <span class="px-3 py-1 rounded-full text-xs font-medium <?= $prioriteColors[$denonciation['priorite'] ?? 'normale'] ?>">
                            <?= ucfirst($denonciation['priorite'] ?? 'Normale') ?>
                        </span>
                    </div>
                    <p class="text-sm text-gray-500 mt-1">
                        Créé le <?= date('d/m/Y à H:i', strtotime($denonciation['created_at'])) ?>
                        <?php if ($denonciation['agent_nom']): ?>
                            • Assigné à <strong><?= htmlspecialchars($denonciation['agent_nom']) ?></strong>
                        <?php endif; ?>
                    </p>
                </div>
            </div>
            <div class="flex gap-2">
                <button onclick="openModal('modal-statut')" class="px-4 py-2 bg-cyan-500 text-white rounded-lg hover:bg-cyan-600 text-sm">
                    <i class="fas fa-edit mr-1"></i> Statut
                </button>
                <button onclick="openModal('modal-priorite')" class="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 text-sm">
                    <i class="fas fa-flag mr-1"></i> Priorité
                </button>
                <button onclick="openModal('modal-assigner')" class="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 text-sm">
                    <i class="fas fa-user-plus mr-1"></i> Assigner
                </button>
            </div>
        </div>
    </div>

    <div class="grid lg:grid-cols-3 gap-6">
        <!-- Colonne principale -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Titre et description -->
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-2"><?= htmlspecialchars($denonciation['titre'] ?: 'Sans titre') ?></h3>
                <p class="text-gray-600 whitespace-pre-wrap"><?= htmlspecialchars($denonciation['description'] ?: 'Aucune description fournie.') ?></p>
            </div>

            <!-- Pièce jointe principale -->
            <?php if (!empty($denonciation['fichier_path'])): ?>
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">
                    <i class="fas fa-paperclip mr-2"></i>Pièce jointe principale
                </h3>
                <?php if ($denonciation['type'] === 'photo'): ?>
                    <img src="<?= BASE_URL ?>/<?= $denonciation['fichier_path'] ?>" class="max-w-full rounded-lg" alt="Photo">
                <?php elseif ($denonciation['type'] === 'audio'): ?>
                    <audio controls class="w-full">
                        <source src="<?= BASE_URL ?>/<?= $denonciation['fichier_path'] ?>" type="<?= $denonciation['fichier_type'] ?? 'audio/webm' ?>">
                    </audio>
                <?php elseif ($denonciation['type'] === 'video'): ?>
                    <video controls class="w-full rounded-lg max-h-96">
                        <source src="<?= BASE_URL ?>/<?= $denonciation['fichier_path'] ?>" type="<?= $denonciation['fichier_type'] ?? 'video/webm' ?>">
                    </video>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Pièces jointes supplémentaires -->
            <?php if (!empty($pieces) && count($pieces) > 0): ?>
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">
                    <i class="fas fa-folder-open mr-2"></i>Documents du dossier (<?= count($pieces) ?>)
                </h3>
                <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
                    <?php foreach ($pieces as $piece): ?>
                    <div class="border rounded-lg p-3 hover:bg-gray-50">
                        <div class="flex items-center gap-2 mb-2">
                            <?php
                            $iconPiece = 'file';
                            if ($piece['type'] === 'photo') $iconPiece = 'image';
                            elseif ($piece['type'] === 'audio') $iconPiece = 'microphone';
                            elseif ($piece['type'] === 'video') $iconPiece = 'video';
                            elseif ($piece['type'] === 'document') $iconPiece = 'file-alt';
                            ?>
                            <i class="fas fa-<?= $iconPiece ?> text-gray-400"></i>
                            <span class="text-sm font-medium truncate"><?= htmlspecialchars($piece['nom_fichier']) ?></span>
                        </div>
                        <p class="text-xs text-gray-500"><?= date('d/m/Y H:i', strtotime($piece['created_at'])) ?></p>
                        <a href="<?= BASE_URL ?>/<?= $piece['chemin_fichier'] ?>" target="_blank" class="text-xs text-cyan-600 hover:underline">
                            Voir
                        </a>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Ajouter une pièce -->
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">
                    <i class="fas fa-plus-circle mr-2"></i>Ajouter un document
                </h3>
                <form id="form-piece" enctype="multipart/form-data" class="flex flex-col md:flex-row gap-3">
                    <input type="file" name="fichier" id="fichier-piece" class="flex-1 px-3 py-2 border rounded-lg text-sm">
                    <input type="text" name="description" placeholder="Description (optionnel)" class="flex-1 px-3 py-2 border rounded-lg text-sm">
                    <button type="submit" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 text-sm">
                        <i class="fas fa-upload mr-1"></i> Ajouter
                    </button>
                </form>
            </div>

            <!-- Note interne -->
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">
                    <i class="fas fa-sticky-note mr-2"></i>Note interne
                </h3>
                <form id="form-note">
                    <textarea id="note-interne" rows="3" class="w-full px-3 py-2 border rounded-lg text-sm resize-none" 
                              placeholder="Notes visibles uniquement par l'équipe..."><?= htmlspecialchars($denonciation['note_interne'] ?? '') ?></textarea>
                    <button type="submit" class="mt-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 text-sm">
                        <i class="fas fa-save mr-1"></i> Enregistrer
                    </button>
                </form>
            </div>

            <!-- Résolution (si clôturé) -->
            <?php if (!empty($denonciation['resolution'])): ?>
            <div class="bg-green-50 rounded-xl p-6 border border-green-200">
                <h3 class="font-semibold text-green-800 mb-2">
                    <i class="fas fa-check-circle mr-2"></i>Résolution
                </h3>
                <p class="text-green-700"><?= nl2br(htmlspecialchars($denonciation['resolution'])) ?></p>
                <p class="text-sm text-green-600 mt-2">
                    Clôturé le <?= date('d/m/Y à H:i', strtotime($denonciation['date_cloture'])) ?>
                </p>
            </div>
            <?php endif; ?>

            <!-- Formulaire clôture -->
            <?php if (!in_array($denonciation['statut'], ['traite', 'cloture', 'rejete'])): ?>
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">
                    <i class="fas fa-flag-checkered mr-2"></i>Clôturer le dossier
                </h3>
                <form id="form-cloture">
                    <textarea id="resolution" rows="3" class="w-full px-3 py-2 border rounded-lg text-sm resize-none" 
                              placeholder="Décrivez la résolution ou le motif de clôture..."></textarea>
                    <div class="flex gap-2 mt-3">
                        <button type="button" onclick="cloturer('traite')" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 text-sm">
                            <i class="fas fa-check mr-1"></i> Marquer traité
                        </button>
                        <button type="button" onclick="cloturer('rejete')" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 text-sm">
                            <i class="fas fa-times mr-1"></i> Rejeter
                        </button>
                    </div>
                </form>
            </div>
            <?php endif; ?>
        </div>

        <!-- Sidebar droite -->
        <div class="space-y-6">
            <!-- Infos dossier -->
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">📋 Informations</h3>
                <div class="space-y-3 text-sm">
                    <div class="flex justify-between">
                        <span class="text-gray-500">N° Dossier</span>
                        <span class="font-mono font-medium"><?= $denonciation['numero_dossier'] ?? '-' ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Type</span>
                        <span class="font-medium capitalize"><?= $denonciation['type'] ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Catégorie</span>
                        <span class="font-medium"><?= $denonciation['categorie'] ?: '-' ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Anonyme</span>
                        <span class="font-medium"><?= $denonciation['anonyme'] ? '✓ Oui' : 'Non' ?></span>
                    </div>
                    <?php if (!empty($denonciation['localisation'])): ?>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Lieu</span>
                        <span class="font-medium"><?= htmlspecialchars($denonciation['localisation']) ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($denonciation['date_faits'])): ?>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Date des faits</span>
                        <span class="font-medium"><?= date('d/m/Y', strtotime($denonciation['date_faits'])) ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Auteur -->
            <?php if (!$denonciation['anonyme'] && !empty($denonciation['client_nom'])): ?>
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">👤 Auteur</h3>
                <div class="flex items-center gap-3">
                    <div class="w-12 h-12 bg-gradient-to-br from-cyan-500 to-emerald-500 rounded-full flex items-center justify-center text-white font-bold">
                        <?= strtoupper(substr($denonciation['client_nom'] ?? 'U', 0, 1)) ?>
                    </div>
                    <div>
                        <p class="font-medium"><?= htmlspecialchars($denonciation['client_nom']) ?></p>
                        <?php if (!empty($denonciation['client_tel'])): ?>
                        <p class="text-sm text-gray-500"><?= htmlspecialchars($denonciation['client_tel']) ?></p>
                        <?php endif; ?>
                        <?php if (!empty($denonciation['client_email'])): ?>
                        <p class="text-sm text-gray-500"><?= htmlspecialchars($denonciation['client_email']) ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Historique -->
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">📜 Historique</h3>
                <div class="space-y-4 max-h-96 overflow-y-auto">
                    <?php if (!empty($historique)): ?>
                        <?php foreach ($historique as $h): ?>
                        <div class="border-l-2 border-cyan-300 pl-3 py-1">
                            <p class="text-sm font-medium text-gray-800">
                                <?= $actionLabels[$h['action']] ?? $h['action'] ?>
                            </p>
                            <?php if (!empty($h['commentaire'])): ?>
                            <p class="text-xs text-gray-600 mt-1"><?= htmlspecialchars($h['commentaire']) ?></p>
                            <?php endif; ?>
                            <?php if (!empty($h['ancien_statut']) || !empty($h['nouveau_statut'])): ?>
                            <p class="text-xs text-gray-500 mt-1">
                                <?= $h['ancien_statut'] ?> → <strong><?= $h['nouveau_statut'] ?></strong>
                            </p>
                            <?php endif; ?>
                            <p class="text-xs text-gray-400 mt-1">
                                <?= date('d/m/Y H:i', strtotime($h['created_at'])) ?>
                                <?php if (!empty($h['user_nom'])): ?>
                                    • <?= htmlspecialchars($h['user_nom']) ?>
                                <?php endif; ?>
                            </p>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="text-sm text-gray-500">Aucun historique</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Statut -->
<div id="modal-statut" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-xl p-6 w-full max-w-md">
        <h3 class="font-bold text-lg mb-4">Changer le statut</h3>
        <select id="select-statut" class="w-full px-4 py-3 border rounded-lg mb-3">
            <option value="nouveau" <?= $denonciation['statut'] === 'nouveau' ? 'selected' : '' ?>>Nouveau</option>
            <option value="en_cours" <?= $denonciation['statut'] === 'en_cours' ? 'selected' : '' ?>>En cours de traitement</option>
            <option value="traite" <?= $denonciation['statut'] === 'traite' ? 'selected' : '' ?>>Traité</option>
            <option value="rejete" <?= $denonciation['statut'] === 'rejete' ? 'selected' : '' ?>>Rejeté</option>
        </select>
        <textarea id="commentaire-statut" rows="2" class="w-full px-3 py-2 border rounded-lg text-sm mb-4" placeholder="Commentaire (optionnel)"></textarea>
        <div class="flex gap-2">
            <button onclick="closeModal('modal-statut')" class="flex-1 px-4 py-2 bg-gray-200 rounded-lg">Annuler</button>
            <button onclick="saveStatut()" class="flex-1 px-4 py-2 bg-cyan-500 text-white rounded-lg">Enregistrer</button>
        </div>
    </div>
</div>

<!-- Modal Priorité -->
<div id="modal-priorite" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-xl p-6 w-full max-w-md">
        <h3 class="font-bold text-lg mb-4">Changer la priorité</h3>
        <div class="grid grid-cols-2 gap-3 mb-4">
            <button onclick="savePriorite('basse')" class="px-4 py-3 bg-gray-100 rounded-lg hover:bg-gray-200">🟢 Basse</button>
            <button onclick="savePriorite('normale')" class="px-4 py-3 bg-blue-100 rounded-lg hover:bg-blue-200">🔵 Normale</button>
            <button onclick="savePriorite('haute')" class="px-4 py-3 bg-orange-100 rounded-lg hover:bg-orange-200">🟠 Haute</button>
            <button onclick="savePriorite('urgente')" class="px-4 py-3 bg-red-100 rounded-lg hover:bg-red-200">🔴 Urgente</button>
        </div>
        <button onclick="closeModal('modal-priorite')" class="w-full px-4 py-2 bg-gray-200 rounded-lg">Annuler</button>
    </div>
</div>

<!-- Modal Assigner -->
<div id="modal-assigner" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-xl p-6 w-full max-w-md">
        <h3 class="font-bold text-lg mb-4">Assigner un agent</h3>
        <select id="select-agent" class="w-full px-4 py-3 border rounded-lg mb-4">
            <option value="">-- Sélectionner un agent --</option>
            <?php if (!empty($agents)): ?>
                <?php foreach ($agents as $agent): ?>
                <option value="<?= $agent['id'] ?>" <?= ($denonciation['agent_id'] ?? 0) == $agent['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($agent['nom'] . ' ' . ($agent['prenom'] ?? '')) ?>
                </option>
                <?php endforeach; ?>
            <?php endif; ?>
        </select>
        <div class="flex gap-2">
            <button onclick="closeModal('modal-assigner')" class="flex-1 px-4 py-2 bg-gray-200 rounded-lg">Annuler</button>
            <button onclick="saveAssignation()" class="flex-1 px-4 py-2 bg-purple-500 text-white rounded-lg">Assigner</button>
        </div>
    </div>
</div>

<script>
var denonciationId = <?= $denonciation['id'] ?>;

function openModal(id) {
    document.getElementById(id).classList.remove('hidden');
}

function closeModal(id) {
    document.getElementById(id).classList.add('hidden');
}

function showToast(message, type) {
    var toast = document.createElement('div');
    toast.textContent = message;
    var bg = type === 'error' ? '#ef4444' : '#10b981';
    toast.style.cssText = 'position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:' + bg + ';color:white;padding:12px 24px;border-radius:8px;z-index:9999';
    document.body.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 2000);
}

function saveStatut() {
    var statut = document.getElementById('select-statut').value;
    var commentaire = document.getElementById('commentaire-statut').value;
    
    fetch('<?= BASE_URL ?>/admin/denonciations/' + denonciationId + '/statut', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ statut: statut, commentaire: commentaire })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) {
            showToast('Statut mis à jour');
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showToast('Erreur', 'error');
        }
    });
    closeModal('modal-statut');
}

function savePriorite(priorite) {
    fetch('<?= BASE_URL ?>/admin/denonciations/' + denonciationId + '/priorite', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ priorite: priorite })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) {
            showToast('Priorité mise à jour');
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showToast('Erreur', 'error');
        }
    });
    closeModal('modal-priorite');
}

function saveAssignation() {
    var agentId = document.getElementById('select-agent').value;
    if (!agentId) { showToast('Sélectionnez un agent', 'error'); return; }
    
    fetch('<?= BASE_URL ?>/admin/denonciations/' + denonciationId + '/assigner', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ agent_id: agentId })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) {
            showToast('Agent assigné');
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showToast('Erreur', 'error');
        }
    });
    closeModal('modal-assigner');
}

function cloturer(statut) {
    var resolution = document.getElementById('resolution').value;
    if (!resolution) { showToast('Entrez une résolution', 'error'); return; }
    
    fetch('<?= BASE_URL ?>/admin/denonciations/' + denonciationId + '/cloturer', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ statut: statut, resolution: resolution })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) {
            showToast('Dossier clôturé');
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showToast('Erreur', 'error');
        }
    });
}

document.getElementById('form-note').addEventListener('submit', function(e) {
    e.preventDefault();
    var note = document.getElementById('note-interne').value;
    
    fetch('<?= BASE_URL ?>/admin/denonciations/' + denonciationId + '/note', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ note: note })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) showToast('Note enregistrée');
        else showToast('Erreur', 'error');
    });
});

document.getElementById('form-piece').addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    
    fetch('<?= BASE_URL ?>/admin/denonciations/' + denonciationId + '/piece', {
        method: 'POST',
        body: formData
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) {
            showToast('Document ajouté');
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showToast('Erreur: ' + (data.error || ''), 'error');
        }
    });
});
</script>

<?php 
$content = ob_get_clean();
$title = ($denonciation['numero_dossier'] ?? 'Dossier #' . $denonciation['id']) . ' - ' . APP_NAME;
$pageTitle = 'Dossier de signalement';
include VIEWS_PATH . '/layouts/main.php';
?>
