<?php
// This script assumes it is included in admin_dashboard.php, 
// so the $conn object (database connection) and $_SESSION data are already available.

$upload_message = '';
$upload_dir = 'uploads/confidential/'; // The relative path on your XAMPP server
$user_id = $_SESSION['user_id'] ?? 1; // Default to ID 1 if session ID is missing

// 1. Ensure the upload directory exists and is writable
if (!is_dir($upload_dir)) {
    // Attempt to create the directory recursively
    if (!mkdir($upload_dir, 0777, true)) {
        $upload_message = "<p style='color:red;'>ERROR: Could not create upload directory: {$upload_dir}. Check server permissions.</p>";
    }
}

// 2. Handle the form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['upload_confidential'])) {
    // Basic validation
    if (empty($_FILES['conf_file']['name']) || $_FILES['conf_file']['error'] !== 0) {
        $upload_message = "<p style='color:red;'>Please select a file to upload or an upload error occurred.</p>";
    } else {
        // Sanitize and prepare data
        $category = $conn->real_escape_string($_POST['category']);
        $file_name_original = $conn->real_escape_string($_FILES['conf_file']['name']);
        $file_info = pathinfo($file_name_original);
        $file_ext = strtolower($file_info['extension']);
        
        // Create a unique filename to prevent filename collisions
        $new_file_name = uniqid('conf_', true) . '.' . $file_ext;
        $target_file = $upload_dir . $new_file_name;
        $file_path_db = $target_file; 

        // 3. Move the uploaded file
        if (move_uploaded_file($_FILES['conf_file']['tmp_name'], $target_file)) {
            
            // 4. Insert metadata into the database using a prepared statement
            $sql = "INSERT INTO confidential_files (file_name, file_path, category, uploaded_by) 
                    VALUES (?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            
            if ($stmt === false) {
                 $upload_message = "<p style='color:red;'>Database prepare error: " . $conn->error . "</p>";
            } else {
                $stmt->bind_param("sssi", $file_name_original, $file_path_db, $category, $user_id);
            
                if ($stmt->execute()) {
                    $upload_message = "<p style='color:green;'>File <b>{$file_name_original}</b> uploaded and successfully recorded under <b>{$category}</b>.</p>";
                } else {
                    $upload_message = "<p style='color:red;'>Database insert failed: " . $stmt->error . "</p>";
                    // Clean up: delete the file if the database record failed
                    unlink($target_file);
                }
                $stmt->close();
            }

        } else {
            // Error moving file (usually a permissions issue)
            $upload_message = "<p style='color:red;'>Error moving file to secure directory. Check folder permissions (should be 0777).</p>";
        }
    }
}
?>

<div class="form-card">
    <h3>Upload Confidential File</h3>
    <p>Upload a sensitive file and assign category for tracking.</p>
    
    <?php echo $upload_message; // Display success or error messages ?>

    <!-- The form MUST include enctype="multipart/form-data" for file uploads -->
    <form action="admin_dashboard.php?page=upload_confidential" method="post" enctype="multipart/form-data">
        
        <label for="conf_file">Select File to Upload:</label>
		</br>
        <!-- The file input field -->
        <input type="file" name="conf_file" id="conf_file" required style="width: auto;">

        <label for="category">Document Category:</label>
        <!-- The required category dropdown -->
        <select name="category" id="category" required>
            <option value="">-- Select Category --</option>
            <option value="Financial Documents">Financial Documents</option>
            <option value="Investment Documents">Investment Documents</option>
            <option value="Company Documents">Company Documents</option>
        </select>
        
        <button type="submit" name="upload_confidential">Upload & Record File</button>
    </form>
</div>
