<?php
require_once 'includes/auth.php';
if (!in_array($_SESSION['user_role'], ['superadmin','admin'])) {
    header('Location: dashboard.php');
    exit;
}
require_once 'config/database.php';
require_once 'includes/functions.php';

$pdo = getPDO();

// Filtre par projet
$projet_id = filter_input(INPUT_GET, 'projet_id', FILTER_VALIDATE_INT);
$sql_where = "f.deleted_at IS NOT NULL";
$params = [];
if ($projet_id) {
    $sql_where .= " AND d.projet_id = ?";
    $params[] = $projet_id;
}

$sql = "SELECT f.*, sd.nom as sous_dossier_nom, d.nom as dossier_nom, p.nom as projet_nom,
               u.nom as createur_nom, ud.nom as deleted_by_nom, f.deleted_at
        FROM fiches f
        JOIN sous_dossiers sd ON f.sous_dossier_id = sd.id
        JOIN dossiers d ON sd.dossier_id = d.id
        JOIN projets p ON d.projet_id = p.id
        LEFT JOIN users u ON f.createur_id = u.id
        LEFT JOIN users ud ON f.deleted_by = ud.id
        WHERE $sql_where
        ORDER BY f.deleted_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$fiches = $stmt->fetchAll();

// Liste des projets pour le filtre
$projets = $pdo->query("SELECT id, nom FROM projets ORDER BY nom")->fetchAll();

require_once 'includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="fas fa-trash-alt me-2"></i>Corbeille (fiches supprimées)</h1>
    <a href="dashboard.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Retour</a>
</div>

<form method="get" class="row g-3 mb-4">
    <div class="col-auto">
        <label class="form-label">Filtrer par projet :</label>
    </div>
    <div class="col-auto">
        <select name="projet_id" class="form-select">
            <option value="">Tous les projets</option>
            <?php foreach ($projets as $proj): ?>
                <option value="<?= $proj['id'] ?>" <?= $projet_id == $proj['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($proj['nom']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="col-auto">
        <button type="submit" class="btn btn-primary">Filtrer</button>
        <?php if ($projet_id): ?>
            <a href="corbeille.php" class="btn btn-secondary">Réinitialiser</a>
        <?php endif; ?>
    </div>
</form>

<?php if (empty($fiches)): ?>
    <div class="alert alert-info">Aucune fiche dans la corbeille.</div>
<?php else: ?>
    <div class="table-responsive">
        <table class="table table-striped table-hover" id="tableCorbeille">
            <thead class="table-dark">
                <tr>
                    <th>N° Fiche</th>
                    <th>Titre</th>
                    <th>Projet</th>
                    <th>Dossier</th>
                    <th>Sous-dossier</th>
                    <th>Zone</th>
                    <th>Type</th>
                    <th>Statut</th>
                    <th>Créateur</th>
                    <th>Supprimé par</th>
                    <th>Date suppression</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($fiches as $fiche): ?>
                <tr>
                    <td><code><?= htmlspecialchars($fiche['numero_fiche']) ?></code></td>
                    <td><?= htmlspecialchars($fiche['titre']) ?></td>
                    <td><?= htmlspecialchars($fiche['projet_nom']) ?></td>
                    <td><?= htmlspecialchars($fiche['dossier_nom']) ?></td>
                    <td><?= htmlspecialchars($fiche['sous_dossier_nom']) ?></td>
                    <td><?= htmlspecialchars($fiche['zone'] ?? '') ?></td>
                    <td><span class="badge <?= $fiche['type_reserve']=='sans_reserve'?'bg-success':'bg-danger' ?>"><?= $fiche['type_reserve'] == 'sans_reserve' ? 'Sans réserve' : 'Avec réserve' ?></span></td>
                    <td><span class="badge <?= match($fiche['statut']){'brouillon'=>'bg-secondary','soumis'=>'bg-warning','valide'=>'bg-success'} ?>"><?= $fiche['statut'] ?></span></td>
                    <td><?= htmlspecialchars($fiche['createur_nom'] ?? '') ?></td>
                    <td><?= htmlspecialchars($fiche['deleted_by_nom'] ?? '') ?></td>
                    <td><?= date('d/m/Y H:i', strtotime($fiche['deleted_at'])) ?></td>
                    <td class="text-center">
                        <div class="btn-group btn-group-sm">
                            <a href="fiche_delete.php?id=<?= $fiche['id'] ?>&action=restore" class="btn btn-success" onclick="return confirm('Restaurer cette fiche ?')" title="Restaurer">
                                <i class="fas fa-undo"></i>
                            </a>
                            <a href="fiche_delete.php?id=<?= $fiche['id'] ?>&action=definitive" class="btn btn-danger" onclick="return confirm('Supprimer définitivement ? Cette action est irréversible.')" title="Supprimer définitivement">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<script>
$(document).ready(function() {
    $('#tableCorbeille').DataTable({
        language: { url: '//cdn.datatables.net/plug-ins/1.13.4/i18n/fr-FR.json' },
        order: [[10, 'desc']]
    });
});
</script>

<?php require_once 'includes/footer.php'; ?>