<?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/'; 
            $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-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>

<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>Date</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(substr($document['uploaded_at'], 0, 10)); ?></td>
                        <td>
                            <!-- DOWNLOAD BUTTON: Uses file_path from the database in an anchor tag -->
                            <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-delete">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>
