<?php
include 'functions.php';

$divisionId = $_GET['division_id'] ?? 1;
$sort = $_GET['sort'] ?? 'asc';
$fileType = $_GET['file_type'] ?? '';

$table = getDivisionTable($divisionId);
$divisionConn = getDivisionConnection($divisionId);
$divisionPrefix = getDivisionPrefix($divisionId);

if (!$table || !$divisionConn) {
    echo "<tr><td colspan='8'>Error: Invalid division or database connection failed</td></tr>";
    exit();
}

// Define field names for the current division
$documentIdField = 'pmed_document_id';
$refNoField = 'pmed_ref_no';
$fileNameField = 'pmed_file_name';
$authorField = 'pmed_author';
$fileTypeField = 'pmed_file_type';
$uploadDateField = 'pmed_upload_date';
$lastUpdatedField = 'pmed_last_updated';
$statusField = 'pmed_status';
$filePathField = 'pmed_file_path';
$descriptionField = 'pmed_description';
$fileSizeField = 'pmed_file_size';
$resolutionField = 'pmed_resolution';

$query = "SELECT * FROM $table WHERE 1=1";

if ($fileType) {
    // Handle multiple file extensions for a category
    $fileTypeArray = explode(',', $fileType);
    $fileTypeConditions = array_map(function ($type) use ($divisionConn, $fileTypeField) {
        return "$fileTypeField = '" . $divisionConn->real_escape_string(trim($type)) . "'";
    }, $fileTypeArray);
    $query .= " AND (" . implode(' OR ', $fileTypeConditions) . ")";
}

if ($sort === 'asc' || $sort === 'desc') {
    $query .= " ORDER BY $fileNameField $sort";
} elseif ($sort === 'date_asc') {
    $query .= " ORDER BY $uploadDateField ASC";
} elseif ($sort === 'date_desc') {
    $query .= " ORDER BY $uploadDateField DESC";
}

$result = $divisionConn->query($query);

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<tr>
            <td>{$row[$refNoField]}</td>
            <td>{$row[$fileNameField]}</td>
            <td>{$row[$authorField]}</td>
            <td>{$row[$fileTypeField]}</td>
            <td>{$row[$uploadDateField]}</td>
            <td>{$row[$lastUpdatedField]}</td>
            <td>{$row[$statusField]}</td>
            <td>
                <div class='action'>
                    <div class='tooltip'>
                        <img src='../../icons/action/view.svg' alt='Preview' class='icon-button' onclick=\"openFileModal('" . addslashes($row[$fileNameField]) . "', '" . addslashes($row[$authorField]) . "', '" . addslashes($row[$fileTypeField]) . "', '" . addslashes($row[$uploadDateField]) . "', '" . addslashes($row[$lastUpdatedField]) . "', '" . addslashes($row[$filePathField]) . "', '{$row[$documentIdField]}', '" . addslashes($row[$descriptionField]) . "', '{$row[$fileSizeField]}', '" . addslashes($row[$resolutionField]) . "', '" . addslashes($row[$refNoField]) . "', '{$divisionId}')\">
                        <span class='tooltip-text'>Preview</span>
                    </div>
                    <div class='tooltip'>
                        <img src='../../icons/action/download.svg' alt='Download' class='icon-button' onclick=\"window.location.href='download.php?id={$row[$documentIdField]}&division_id={$divisionId}'\">
                        <span class='tooltip-text'>Download</span>
                    </div>
                </div>
            </td>
        </tr>";
    }
} else {
    echo "<tr><td colspan='8'>No documents found</td></tr>";
}

// Close the division connection
$divisionConn->close();
?>
