<?php
include 'functions.php';

// Always use pmed documents and pmed DB connection on admin side
$dbConn = isset($conn2) ? $conn2 : $conn;
$table = 'pmed_documents';

$divisionId = isset($_GET['division_id']) ? (int)$_GET['division_id'] : 1;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'asc';
$fileType = isset($_GET['file_type']) ? $_GET['file_type'] : '';
// Search and pagination
$searchQuery = isset($_GET['search_query']) ? $_GET['search_query'] : '';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$rowsPerPage = isset($_GET['rowsPerPage']) ? (int)$_GET['rowsPerPage'] : 25;
$offset = ($page - 1) * $rowsPerPage;

if (!$dbConn) {
    echo "<tr><td colspan='8'>Error: Database connection failed</td></tr>";
    exit();
}

// Field names
$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";

// File type filter (supports comma-separated list)
if (!empty($fileType)) {
    $fileTypeArray = explode(',', $fileType);
    $parts = [];
    foreach ($fileTypeArray as $t) {
        $parts[] = "$fileTypeField = '" . $dbConn->real_escape_string(trim($t)) . "'";
    }
    if (!empty($parts)) {
        $query .= " AND (" . implode(' OR ', $parts) . ")";
    }
}

// Sorting
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";
}

// Search across fields
if (!empty($searchQuery)) {
    $s = $dbConn->real_escape_string($searchQuery);
    $query .= " AND ($fileNameField LIKE '%$s%' OR $authorField LIKE '%$s%' OR $fileTypeField LIKE '%$s%' OR $uploadDateField LIKE '%$s%' OR $refNoField LIKE '%$s%')";
    // Log on main connection when available
    if (isset($conn)) {
        logAction($conn, isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0, isset($_SESSION['username']) ? $_SESSION['username'] : 'Guest', "Searched documents: '$s'");
    }
}

// Pagination
$query .= " LIMIT $rowsPerPage OFFSET $offset";

$result = $dbConn->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/edit.svg' alt='Edit' class='icon-button' onclick=\"openEditModal('{$row[$documentIdField]}', '" . htmlspecialchars($row[$fileNameField], ENT_QUOTES) . "', '" . htmlspecialchars($row[$authorField], ENT_QUOTES) . "', '" . htmlspecialchars($row[$descriptionField], ENT_QUOTES) . "', '{$row[$fileSizeField]}', '{$row[$resolutionField]}', '{$row[$filePathField]}', '{$row[$statusField]}', '{$row[$refNoField]}', '{$divisionId}')\"> 
                        <span class='tooltip-text'>Edit File</span>
                    </div>
                    <div class='tooltip'>
                        <img src='icons/action/paper_plane.svg' alt='email' class='icon-button' onclick=\"openEmailModalFromTable('{$row[$documentIdField]}', '" . addslashes($row[$fileNameField]) . "', '{$divisionId}')\"> 
                        <span class='tooltip-text'>Send Via Email</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 class='tooltip'>
                        <img src='icons/action/delete.svg' alt='Delete' class='icon-button' onclick=\"confirmDelete('{$row[$documentIdField]}', '{$divisionId}')\"> 
                        <span class='tooltip-text'>Delete</span>
                    </div>
                </div>
            </td>
        </tr>";
    }
} else {
    echo "<tr><td colspan='8'>No documents found</td></tr>";
}

// No close here; connections are global and reused
?>
