<?php
session_start();
include "../include/config.php";

if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit();
}

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $note_id = intval($_GET['id']);
    $program = $_SESSION['program'];
    
    $query = "SELECT * FROM notes WHERE id = '$note_id' ";
    $result = mysqli_query($conn, $query);
    
    if (mysqli_num_rows($result) > 0) {
        $note = mysqli_fetch_assoc($result);
        $file_name = $note['doc']; // Get the filename from 'doc' column
        $file_path = "../../staff/staff/" . $file_name; // Construct the correct path
        
        // Debug: Check if file exists
        if (!file_exists($file_path)) {
            error_log("File not found: " . $file_path);
            header("Location: notes.php?error=File not found: " . $file_name);
            exit();
        }
        
        if (file_exists($file_path) && is_readable($file_path)) {
            // Get file information
            $file_size = filesize($file_path);
            $file_extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
            
            // Set appropriate Content-Type based on file extension
            $content_types = [
                'pdf' => 'application/pdf',
                'doc' => 'application/msword',
                'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'txt' => 'text/plain',
                'jpg' => 'image/jpeg',
                'jpeg' => 'image/jpeg',
                'png' => 'image/png',
                'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                'zip' => 'application/zip'
            ];
            
            $content_type = $content_types[$file_extension] ?? 'application/octet-stream';
            
            // Set headers for download
            header('Content-Description: File Transfer');
            header('Content-Type: ' . $content_type);
            header('Content-Disposition: attachment; filename="' . $file_name . '"');
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . $file_size);
            
            // Clear output buffer
            ob_clean();
            flush();
            
            // Read the file
            readfile($file_path);
            exit();
        } else {
            header("Location: notes.php?error=File not found or not accessible: " . $file_name);
            exit();
        }
    } else {
        header("Location: notes.php?error=Note not found or access denied");
        exit();
    }
} else {
    header("Location: notes.php");
    exit();
}
?>