<?php
include __DIR__ . '/user-ssinclude/user-init.php';
include __DIR__ . '/user-ssinclude/user-sessions.php';
include __DIR__ . '/user-ssinclude/user-header.php';

/* ==========================================
   CONFIG
========================================== */
$folder_table_name = "folders";
$order_by = "ord ASC";

/* ==========================================
   GET FOLDER ID
========================================== */
$folder_id = 0; // default root

if (!empty($_GET['fid'])) {
    $dec = decrypt_data($_GET['fid']);
    if (is_numeric($dec)) {
        $folder_id = (int)$dec;
    }
}

/* ==========================================
   BUILD BREADCRUMB (PATH)
========================================== */
$path = [];
$current = $folder_id;

while ($current > 0) {
    $stmt = $db->prepare("SELECT folder_id, parent_id, name FROM {$folder_table_name} WHERE folder_id = ? LIMIT 1");
    $stmt->execute([$current]);
    $f = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$f) break;

    array_unshift($path, $f);
    $current = (int)$f['parent_id'];
}

// Root always first
array_unshift($path, ['folder_id' => 0, 'name' => 'Racine']);

/* ==========================================
   GET SUBFOLDERS
========================================== */
$stmtFolders = $db->prepare("
    SELECT *
    FROM {$folder_table_name}
    WHERE parent_id = ?
      AND active = 1
    ORDER BY {$order_by}
");
$stmtFolders->execute([$folder_id]);
$folders = $stmtFolders->fetchAll(PDO::FETCH_ASSOC);

/* ==========================================
   BACK BUTTON
========================================== */
$back_url = null;

if ($folder_id > 0) {
    $stmtParent = $db->prepare("SELECT parent_id FROM {$folder_table_name} WHERE folder_id = ? LIMIT 1");
    $stmtParent->execute([$folder_id]);
    $p = $stmtParent->fetch(PDO::FETCH_ASSOC);

    if ($p) {
        $real_parent = (int)$p['parent_id'];
        $back_url = user_listing;
        if ($real_parent > 0) $back_url .= '?fid=' . encrypt_data($real_parent);
    }
}

/* ==========================================
   GET FILES IN FOLDER
========================================== */
$employee_id = $sessionData['EMPLOYEE_ID'];

// First, get folder visibility
$stmtFolder = $db->prepare("SELECT visibility FROM folders WHERE folder_id = :folder_id");
$stmtFolder->execute(['folder_id' => $folder_id]);
$folderData = $stmtFolder->fetch(PDO::FETCH_ASSOC);

$rs = [];

if ($folderData) {
    if ($folderData['visibility'] === 'public') {
        // Public folder: no employee filter
        $sql = "
            SELECT f.file_id, f.name AS file_name, f.file_path, f.file_size, 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]);
        $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        // Private folder: restrict to current employee
        $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
        ]);
        $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>

<div id="content" class="p-4 pt-5 w-100">

    <!-- PATH + BACK BUTTON -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="h5 m-0">
            <i class="fas fa-folder mr-2"></i>
            <?php
                $parts = [];
                foreach ($path as $p) $parts[] = htmlspecialchars($p['name']);
                echo implode(" / ", $parts);
            ?>
        </div>

        <?php if ($back_url): ?>
            <button class="btn btn-outline-secondary btn-sm" onclick="goTo('<?= $back_url ?>')" data-loader="on">
                <i class="fas fa-arrow-left"></i> Retour
            </button>
        <?php endif; ?>
    </div>

    <!-- SUBFOLDERS -->
    <?php if (!empty($folders)): ?>
        <div class="card mb-4 shadow">
            <div class="card-header bg-light">
                <i class="fas fa-folder mr-2"></i> Dossiers
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <?php foreach ($folders as $folder): ?>
                        <?php
                            $cid = encrypt_data($folder['folder_id']);
                            $icon = ($folder['visibility'] === "public")
                                    ? "/user-assets/img/files/folder.png"
                                    : "/user-assets/img/files/folder-private.png";
                        ?>
                        <div class="col-4 mb-3 text-center folder-item" style="cursor:pointer;"
                             onclick="goTo('<?= user_listing ?>?fid=<?= $cid ?>')" data-loader="on">
                            <img src="<?= $icon ?>" class="img-fluid mb-2" style="width:60px;" alt="Dossier">
                            <div class="small"><?= htmlspecialchars($folder['name']) ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>

   <!-- FILES / DOCUMENTS -->
<div class="card mb-4 shadow">
    <div class="card-header bg-light">
        <i class="fas fa-folder-open mr-2"></i> Documents du dossier
    </div>
    <div class="card-body">
        <div class="row text-center">
            <?php if (empty($rs)): ?>
                <div class="col-12 text-muted p-3">Aucun document dans ce dossier.</div>
            <?php else: ?>
                <?php foreach ($rs as $row): ?>
                    <?php
                        $ext = strtolower(pathinfo($row['file_name'], PATHINFO_EXTENSION));
                        $icon = match($ext) {
                            'jpg','jpeg' => "jpg.png",
                            'png' => "png.png",
                            'pdf' => "pdf.png",
                            'doc' => "doc.png",
                            'docx' => "docx.png",
                            default => "unknown.png"
                        };
                        $cid = encrypt_data($row['file_id']);
                    ?>
                    <div class="col-4 mb-3">
                        <a href="dw?<?= $cid ?>" class="text-decoration-none" data-loader="off" target="_blank">
                            <img src="/user-assets/img/files/<?= $icon ?>" class="img-fluid mb-2" style="width:60px;">
                            <div class="file-name"><?= htmlspecialchars($row['file_name']) ?></div>
                        </a>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>



</div>

<?php
include __DIR__ . "/user-ssinclude/user-footer.php";
?>
