<?php
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../includes/functions.php';

if ($_SESSION['user_role'] !== 'personnel') {
    header('Location: ../dashboard.php');
    exit;
}

$sous_dossier_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$show_deleted = filter_input(INPUT_GET, 'deleted', FILTER_VALIDATE_BOOLEAN) ? true : false;
if (!$sous_dossier_id) { header('Location: index.php'); exit; }

$pdo = getPDO();
$stmt = $pdo->prepare("SELECT sd.*, d.nom as dossier_nom, p.nom as projet_nom FROM sous_dossiers sd
                       JOIN dossiers d ON sd.dossier_id = d.id
                       JOIN projets p ON d.projet_id = p.id
                       WHERE sd.id = ?");
$stmt->execute([$sous_dossier_id]);
$sous_dossier = $stmt->fetch();
if (!$sous_dossier) { header('Location: index.php'); exit; }

$user_id = $_SESSION['user_id'];

// Filtres (simplifiés)
$filtre_zone = trim($_GET['zone'] ?? '');
$filtre_type = $_GET['type_reserve'] ?? '';
$filtre_statut = $_GET['statut'] ?? '';

$sql_where = "f.sous_dossier_id = :sd_id";
$params = [':sd_id' => $sous_dossier_id];
if (!$show_deleted) $sql_where .= " AND f.deleted_at IS NULL";
else $sql_where .= " AND f.deleted_at IS NOT NULL";
if ($filtre_zone !== '') { $sql_where .= " AND f.zone LIKE :zone"; $params[':zone'] = '%' . $filtre_zone . '%'; }
if ($filtre_type !== '') { $sql_where .= " AND f.type_reserve = :type_reserve"; $params[':type_reserve'] = $filtre_type; }
if ($filtre_statut !== '') { $sql_where .= " AND f.statut = :statut"; $params[':statut'] = $filtre_statut; }

$sql = "SELECT f.*, u.nom as createur_nom
        FROM fiches f
        LEFT JOIN users u ON f.createur_id = u.id
        WHERE $sql_where
        ORDER BY f.date_creation DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$fiches = $stmt->fetchAll();

require_once '../includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1><i class="fas fa-folder-open"></i> <?= htmlspecialchars($sous_dossier['nom']) ?></h1>
        <p class="text-muted">Dossier : <?= htmlspecialchars($sous_dossier['dossier_nom']) ?> | Projet : <?= htmlspecialchars($sous_dossier['projet_nom']) ?></p>
    </div>
    <div>
        <?php if ($show_deleted): ?>
            <a href="?id=<?= $sous_dossier_id ?>" class="btn btn-outline-primary me-2"><i class="fas fa-arrow-left"></i> Fiches actives</a>
        <?php else: ?>
            <a href="?id=<?= $sous_dossier_id ?>&deleted=1" class="btn btn-outline-secondary me-2"><i class="fas fa-trash-alt"></i> Corbeille</a>
        <?php endif; ?>
        <a href="fiche_edit.php?sous_dossier_id=<?= $sous_dossier_id ?>" class="btn btn-success"><i class="fas fa-plus-circle"></i> Nouvelle fiche</a>
    </div>
</div>

<div class="card mb-3">
    <div class="card-header bg-light"><i class="fas fa-filter"></i> Filtres</div>
    <div class="card-body">
        <form method="get" class="row g-2">
            <input type="hidden" name="id" value="<?= $sous_dossier_id ?>">
            <?php if ($show_deleted) echo '<input type="hidden" name="deleted" value="1">'; ?>
            <div class="col-md-3"><label>Zone</label><input type="text" name="zone" class="form-control" value="<?= htmlspecialchars($filtre_zone) ?>"></div>
            <div class="col-md-2"><label>Type</label><select name="type_reserve" class="form-select"><option value="">Tous</option><option value="sans_reserve" <?= $filtre_type==='sans_reserve'?'selected':'' ?>>Sans réserve</option><option value="avec_reserve" <?= $filtre_type==='avec_reserve'?'selected':'' ?>>Avec réserve</option></select></div>
            <div class="col-md-2"><label>Statut</label><select name="statut" class="form-select"><option value="">Tous</option><option value="brouillon" <?= $filtre_statut==='brouillon'?'selected':'' ?>>Brouillon</option><option value="soumis" <?= $filtre_statut==='soumis'?'selected':'' ?>>Soumis</option><option value="valide" <?= $filtre_statut==='valide'?'selected':'' ?>>Validé</option></select></div>
            <div class="col-md-2 align-self-end"><button type="submit" class="btn btn-primary">Filtrer</button></div>
        </form>
    </div>
</div>

<?php if (empty($fiches)): ?>
    <div class="alert alert-info"><?= $show_deleted ? 'Corbeille vide' : 'Aucune fiche' ?></div>
<?php else: ?>
    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead class="table-dark">
                <tr>
                    <th>N° Fiche</th>
                    <th>Titre</th>
                    <th>Zone</th>
                    <th>Type</th>
                    <th>Statut</th>
                    <th>Créateur</th>
                    <th>Date création</th>
                    <?php if ($show_deleted): ?><th>Supprimé par</th><th>Date suppression</th><?php endif; ?>
                    <th>PDF</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($fiches as $fiche): 
                    $peut_modifier = ($_SESSION['user_id'] == $fiche['createur_id']);
                ?>
                <tr class="<?= $fiche['type_reserve'] === 'avec_reserve' ? 'table-danger' : ($fiche['type_reserve'] === 'sans_reserve' ? 'table-success' : '') ?>">
                    <td><code><?= htmlspecialchars($fiche['numero_fiche']) ?></code></td>
                    <td><?= htmlspecialchars($fiche['titre']) ?></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'] ?? 'N/A') ?></td>
                    <td><?= date('d/m/Y', strtotime($fiche['date_creation'])) ?></td>
                    <?php if ($show_deleted): ?>
                        <td><?= htmlspecialchars($fiche['deleted_by_nom'] ?? '') ?></td>
                        <td><?= $fiche['deleted_at'] ? date('d/m/Y H:i', strtotime($fiche['deleted_at'])) : '' ?></td>
                    <?php endif; ?>
                    <td class="text-center">
                        <?php if ($fiche['pdf_path']): ?>
                            <a href="<?= htmlspecialchars($fiche['pdf_path']) ?>" target="_blank"><i class="fas fa-file-pdf text-danger"></i></a>
                        <?php else: ?>
                            <i class="fas fa-times text-muted"></i>
                        <?php endif; ?>
                    </td>
                    <td class="text-end">
                        <div class="btn-group btn-group-sm">
                            <a href="fiche_view.php?id=<?= $fiche['id'] ?>" class="btn btn-info"><i class="fas fa-eye"></i></a>
                            <?php if (!$show_deleted): ?>
                                <?php if ($peut_modifier): ?>
                                    <a href="fiche_edit.php?id=<?= $fiche['id'] ?>" class="btn btn-warning"><i class="fas fa-edit"></i></a>
                                    <a href="../fiche_delete.php?id=<?= $fiche['id'] ?>&action=soft" class="btn btn-danger" onclick="return confirm('Déplacer vers la corbeille ?')"><i class="fas fa-trash"></i></a>
                                <?php endif; ?>
                                <a href="generer_pdf.php?id=<?= $fiche['id'] ?>" class="btn btn-secondary" target="_blank"><i class="fas fa-file-pdf"></i></a>
                                <a href="upload_fichier.php?fiche_id=<?= $fiche['id'] ?>" class="btn btn-success"><i class="fas fa-paperclip"></i></a>
                            <?php else: ?>
                                <!-- Pas de restauration ni suppression définitive pour le personnel -->
                                <span class="text-muted">Supprimée</span>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

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