<?php
require_once 'auth.php';
require_once '../config/database.php';
check_admin_login();

// Handle document deletion
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    
    // Obtenir le nom du fichier pour le supprimer du disque
    $stmt = $pdo->prepare("SELECT file_path FROM documents WHERE id = :id");
    $stmt->execute(['id' => $id]);
    $doc = $stmt->fetch();
    
    if ($doc && file_exists('../uploads/' . $doc['file_path'])) {
        unlink('../uploads/' . $doc['file_path']);
    }

    $stmt = $pdo->prepare("DELETE FROM documents WHERE id = :id");
    $stmt->execute(['id' => $id]);
    header("Location: documents.php");
    exit;
}

// Handle document upload
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $type = $_POST['type'] ?? 'bulletin';
    $date_document = $_POST['date_document'] ?? date('Y-m-d');
    
    if (isset($_FILES['document']) && $_FILES['document']['error'] == 0) {
        $allowed = ['pdf'];
        $filename = $_FILES['document']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_filename = uniqid() . '-' . str_replace(' ', '-', strtolower($filename));
            $destination = '../uploads/' . $new_filename;
            if (!is_dir('../uploads')) mkdir('../uploads', 0777, true);
            
            if (move_uploaded_file($_FILES['document']['tmp_name'], $destination)) {
                $stmt = $pdo->prepare("INSERT INTO documents (title, type, file_path, date_document) VALUES (:title, :type, :file_path, :date_document)");
                $stmt->execute([
                    'title' => $title,
                    'type' => $type,
                    'file_path' => $new_filename,
                    'date_document' => $date_document
                ]);
            }
        }
    }
    header("Location: documents.php");
    exit;
}

// Fetch documents
$stmt = $pdo->query("SELECT * FROM documents ORDER BY date_document DESC");
$documents = $stmt->fetchAll();

function getBadgeColor($type) {
    switch($type) {
        case 'bulletin': return 'bg-blue-100 text-blue-800';
        case 'compte_rendu': return 'bg-purple-100 text-purple-800';
        case 'arrete_municipal': return 'bg-orange-100 text-orange-800';
        case 'arrete_prefectoral': return 'bg-red-100 text-red-800';
        default: return 'bg-gray-100 text-gray-800';
    }
}

function getTypeLabel($type) {
    switch($type) {
        case 'bulletin': return 'Bulletin Communal';
        case 'compte_rendu': return 'Compte-rendu de réunion';
        case 'arrete_municipal': return 'Arrêté Municipal';
        case 'arrete_prefectoral': return 'Arrêté Préfectoral';
        default: return 'Autre Document';
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Documents - Admin Kutzenhausen</title>
    <script src="../js/tailwind.min.js"></script>
    <script src="../js/lucide.min.js"></script>
</head>
<body class="bg-gray-50 flex h-screen font-sans text-gray-800">

    <?php include 'includes/sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-screen overflow-hidden">
        
        <header class="h-20 bg-white shadow-sm flex items-center justify-between px-8 flex-shrink-0">
            <div class="flex items-center space-x-4">
                <i data-lucide="file-archive" class="w-8 h-8 text-[#7b2c2d]"></i>
                <h1 class="text-2xl font-bold text-gray-800">Documents Officiels (PDF)</h1>
            </div>
        </header>
        
        <div class="flex-1 overflow-auto p-8 flex space-x-8">
            
            <div class="flex-1 bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden h-fit">
                <div class="p-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center">
                    <h2 class="font-bold text-gray-700">Fichiers publiés</h2>
                </div>

                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-gray-50 border-b border-gray-200">
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600">Document</th>
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600">Catégorie</th>
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600">Date</th>
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        <?php foreach($documents as $doc): ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-6 py-4">
                                <div class="flex items-center space-x-3">
                                    <i data-lucide="file-text" class="w-5 h-5 text-red-500"></i>
                                    <div>
                                        <p class="font-medium text-gray-800"><a href="../uploads/<?php echo htmlspecialchars($doc['file_path']); ?>" target="_blank" class="hover:text-alsace-red hover:underline"><?php echo htmlspecialchars($doc['title']); ?></a></p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo getBadgeColor($doc['type']); ?>">
                                    <?php echo getTypeLabel($doc['type']); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-500">
                                <?php echo date('d/m/Y', strtotime($doc['date_document'])); ?>
                            </td>
                            <td class="px-6 py-4 text-right space-x-2">
                                <a href="documents.php?delete=<?php echo $doc['id']; ?>" class="inline-flex items-center p-2 bg-red-50 text-red-600 rounded-md hover:bg-red-100 transition" title="Supprimer" onclick="return confirm('Êtes-vous sûr de vouloir supprimer ce document ?')">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($documents)): ?>
                        <tr>
                            <td colspan="4" class="px-6 py-8 text-center text-gray-500">Aucun document pour le moment.</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="w-1/3 bg-white rounded-xl shadow-sm border border-gray-200 h-fit">
                <div class="p-4 border-b border-gray-200 bg-[#5c1a1b] text-white rounded-t-xl">
                    <h2 class="font-bold flex items-center"><i data-lucide="upload-cloud" class="w-5 h-5 mr-2"></i> Mettre en ligne un PDF</h2>
                </div>
                <div class="p-6">
                    <form action="" method="POST" enctype="multipart/form-data" class="space-y-4">
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Titre du document</label>
                            <input type="text" name="title" required placeholder="Ex: Compte rendu du 24 Mars" class="w-full border border-gray-300 rounded-md p-2 outline-none focus:border-[#7b2c2d]">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Type de publication</label>
                            <select name="type" class="w-full border border-gray-300 rounded-md p-2 outline-none focus:border-[#7b2c2d]">
                                <option value="bulletin">Bulletin Communal</option>
                                <option value="compte_rendu">Compte-rendu de réunion</option>
                                <option value="arrete_municipal">Arrêté Municipal</option>
                                <option value="arrete_prefectoral">Arrêté Préfectoral</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Date associée</label>
                            <input type="date" name="date_document" required value="<?php echo date('Y-m-d'); ?>" class="w-full border border-gray-300 rounded-md p-2 outline-none focus:border-[#7b2c2d]">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Fichier PDF</label>
                            <input type="file" name="document" accept=".pdf" required class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-red-50 file:text-[#7b2c2d] hover:file:bg-red-100 border border-gray-200">
                        </div>

                        <button type="submit" class="w-full bg-[#7b2c2d] hover:bg-[#5c1a1b] text-white font-bold py-2 px-4 rounded mt-4 transition flex justify-center items-center">
                            <i data-lucide="upload" class="w-4 h-4 mr-2"></i> Publier le document
                        </button>
                    </form>
                </div>
            </div>

        </div>
    </main>

    <script>
        lucide.createIcons();
    </script>
</body>
</html>
