<?php
require_once(__DIR__ . '/../ssinclude/app-init.php');
require_once(__DIR__ . '/../ssinclude/app-session.php');

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

// ID du dossier crypté
$id = verif_get('id');
$folder_id = decrypt_data($id);

$sessionData['last_folder_line'] = $folder_id;
storeSession($sessionId, $sessionData);

// ID employé crypté
$id = verif_get('id_employee');
$employee_id = decrypt_data($id);

if (!is_numeric($folder_id)) {
    exit('<tr><td class="text-center">ID de dossier invalide</td></tr>');
}

try {
    // Vérifier si dossier public/private
    $stmtFolder = $db->prepare("SELECT visibility FROM folders WHERE folder_id = :folder_id");
    $stmtFolder->execute(['folder_id' => $folder_id]);
    $folder = $stmtFolder->fetch(PDO::FETCH_ASSOC);

    if (!$folder) {
        exit('<tr><td class="text-center">Dossier introuvable</td></tr>');
    }

    if ($folder['visibility'] === 'public') {

        // Dossier public → pas de jointure employees
        $sql = "
            SELECT f.file_id, f.file_size, f.name AS file_name, f.file_path, f.file_type, f.created_on
            FROM files f
            WHERE f.folder_id = :folder_id
            ORDER BY f.created_on DESC
        ";
        $stmt = $db->prepare($sql);
        $stmt->execute(['folder_id' => $folder_id]);
        $files = $stmt->fetchAll(PDO::FETCH_ASSOC);

    } else {

        // Dossier privé → jointure employees
        $sql = "
            SELECT 
                f.file_id,
                f.name AS file_name,
                f.file_path,
                f.file_size,
                f.file_type,
                f.created_on,
                CONCAT(e.first_name,' ',e.last_name) AS employee_name
            FROM files f
            INNER JOIN employee_files ef ON ef.file_id = f.file_id
            INNER JOIN employees e ON e.employee_id = ef.employee_id
            WHERE f.folder_id = :folder_id 
              AND e.employee_id = :employee_id
            ORDER BY f.created_on DESC
        ";
        $stmt = $db->prepare($sql);
        $stmt->execute([
            'folder_id' => $folder_id,
            'employee_id' => $employee_id
        ]);
        $files = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    if (empty($files)) {
        echo '<tr><td class="text-center">Le dossier est vide</td></tr>';
        exit;
    }

    foreach ($files as $file) {

        $ext = strtolower(pathinfo($file['file_name'], PATHINFO_EXTENSION));

        $icon = "unknown.png";
        if (in_array($ext, ['jpg','jpeg'])) $icon = "jpg.png";
        elseif ($ext === 'png') $icon = "png.png";
        elseif ($ext === 'pdf') $icon = "pdf.png";
        elseif ($ext === 'doc') $icon = "doc.png";
        elseif ($ext === 'docx') $icon = "docx.png";

        // URL fichier
        $fileUrl = "dw?" . encrypt_data($file['file_id']);

        echo '
        <tr class="bg-tr-light-2" data-file-id="' . $file['file_id'] . '">
            <td style="padding: 8px 12px;">
                <div style="display: flex; align-items: center; justify-content: space-between;">

                    <a style="display: flex; align-items: center;" href="' . $fileUrl . '" target="_blank">
                        <img class="file-icon" src="assets/img/files/' . htmlspecialchars($icon) . '" 
                             style="max-width: 40px; margin-right: 10px;">
                        
                        <div>
                            <b style="color:#555 !important;">' . htmlspecialchars($file['file_name']) . '</b>
                            <div class="text-muted small">'
                                . htmlspecialchars($file['created_on']) . 
                                ' (' . formatFileSize($file['file_size']) . ')
                            </div>
                        </div>
                    </a>

                    <div>
                        <button class="btn btn-sm btn-danger delete-file-btn" 
                                data-file-id="' . $file['file_id'] . '">
                            <i class="fa fa-trash" aria-hidden="true"></i>
                        </button>
                    </div>

                </div>
            </td>
        </tr>';
    }

} catch (PDOException $e) {
    echo '<tr><td>Erreur : ' . htmlspecialchars($e->getMessage()) . '</td></tr>';
}

require_once(__DIR__ . '/../ssinclude/app-close.php');
?>
