<?php
session_start();
require_once 'config.php';

// Check if user is logged in and is admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 1) {
    http_response_code(403);
    die('Unauthorized access');
}

$filename = $_GET['file'] ?? '';

if (empty($filename)) {
    http_response_code(400);
    die('No file specified');
}

// Security: Only allow files from reports directory
$reportsDir = 'reports/';
if (strpos($filename, $reportsDir) !== 0) {
    http_response_code(403);
    die('Invalid file path');
}

// Check if file exists
if (!file_exists($filename)) {
    http_response_code(404);
    die('File not found');
}

// Get file extension
$fileExtension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

if ($fileExtension === 'html') {
    // For HTML files, add print CSS and auto-print JavaScript
    $content = file_get_contents($filename);
    
    // Add print styles and auto-print script
    $printStyles = "
    <style media='print'>
        @page {
            margin: 0.5in;
            size: A4;
        }
        body {
            font-size: 12px;
            line-height: 1.4;
        }
        .no-print {
            display: none;
        }
        table {
            page-break-inside: auto;
        }
        tr {
            page-break-inside: avoid;
            page-break-after: auto;
        }
        .report-card {
            page-break-after: always;
        }
        .class-section {
            page-break-inside: avoid;
        }
    </style>
    <script>
        window.onload = function() {
            window.print();
            // Optional: Close window after printing
            setTimeout(function() {
                window.close();
            }, 1000);
        }
    </script>
    ";
    
    // Insert print styles and script before closing head tag
    $content = str_replace('</head>', $printStyles . '</head>', $content);
    
    // Set content type for HTML
    header('Content-Type: text/html; charset=UTF-8');
    
    // Output the modified HTML
    echo $content;
    
} else {
    // For other file types, just display them
    $contentType = 'application/octet-stream';
    
    switch ($fileExtension) {
        case 'pdf':
            $contentType = 'application/pdf';
            break;
        case 'xlsx':
            // Convert Excel to HTML for printing (would need additional library)
            echo '<p>Excel files cannot be directly printed. Please download and print using Excel.</p>';
            echo '<script>setTimeout(function() { window.close(); }, 3000);</script>';
            exit;
    }
    
    header('Content-Type: ' . $contentType);
    header('Content-Disposition: inline; filename="' . basename($filename) . '"');
    
    readfile($filename);
}
exit;
?>