<?php
// This script provides file upload and management functionality.
// It uses a full page reload architecture (PRG) to ensure stable dashboard rendering
// and eliminate the "second sidebar" issue common with partial reloads.

// --- Initialization and Global Variables ---
// Assuming $conn (database connection) and $_SESSION data are available.
$upload_message = '';
$upload_dir = 'uploads/confidential/'; 
$user_id = $_SESSION['user_id'] ?? 1; // Default user_id if session isn't set
$current_category = ''; 
$page_url_base = 'admin_dashboard.php?page=upload_confidential'; // Base URL for redirects/links

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

if (isset($_GET['status'])) {
    if ($_GET['status'] === 'upload_success' && isset($_GET['file_name'])) {
        $uploaded_file_name = htmlspecialchars($_GET['file_name']);
        $upload_message = "<p style='color:green; font-weight: bold;'>File <b>{$uploaded_file_name}</b> uploaded successfully.</p>";
    } elseif ($_GET['status'] === 'delete_success' && isset($_GET['file_name'])) {
        $deleted_file_name = htmlspecialchars($_GET['file_name']);
        $upload_message = "<p style='color:green; font-weight: bold;'>File <b>{$deleted_file_name}</b> successfully deleted.</p>";
    } elseif ($_GET['status'] === 'delete_error') {
         $upload_message = "<p style='color:red; font-weight: bold;'>Error: Could not complete file deletion.</p>";
    }
}

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

if (isset($_GET['delete_file_id'])) {
    $file_id = (int)$_GET['delete_file_id'];
    $category_after_delete = $_GET['list_category'] ?? '';

    if ($file_id > 0 && isset($conn)) {
        // A. Fetch file path
        $stmt_fetch = $conn->prepare("SELECT file_path, file_name FROM confidential_files WHERE file_id = ?");
        $stmt_fetch->bind_param("i", $file_id);
        $stmt_fetch->execute();
        $result = $stmt_fetch->get_result();
        $file_data = $result->fetch_assoc();
        $stmt_fetch->close();

        if ($file_data) {
            $file_to_delete = $file_data['file_path'];
            $file_name_deleted = $file_data['file_name'];

            // B. Delete database record
            $stmt_delete = $conn->prepare("DELETE FROM confidential_files WHERE file_id = ?");
            
            if ($stmt_delete && $stmt_delete->bind_param("i", $file_id) && $stmt_delete->execute()) {
                // C. Delete physical file
                if (file_exists($file_to_delete) && unlink($file_to_delete)) {
                    $status = 'delete_success';
                } else {
                    // DB record deleted, but physical file failed to unlink
                    $status = 'delete_error';
                    $file_name_deleted = "DB record deleted, but physical file failed."; 
                }
                
                // PRG: Redirect to display status and refresh the list
                $redirect_url = "{$page_url_base}&list_category=" . urlencode($category_after_delete) . "&status={$status}&file_name=" . urlencode($file_name_deleted);
                echo "<script>window.location.href='" . $redirect_url . "';</script>";
				exit();

            } else {
                $status_message = "Database delete failed: " . ($stmt_delete ? $stmt_delete->error : $conn->error);
            }
        } else {
            $status_message = "Error: File not found in database.";
        }
    } else {
        $status_message = "Invalid file ID for deletion.";
    }
    
    // If we reach here, a non-redirectable error occurred during the process
    $upload_message = "<p style='color:red;'>{$status_message}</p>";
}

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

$is_upload_dir_ok = true;
if (!is_dir($upload_dir) && !mkdir($upload_dir, 0777, true)) {
    $upload_message = "<p style='color:red; font-weight: bold;'>ERROR: Could not create upload directory. Check permissions.</p>";
    $is_upload_dir_ok = false;
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['upload_confidential']) && $is_upload_dir_ok) {
    if (empty($_FILES['conf_file']['name']) || $_FILES['conf_file']['error'] !== 0) {
        $upload_message = "<p style='color:red;'>Please select a file to upload.</p>";
    } else {
        $category = $conn->real_escape_string($_POST['category']);
        $file_name_original = $conn->real_escape_string($_FILES['conf_file']['name']);
        
        $new_file_name = uniqid('conf_', true) . '.' . pathinfo($file_name_original, PATHINFO_EXTENSION);
        $target_file = $upload_dir . $new_file_name;
        
        if (move_uploaded_file($_FILES['conf_file']['tmp_name'], $target_file)) {
            $sql = "INSERT INTO confidential_files (file_name, file_path, category, uploaded_by) VALUES (?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            
            if ($stmt && $stmt->bind_param("sssi", $file_name_original, $target_file, $category, $user_id) && $stmt->execute()) {
                // PRG Success: Redirect (R) to the list view (G)
                $redirect_url = "{$page_url_base}&list_category=" . urlencode($category) . "&status=upload_success&file_name=" . urlencode($file_name_original);
                
                echo "<script>window.location.href='" . $redirect_url . "';</script>";
                exit(); 
                
            } else {
                // Database insert failed (No Redirect)
                $upload_message = "<p style='color:red;'>Database insert failed: " . ($stmt ? $stmt->error : $conn->error) . "</p>";
                if (file_exists($target_file)) unlink($target_file); 
            }
            if ($stmt) $stmt->close();
        } else {
            $upload_message = "<p style='color:red;'>Error moving file to directory. Check permissions.</p>";
        }
    }
}


// ----------------------------------------------------------------------
// 4. SET CURRENT CATEGORY FOR DISPLAY (Check for list_category in URL)
// ----------------------------------------------------------------------

if (isset($_GET['list_category'])) {
    $current_category = $_GET['list_category'];
}


// ----------------------------------------------------------------------
// 5. CORE FUNCTION (Generates the file list HTML)
// ----------------------------------------------------------------------

function get_confidential_files_html($conn, $category, $page_url_base) {
    $category_escaped = $conn->real_escape_string($category);
    
    $sql = "SELECT cf.file_id, cf.file_name, cf.file_path, cf.upload_date, u.username 
            FROM confidential_files cf
            LEFT JOIN users u ON cf.uploaded_by = u.user_id
            WHERE cf.category = ?
            ORDER BY cf.upload_date DESC";
    
    $stmt = $conn->prepare($sql);
    $output = "";

    if ($stmt) {
        $stmt->bind_param("s", $category_escaped);
        $stmt->execute();
        $result = $stmt->get_result();

        $output .= "<h3 style='margin-top: 20px; color: #2c3e50; border-bottom: 1px solid #ccc; padding-bottom: 5px;'>Files in Category: {$category}</h3>";

        if ($result->num_rows > 0) {
            $output .= "<table class='data-table file-list-table'>";
            $output .= "<thead><tr><th>File Name</th><th>Uploaded By</th><th>Date</th><th style='width: 150px; text-align: center;'>Actions</th></tr></thead>";
            $output .= "<tbody>";
            
            while ($row = $result->fetch_assoc()) {
                $file_id = htmlspecialchars($row['file_id']);
                $file_name = htmlspecialchars($row['file_name']);
                $upload_date = date('Y-m-d H:i', strtotime($row['upload_date'])); 
                $uploader = htmlspecialchars($row['username'] ?? 'N/A');
                
                $output .= "<tr id='file-row-{$file_id}'>"; 
                $output .= "<td>{$file_name}</td>";
                $output .= "<td>{$uploader}</td>";
                $output .= "<td>{$upload_date}</td>";
                $output .= "<td class='table-actions'>";
				$output .= "<a href='#' class='action-button view-btn' data-filepath='{$row['file_path']}' data-filename='{$file_name}'>View</a>";
                $output .= "<a href='{$row['file_path']}' download='{$file_name}' class='action-button download-btn'>Download</a>";
                
                // Deletion link: includes the current category so the list remains open after deletion
                $output .= "<a href='{$page_url_base}&list_category={$category}&delete_file_id={$file_id}' 
                             onclick=\"return confirm('Are you sure you want to permanently delete the file \\'{$file_name}\\'?');\" 
                             class='action-button delete-btn'>Delete</a>";
                $output .= "</td>";
                $output .= "</tr>";
            }
            
            $output .= "</tbody>";
            $output .= "</table>";
        } else {
            $output .= "<p>No confidential files found for the category: <b>{$category}</b>.</p>";
        }

        $stmt->close();
    } else {
        $output .= "<p style='color:red;'>Error fetching files (DB Connection Error).</p>";
    }
    
    return $output;
}


// ----------------------------------------------------------------------
// 6. MAIN HTML STRUCTURE (Rendering based on variables set above)
// ----------------------------------------------------------------------
?>

<style>
    /* Styling for the module */
    .button-group { display: flex; justify-content: space-around; margin-top: 30px; gap: 10px; }
    .list-button {
        background-color: #3498db; color: white; padding: 15px 25px; border: none; border-radius: 8px;
        cursor: pointer; font-size: 16px; font-weight: bold; transition: background-color 0.3s, transform 0.1s;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); width: 30%; 
        text-align: center; 
        text-decoration: none; 
    }
    .list-button:hover { background-color: #2980b9; transform: translateY(-2px); }
    .action-button { padding: 8px 12px; border: none; border-radius: 5px; cursor: pointer; font-size: 14px; margin-right: 5px; text-decoration: none; display: inline-block; }
    .download-btn { background-color: #2ecc71; color: white; }
    .download-btn:hover { background-color: #27ae60; }
    .delete-btn { background-color: #e74c3c; color: white; }
    .delete-btn:hover { background-color: #c0392b; }
    .table-actions { display: flex; gap: 5px; justify-content: flex-start; }
    .data-table { margin-top: 15px !important; 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: #2c3e50; color: white; }
	.view-btn { background-color: #f39c12; color: white; }
	.view-btn:hover { background-color: #e67e22; }

</style>

<div class="form-card">
    <h3>Upload Confidential File</h3>
    <p>Upload a sensitive file and assign category for tracking.</p>
    
    <?php if (!empty($upload_message)) : ?>
	<script>
		window.addEventListener('DOMContentLoaded', function() {
			const msg = <?php echo json_encode(strip_tags($upload_message)); ?>;
			if (msg) alert(msg);
		});
	</script>
	<?php endif; ?>


    <form action="<?php echo $page_url_base; ?>" method="post" enctype="multipart/form-data">
        
        <label for="conf_file">Select File to Upload:</label>
		</br>
        <input type="file" name="conf_file" id="conf_file" required style="width: auto;">

        <label for="category">Document Category:</label>
        <select name="category" id="category" required>
            <option value="">-- Select Category --</option>
            <option value="Financial Documents" <?php echo ($current_category == 'Financial Documents' ? 'selected' : ''); ?>>Financial Documents</option>
            <option value="Investment Documents" <?php echo ($current_category == 'Investment Documents' ? 'selected' : ''); ?>>Investment Documents</option>
            <option value="Company Documents" <?php echo ($current_category == 'Company Documents' ? 'selected' : ''); ?>>Company Documents</option>
        </select>
        
        <button type="submit" name="upload_confidential">Upload & Record File</button>
    </form>
</div>

<!-- BUTTONS TO DISPLAY LISTS (GET Request) -->
<div class="button-group">
    <a href="<?php echo $page_url_base; ?>&list_category=Financial Documents" class="list-button">
        Financial Documents List
    </a>
    <a href="<?php echo $page_url_base; ?>&list_category=Investment Documents" class="list-button">
        Investment Document List
    </a>
    <a href="<?php echo $page_url_base; ?>&list_category=Company Documents" class="list-button">
        Company Documents List
    </a>
</div>

<!-- CONDITIONAL CONTENT AREA: File list is only rendered if $current_category is set -->
<?php if ($current_category): ?>
<div id="fileListContainer" class="form-card" style="margin-top: 20px;">
    <?php echo get_confidential_files_html($conn, $current_category, $page_url_base); ?>
</div>
<?php endif; ?>


<!-- Popup Viewer -->
<div id="filePreviewModal" style="
    display:none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
    background: rgba(0,0,0,0.7); justify-content: center; align-items: center; z-index: 9999;">
    <div style="
        background: white; padding: 20px; border-radius: 8px; max-width: 80%; max-height: 80%;
        overflow: auto; position: relative;">
        <button id="closePreview" style="
            position: absolute; top: 10px; right: 10px; background: #e74c3c; color: white;
            border: none; padding: 5px 10px; border-radius: 5px; cursor: pointer;">Close</button>
        <h3 id="previewTitle" style="margin-bottom: 10px; color:#2c3e50;"></h3>
        <div id="filePreviewContent" style="text-align:center;"></div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('filePreviewModal');
    const closeBtn = document.getElementById('closePreview');
    const content = document.getElementById('filePreviewContent');
    const title = document.getElementById('previewTitle');

    document.querySelectorAll('.view-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const filePath = this.dataset.filepath;
            const fileName = this.dataset.filename;
            title.textContent = fileName;

            let lowerPath = filePath.toLowerCase();

            // Reset content
            content.innerHTML = "";

            if (lowerPath.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i)) {
                // 🖼️ Image preview
                content.innerHTML = `<img src="${filePath}" alt="${fileName}" style="max-width:100%; height:auto; border:1px solid #ccc;">`;
            } 
            else if (lowerPath.match(/\.(pdf)$/i)) {
                // 📄 PDF preview
                content.innerHTML = `<iframe src="${filePath}" width="100%" height="500px" style="border:none;"></iframe>`;
            } 
            else if (lowerPath.match(/\.(doc|docx|ppt|pptx|xls|xlsx|xml)$/i)) {
                // 📑 Office or XML file preview using Google Docs Viewer
                const encodedURL = encodeURIComponent(window.location.origin + '/' + filePath.replace(/^\/+/, ''));
                const viewerURL = `https://docs.google.com/gview?url=${encodedURL}&embedded=true`;
                content.innerHTML = `<iframe src="${viewerURL}" width="100%" height="500px" style="border:none;"></iframe>`;
            } 
            else {
                // ❌ Unsupported type
                content.innerHTML = `<p>Preview not supported for this file type. You can download it instead.</p>`;
            }

            modal.style.display = 'flex';
        });
    });

    closeBtn.addEventListener('click', function() {
        modal.style.display = 'none';
        content.innerHTML = '';
    });

    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.style.display = 'none';
            content.innerHTML = '';
        }
    });

    // Optional: Close modal with ESC key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.style.display === 'flex') {
            modal.style.display = 'none';
            content.innerHTML = '';
        }
    });
});
</script>
