<?php
$pageTitle = 'Documents & Archivage';
require_once __DIR__ . '/includes/header.php';
$db = getDB();

$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
    $doc = $db->prepare("SELECT * FROM documents WHERE id=?");
    $doc->execute([$id]);
    $doc = $doc->fetch();
    if ($doc && file_exists(DOCUMENTS_DIR . $doc['fichier'])) {
        unlink(DOCUMENTS_DIR . $doc['fichier']);
    }
    $db->prepare("DELETE FROM documents WHERE id=?")->execute([$id]);
    flash('success', 'Document supprimé.');
    redirect('/documents.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $voyageurId = intval($_POST['voyageur_id'] ?? 0) ?: null;
    $programmeId = intval($_POST['programme_id'] ?? 0) ?: null;
    $type = $_POST['type'] ?? 'autre';
    $nom = sanitize($_POST['nom'] ?? '');
    $notes = sanitize($_POST['notes'] ?? '');

    if (!empty($_FILES['fichier']['name'])) {
        $fichier = uploadFile($_FILES['fichier'], DOCUMENTS_DIR, ['jpg','jpeg','png','pdf','doc','docx','xls','xlsx']);
        if ($fichier) {
            $db->prepare("INSERT INTO documents (voyageur_id, programme_id, type, nom, fichier, notes) VALUES (?,?,?,?,?,?)")
                ->execute([$voyageurId, $programmeId, $type, $nom, $fichier, $notes]);
            logAction($_SESSION['user_id'], 'document_upload', "Document uploadé: $nom");
            flash('success', 'Document ajouté avec succès.');
        } else {
            flash('error', 'Erreur lors de l\'upload du fichier.');
        }
    } else {
        flash('error', 'Veuillez sélectionner un fichier.');
    }
    redirect('/documents.php');
}

// Upload form
if ($action === 'add') {
    $voyageurs = $db->query("SELECT id, nom, prenom, reference FROM voyageurs WHERE status='actif' ORDER BY nom")->fetchAll();
    $programmes = $db->query("SELECT id, nom, type FROM programmes ORDER BY date_depart DESC")->fetchAll();
    $types = ['passeport'=>'Passeport','visa'=>'Visa','billet'=>'Billet d\'avion','contrat'=>'Contrat','medical'=>'Dossier médical','autorisation'=>'Autorisation','facture'=>'Facture','autre'=>'Autre'];
?>
    <div class="d-flex justify-content-between mb-4">
        <a href="<?= APP_URL ?>/documents.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour</a>
    </div>
    <div class="card table-card">
        <div class="card-header"><i class="bi bi-cloud-upload me-2"></i>Ajouter un document</div>
        <div class="card-body p-4">
            <form method="POST" enctype="multipart/form-data">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Nom du document *</label>
                        <input type="text" name="nom" class="form-control" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Type *</label>
                        <select name="type" class="form-select">
                            <?php foreach ($types as $k=>$v): ?>
                                <option value="<?= $k ?>"><?= $v ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Fichier *</label>
                        <input type="file" name="fichier" class="form-control" required accept=".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Voyageur</label>
                        <select name="voyageur_id" class="form-select select2">
                            <option value="">-- Aucun --</option>
                            <?php foreach ($voyageurs as $v): ?>
                                <option value="<?= $v['id'] ?>"><?= sanitize($v['prenom'].' '.$v['nom'].' ('.$v['reference'].')') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Programme</label>
                        <select name="programme_id" class="form-select select2">
                            <option value="">-- Aucun --</option>
                            <?php foreach ($programmes as $p): ?>
                                <option value="<?= $p['id'] ?>"><?= sanitize($p['nom'].' ['.ucfirst($p['type']).']') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Notes</label>
                        <input type="text" name="notes" class="form-control">
                    </div>
                </div>
                <div class="d-flex gap-2 mt-4">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-upload me-1"></i>Ajouter</button>
                    <a href="<?= APP_URL ?>/documents.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php require_once __DIR__ . '/includes/footer.php'; exit; }

// List
$search = $_GET['search'] ?? '';
$typeFilter = $_GET['type'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));

$where = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (d.nom LIKE ? OR v.nom LIKE ? OR v.prenom LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s]; }
if ($typeFilter) { $where .= " AND d.type=?"; $params[] = $typeFilter; }

$total = $db->prepare("SELECT COUNT(*) FROM documents d LEFT JOIN voyageurs v ON d.voyageur_id=v.id $where");
$total->execute($params);
$pagination = paginate($total->fetchColumn(), 20, $page);

$stmt = $db->prepare("SELECT d.*, v.nom as v_nom, v.prenom as v_prenom, p.nom as programme_nom FROM documents d LEFT JOIN voyageurs v ON d.voyageur_id=v.id LEFT JOIN programmes p ON d.programme_id=p.id $where ORDER BY d.created_at DESC LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$documents = $stmt->fetchAll();

$typeIcons = ['passeport'=>'bi-journal-text','visa'=>'bi-passport','billet'=>'bi-ticket-perforated','contrat'=>'bi-file-earmark-text','medical'=>'bi-heart-pulse','autorisation'=>'bi-shield-check','facture'=>'bi-receipt','autre'=>'bi-file-earmark'];
?>

<div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
    <form class="d-flex gap-2 flex-wrap" method="GET">
        <div class="input-group" style="width:250px;">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control" placeholder="Rechercher..." value="<?= sanitize($search) ?>">
        </div>
        <select name="type" class="form-select" style="width:160px;">
            <option value="">Tous types</option>
            <option value="passeport" <?= $typeFilter=='passeport'?'selected':'' ?>>Passeport</option>
            <option value="visa" <?= $typeFilter=='visa'?'selected':'' ?>>Visa</option>
            <option value="billet" <?= $typeFilter=='billet'?'selected':'' ?>>Billet</option>
            <option value="contrat" <?= $typeFilter=='contrat'?'selected':'' ?>>Contrat</option>
            <option value="medical" <?= $typeFilter=='medical'?'selected':'' ?>>Médical</option>
            <option value="autre" <?= $typeFilter=='autre'?'selected':'' ?>>Autre</option>
        </select>
        <button class="btn btn-outline-primary">Filtrer</button>
    </form>
    <a href="<?= APP_URL ?>/documents.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Ajouter un document</a>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr><th>Type</th><th>Nom</th><th>Voyageur</th><th>Programme</th><th>Date</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($documents as $d): ?>
                <tr>
                    <td><i class="bi <?= $typeIcons[$d['type']] ?? 'bi-file-earmark' ?> me-1"></i><?= ucfirst($d['type']) ?></td>
                    <td><strong><?= sanitize($d['nom']) ?></strong><?php if ($d['notes']): ?><br><small class="text-muted"><?= sanitize($d['notes']) ?></small><?php endif; ?></td>
                    <td><?= $d['v_nom'] ? sanitize($d['v_prenom'].' '.$d['v_nom']) : '-' ?></td>
                    <td><small><?= sanitize($d['programme_nom'] ?: '-') ?></small></td>
                    <td><small><?= formatDateTime($d['created_at']) ?></small></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/uploads/documents/<?= $d['fichier'] ?>" class="btn btn-outline-primary" target="_blank" title="Voir"><i class="bi bi-eye"></i></a>
                            <a href="<?= APP_URL ?>/uploads/documents/<?= $d['fichier'] ?>" class="btn btn-outline-success" download title="Télécharger"><i class="bi bi-download"></i></a>
                            <a href="<?= APP_URL ?>/documents.php?action=delete&id=<?= $d['id'] ?>" class="btn btn-outline-danger" onclick="return confirmDelete()"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($documents)): ?><tr><td colspan="6" class="text-center text-muted py-4">Aucun document</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        <?= renderPagination($pagination, APP_URL.'/documents.php?search='.urlencode($search).'&type='.urlencode($typeFilter)) ?>
    </div>
</div>

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