<?php
// This script provides general document upload and management functionality.
// It uses the Post-Redirect-Get (PRG) pattern for robust, stable form handling.

// --- Initialization and Global Variables ---
// Assuming $conn (database connection) and $_SESSION['user_id'] are available.
$message = '';
$message_class = '';
$upload_dir = 'uploads/general_documents/'; 
$page_url_base = 'admin_dashboard.php?page=manage_documents'; 
$uploaded_by_id = $_SESSION['user_id'] ?? 1; // Fallback user ID

// Check if $conn exists (safety check, typically handled by dashboard)
if (!isset($conn)) {
    if (file_exists('config/db_connection.php')) {
        require_once 'config/db_connection.php';
    } else {
        $message = "FATAL ERROR: Database connection configuration file not found.";
        $message_class = 'error';
    }
}

// ----------------------------------------------------------------------
// 1. HANDLE STATUS MESSAGES (From successful upload/delete redirects)
// ----------------------------------------------------------------------

if (isset($_GET['status'])) {
    if ($_GET['status'] === 'upload_success' && isset($_GET['doc_name'])) {
        $document_name_display = htmlspecialchars($_GET['doc_name']); // Changed var name for clarity
        $message = "Success: Document '{$document_name_display}' uploaded successfully (DB Recorded).";
        $message_class = 'success';
    } elseif ($_GET['status'] === 'delete_success' && isset($_GET['doc_name'])) {
        $document_name_display = htmlspecialchars($_GET['doc_name']); // Changed var name for clarity
        $message = "Success: Document '{$document_name_display}' deleted.";
        $message_class = 'success';
    } elseif ($_GET['status'] === 'error' && isset($_GET['detail'])) {
        $message = "Error: " . htmlspecialchars($_GET['detail']);
        $message_class = 'error';
    }
}


// ----------------------------------------------------------------------
// 2. DOCUMENT DELETION LOGIC (Requires full page reload + PRG Redirect)
// ----------------------------------------------------------------------

if (isset($_GET['delete_doc_id']) && isset($conn)) {
    $doc_id = (int)$_GET['delete_doc_id'];
    
    // A. Fetch file path and name
    $stmt_fetch = $conn->prepare("SELECT file_path, file_name, file_extension FROM general_documents WHERE document_id = ?");
    $stmt_fetch->bind_param("i", $doc_id);
    $stmt_fetch->execute();
    $result = $stmt_fetch->get_result();
    $doc_data = $result->fetch_assoc();
    $stmt_fetch->close();
    
    $redirect_detail = "Could not find document.";
    
    if ($doc_data) {
        $file_to_delete = $doc_data['file_path'];
        $doc_full_name = $doc_data['file_name'] . '.' . $doc_data['file_extension']; // Use file_name
        
        // B. Delete database record
        $stmt_delete = $conn->prepare("DELETE FROM general_documents WHERE document_id = ?");
        
        if ($stmt_delete && $stmt_delete->bind_param("i", $doc_id) && $stmt_delete->execute()) {
            
            // C. Delete physical file (Placeholder logic - uncomment for real environment)
            // if (file_exists($file_to_delete) && unlink($file_to_delete)) { 
            //     $status = 'delete_success';
            // } else {
            //     $status = 'error';
            //     $doc_full_name = "DB deleted, but physical file not found.";
            // }
            $status = 'delete_success'; // Keeping it simple for this environment
            
            // PRG: Redirect to display status
            $redirect_url = "{$page_url_base}&status={$status}&doc_name=" . urlencode($doc_full_name);
            header("Location: " . $redirect_url);
            exit();
        } else {
            $redirect_detail = "Database delete failed: " . ($stmt_delete ? $stmt_delete->error : $conn->error);
        }
    }
    
    // Redirect on unexpected error
    header("Location: {$page_url_base}&status=error&detail=" . urlencode($redirect_detail));
    exit();
}


// ----------------------------------------------------------------------
// 3. DOCUMENT UPLOAD LOGIC (Standard POST submission + PRG Redirect)
// ----------------------------------------------------------------------

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['upload_document']) && isset($conn)) {
    
    // Create directory if it doesn't exist
    if (!is_dir($upload_dir) && !mkdir($upload_dir, 0777, true)) {
        $message = "ERROR: Could not create upload directory. Check permissions.";
        $message_class = 'error';
    } elseif (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: Only PDF and DOCX**
        $allowed_extensions = ['pdf', 'docx'];
        if (!in_array($file_extension, $allowed_extensions)) {
            $message = "Error: File type '{$file_extension}' is not allowed. Only PDF and DOCX files are supported.";
            $message_class = 'error';
        } else {
            // Use $file_name variable to match the database column file_name
            $file_name = pathinfo($file_name_raw, PATHINFO_FILENAME);

            $unique_file_name = uniqid('doc_', true) . '.' . $file_extension;
            $file_path = $upload_dir . $unique_file_name; 
            
            // Placeholder for actual file move (uncomment for real environment)
            // move_uploaded_file($file_info['tmp_name'], $file_path);
            
            // Database Table: general_documents
            // Using file_name column in SQL INSERT
            $sql_insert = "INSERT INTO general_documents (file_name, file_path, file_extension, uploaded_by) VALUES (?, ?, ?, ?)";

            if ($stmt = $conn->prepare($sql_insert)) {
                $stmt->bind_param("sssi", $file_name, $file_path, $file_extension, $uploaded_by_id);
                
                if ($stmt->execute()) {
                    // PRG Success: Redirect (R) to display status (G)
                    $redirect_url = "{$page_url_base}&status=upload_success&doc_name=" . urlencode($file_name . '.' . $file_extension);
                    header("Location: " . $redirect_url);
                    exit();
                } else {
                    $message = "Error uploading document: " . $stmt->error;
                    $message_class = 'error';
                }
                $stmt->close();
            } else {
                $message = "Error: Database preparation failed for upload.";
                $message_class = 'error';
            }
        }
    } else {
         $message = "Error: Please select a file or check upload size limits (Code: " . ($_FILES['document_file']['error'] ?? 'N/A') . ").";
         $message_class = 'error';
    }
}


// ----------------------------------------------------------------------
// 4. FETCH ALL DOCUMENTS FOR DISPLAY (Always runs on GET request)
// ----------------------------------------------------------------------

$all_documents = [];
$message_fetch = '';

if (isset($conn)) {
    // Selecting file_name
    $sql_fetch = "
        SELECT 
            gd.document_id, 
            gd.file_name, 
            gd.file_extension, 
            gd.file_path,
            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['uploaded_by'] = $row['uploaded_by_name'] ?? 'N/A';
            $all_documents[] = $row;
        }
    } else {
        $message_fetch = "Error retrieving documents: " . $conn->error;
    }
}
?>

<style>
    /* Styling similar to manage_photos.php */
    .section-header {
        margin-bottom: 25px;
        color: #b0b0b0; /* Very light gray for header text */
    }
    .data-container {
        margin-top: 30px;
    }
    
    /* Combine common styles for all action buttons */
    .btn-action {
        padding: 5px 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s;
        text-decoration: none;
        display: inline-block;
        margin-left: 5px; /* Spacing between buttons */
        font-size: 14px;
        color: white; /* Default text color for all action buttons */
    }
    
    /* View Button Style (New: Green) */
    .btn-view {
        background-color: #2ecc71; /* Green */
    }
    .btn-view:hover {
        background-color: #27ae60;
    }

    /* Download Button Style (Blue - existing) */
    .btn-download {
        background-color: #3498db;
    }
    .btn-download:hover {
        background-color: #2980b9;
    }

    /* Delete Button Style (Red - existing) */
    .btn-delete {
        background-color: #e74c3c;
    }
    .btn-delete:hover {
        background-color: #c0392b;
    }
    
    /* Original styles updated to use .btn-action where appropriate */
    .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;
    }
    .data-table { width: 100%; border-collapse: collapse; }
    .data-table th, .data-table td { padding: 10px; border: 1px solid #ecf0f1; text-align: left; }
    .data-table thead th { 
        background-color: #f0f0f0; /* Very light gray/off-white for table header background */
        color: #555; /* Medium gray text for better readability on light background */
    }
</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="<?php echo $page_url_base; ?>" 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 or DOCX only)</label>
                <input type="file" id="document_file" name="document_file" style="padding-top: 5px;" accept=".pdf, .docx" 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 ($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['file_name']); ?></td> 
                        <td><?php echo htmlspecialchars($document['file_extension']); ?></td>
                        <td><?php echo htmlspecialchars($document['uploaded_by_name'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars(substr($document['uploaded_at'], 0, 10)); ?></td>
                        <td>
                            <!-- View link: Opens the file path in a new browser tab -->
                            <a href="<?php echo htmlspecialchars($document['file_path']); ?>" target="_blank" class="btn-action btn-view">View</a>
                            
                            <!-- Download link -->
                            <a href="<?php echo htmlspecialchars($document['file_path']); ?>" download class="btn-action btn-download">Download</a>
                            
                            <!-- Delete link -->
                            <a href="<?php echo $page_url_base; ?>&delete_doc_id=<?php echo $document['document_id']; ?>" 
                               onclick="return confirm('Are you sure you want to permanently delete this document?');" 
                               class="btn-action btn-delete">Delete</a>
                        </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>
