<?php
// This script is intended to be included within admin_dashboard.php,
// ensuring $conn (database connection) is available.

$message = '';
$message_class = '';

// --- 1. HANDLE DOCUMENT UPLOAD LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['upload_document'])) {
    
    // Check if a file was actually uploaded
    if (isset($_FILES['document_file']) && $_FILES['document_file']['error'] === UPLOAD_ERR_OK) {
        
        $file_info = $_FILES['document_file'];
        $file_name_raw = $file_info['name'];
        $file_extension = strtolower(pathinfo($file_name_raw, PATHINFO_EXTENSION));
        
        // **File Type Validation: Allowed Document Types**
        $allowed_extensions = ['pdf', 'doc', 'docx', 'xlsx', 'xls', 'txt', 'ppt', 'pptx', 'rtf', 'csv'];
        if (!in_array($file_extension, $allowed_extensions)) {
            $message = "Error: File type '{$file_extension}' is not allowed. Only common document formats (PDF, DOCX, XLSX, etc.) are supported.";
            $message_class = 'error';
        } else {
            // Define the server path for documents
            // IMPORTANT: Make sure this directory exists on your server!
            $target_dir = 'uploads/general_documents/'; 
			// Normalize file name parts
			$path_info = pathinfo($file_name_raw);
			$base_name = $path_info['filename'];
			$ext = isset($path_info['extension']) ? $path_info['extension'] : '';

			// Build initial path
			$file_path = $target_dir . $file_name_raw;

			// If the file_path already exists, append timestamp (Ymd_His) to filename to avoid DB unique constraint
			if (file_exists($file_path)) {
				$timestamp = date('Ymd_His'); // e.g. 20251023_153045
				$file_name_raw = $base_name . '_' . $timestamp . ($ext ? '.' . $ext : '');
				$file_path = $target_dir . $file_name_raw;
			}

            
            // Use the authenticated user's ID for the Foreign Key constraint.
            $uploaded_by_id = $_SESSION['user_id'] ?? 1; 

            // **Database Table: general_documents**
            $sql_insert = "INSERT INTO general_documents (file_name, file_path, file_extension, uploaded_by) VALUES (?, ?, ?, ?)";

            if (isset($conn) && $stmt = $conn->prepare($sql_insert)) {
                
                $stmt->bind_param("sssi", $file_name_raw, $file_path, $file_extension, $uploaded_by_id);
                
                if ($stmt->execute()) {
                    
                    // === FIX: THIS LINE MOVES THE FILE FROM TEMP STORAGE TO ITS FINAL LOCATION ===
                    if (move_uploaded_file($file_info['tmp_name'], $file_path)) {
						//$message = "Success: Document '{$file_name_raw}' uploaded and saved successfully.";
						//$message_class = 'success';
						
						// Show popup alert for success
						echo "<script>window.alert.call(window, 'Success: Document {$file_name_raw} uploaded and saved successfully.');</script>";

                    } else {
                        // If file move fails, report the file system error
                        $message = "Error: Database updated, but **file system failed to save the file** to '{$file_path}'. Check that the directory ({$target_dir}) exists and has write permissions (e.g., chmod 777).";
                        $message_class = 'error';
                        
                        // OPTIONAL: Delete the DB entry since the file is missing
                        // $conn->query("DELETE FROM general_documents WHERE document_id = {$conn->insert_id}");
                    }
                    // =============================================================================

                } else {
                    $message = "Error uploading document (DB): " . $stmt->error;
                    $message_class = 'error';
                }
                $stmt->close();
            } else {
                $message = "Error: Database preparation failed for upload or connection unavailable.";
                $message_class = 'error';
            }
        }
    } else {
        // Handle case where no file was selected or a specific upload error occurred
        if (isset($_POST['upload_document'])) {
            $error_code = $_FILES['document_file']['error'] ?? UPLOAD_ERR_NO_FILE;
            
            switch ($error_code) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $message = "Error: The uploaded file exceeds the maximum file size allowed by the server configuration (php.ini limits).";
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $message = "Error: Please select a file to upload.";
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $message = "Error: The file was only partially uploaded.";
                    break;
                default:
                    $message = "Error: An unknown upload error occurred (Code: {$error_code}).";
                    break;
            }
            $message_class = 'error';
        }
    }
}

// --- 2. FETCH ALL DOCUMENTS FOR DISPLAY ---
$all_documents = [];

if (isset($conn)) {
    // IMPORTANT: Added gd.file_path to the SELECT query for the download link
    $sql_fetch = "
        SELECT 
            gd.document_id, 
            gd.file_name, 
            gd.file_path, 
            gd.file_extension, 
            u.username AS uploaded_by_name, 
            gd.uploaded_at 
        FROM general_documents gd
        LEFT JOIN users u ON gd.uploaded_by = u.user_id
        ORDER BY gd.uploaded_at DESC
    ";
    
    $result = $conn->query($sql_fetch);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $row['display_name'] = pathinfo($row['file_name'], PATHINFO_FILENAME);
            $row['uploaded_by'] = $row['uploaded_by_name'] ?? 'N/A';
            $all_documents[] = $row;
        }
    } else {
        $message_fetch = "Error retrieving documents. Check your database column names: " . $conn->error;
    }
}
?>

<style>
    /* Styling for buttons */
    .section-header {
        margin-bottom: 25px;
        color: #2c3e50;
    }
    .data-container {
        margin-top: 30px;
    }
    .btn-action {
        padding: 5px 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-right: 5px; /* Spacing between buttons */
        display: inline-block;
        text-decoration: none; /* Remove underline from anchor tag */
        text-align: center;
    }
	.btn-view {
        background-color: #2ecc71; /* Green color for 'View' */
        color: white;
    }
    .btn-view:hover {
        background-color: #27ae60;
    }
    .btn-delete {
        background-color: #e74c3c;
        color: white;
    }
    .btn-delete:hover {
        background-color: #c0392b;
    }
    .btn-download {
        background-color: #3498db;
        color: white;
    }
    .btn-download:hover {
        background-color: #2980b9;
    }
    /* Messages and form group styles remain the same */
    .message {
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 4px;
        font-weight: bold;
    }
    .message.success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .message.error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    .upload-form-group {
        display: flex;
        gap: 10px;
        align-items: flex-end;
    }
    .upload-form-group > div {
        flex-grow: 1;
    }
    .upload-form-group button {
        margin-top: 0;
        padding: 10px 15px;
    }
	
	
</style>

<script>
/**
 * Opens the document file path in a new browser tab.
 * Browsers are typically configured to view PDF files natively.
 * For other document types (DOCX, XLSX), the browser will usually
 * prompt the user to download the file, which is a sensible fallback.
 * @param {string} filePath - The server path to the document (e.g., 'uploads/general_documents/file.pdf').
 */
function viewDocument(filePath) {
    // We open the file path in a new tab/window
    window.open(filePath, '_blank');
}
</script>



<div class="form-card">
    <h2 class="section-header">Upload New General Document</h2>
    
    <?php if ($message): ?>
        <div class="message <?php echo $message_class; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <form method="POST" action="admin_dashboard.php?page=manage_documents" enctype="multipart/form-data">
        <input type="hidden" name="upload_document" value="1">
        
        <div class="upload-form-group">
            <div>
                <label for="document_file">Select Document (PDF, DOCX, XLSX, etc.)</label>
                <input type="file" id="document_file" name="document_file" style="padding-top: 5px;" accept=".pdf,.doc,.docx,.xlsx,.xls,.txt,.ppt,.pptx,.rtf,.csv" required>
            </div>
            
            <button type="submit" class="btn-primary">Upload Document</button>
        </div>
    </form>
</div>

<div class="form-card data-container">
    <h2 class="section-header">Document List</h2>
    
    <?php if (isset($message_fetch)): ?>
        <div class="message error"><?php echo htmlspecialchars($message_fetch); ?></div>
    <?php elseif (!empty($all_documents)): ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Extension</th> 
                    <th>Uploaded By</th>
                    <th>Uploaded At</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($all_documents as $document): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($document['document_id']); ?></td>
                        <td><?php echo htmlspecialchars($document['display_name']); ?></td> 
                        <td><?php echo htmlspecialchars($document['file_extension']); ?></td>
                        <td><?php echo htmlspecialchars($document['uploaded_by']); ?></td>
                        <td><?php echo htmlspecialchars($document['uploaded_at']); ?></td>
                        <td>
							<a href="<?php echo htmlspecialchars($document['file_path']); ?>" 
							   class="btn-action btn-download" 
							   download="<?php echo htmlspecialchars($document['file_name']); ?>">
								Download
							</a>
							
							<button class="btn-action btn-view" onclick="openPopup('<?php echo htmlspecialchars($document['file_path']); ?>', '<?php echo htmlspecialchars($document['file_extension']); ?>')">View</button>
													
							<button class="btn-action btn-delete" onclick="deleteDocument(<?php echo (int)$document['document_id']; ?>)">Delete</button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>No documents found in the database. Upload one above to get started.</p>
    <?php endif; ?>
</div>
<!-- Document Viewer Popup -->
<div id="popupModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%;
 background-color:rgba(0,0,0,0.6); z-index:9999; justify-content:center; align-items:center;">
    <div style="background:white; padding:20px; border-radius:8px; max-width:90%; max-height:90%; overflow:auto; position:relative;">
        <button onclick="closePopup()" style="position:absolute; top:10px; right:15px; background:red; color:white; border:none; border-radius:4px; padding:5px 10px;">X</button>
        <div id="popupContent" style="text-align:center;"></div>
    </div>
</div>


<script>
function openPopup(filePath, ext) {
    const popup = document.getElementById('popupModal');
    const content = document.getElementById('popupContent');
    ext = ext.toLowerCase();

    let viewerHTML = '';

    if (['pdf', 'png', 'jpg', 'jpeg', 'gif'].includes(ext)) {
        viewerHTML = `<iframe src="${filePath}" style="width:80vw; height:80vh; border:none;"></iframe>`;
    } 
    else if (['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt', 'rtf', 'csv'].includes(ext)) {
        viewerHTML = `<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=${window.location.origin}/${filePath}" style="width:80vw; height:80vh; border:none;"></iframe>`;
    } 
    else {
        viewerHTML = `<p>No preview available for .${ext} files.</p>`;
    }

    content.innerHTML = viewerHTML;
    popup.style.display = 'flex';
}

function closePopup() {
    document.getElementById('popupModal').style.display = 'none';
}

// --- Delete Document Logic ---
function deleteDocument(documentId) {
    if (!confirm('Are you sure you want to delete this document?')) return;

    fetch('delete_document.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'id=' + documentId
    })
    .then(response => response.text())
    .then(result => {
        alert(result.trim());
        location.reload();
    })
    .catch(error => {
        alert('Error deleting document: ' + error);
    });
}
</script>
