<?php 
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Security check for PDF file
if (!isset($_GET['file']) || empty($_GET['file'])) {
    die('<div class="alert alert-danger m-3">No PDF selected</div>');
}

$filename = basename($_GET['file']);
$pdf_path = 'pdfs/' . $filename;

// Check if file exists
if (!file_exists($pdf_path)) {
    die('<div class="alert alert-danger m-3">PDF file not found: ' . htmlspecialchars($filename) . '</div>');
}

// Allowed PDF files (security check)
$allowed_files = ['P1.pdf', 'P2.pdf', 'P3.pdf'];
if (!in_array($filename, $allowed_files)) {
    die('<div class="alert alert-danger m-3">Access denied for this file</div>');
}

// Check if download action is requested
if (isset($_GET['action']) && $_GET['action'] == 'download') {
    // Force download
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($pdf_path));
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Expires: 0');
    
    // Clear output buffer
    ob_clean();
    flush();
    
    // Read and output the file
    readfile($pdf_path);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View PDF - Rotomax Electric</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f8f9fa;
        }
        
        .pdf-header {
            background: linear-gradient(135deg, #0d6efd 0%, #0b5ed7 100%);
            color: white;
            padding: 15px 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        
        .pdf-container {
            width: 100%;
            height: calc(100vh - 70px);
            border: none;
            background: white;
        }
        
        .btn-custom {
            padding: 8px 20px;
            font-weight: 500;
            border-radius: 6px;
            transition: all 0.3s ease;
        }
        
        .btn-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .btn-download {
            background: #28a745;
            border-color: #28a745;
            color: white;
        }
        
        .btn-download:hover {
            background: #218838;
            border-color: #1e7e34;
            color: white;
        }
        
        .btn-back {
            background: transparent;
            border: 1px solid rgba(255,255,255,0.5);
        }
        
        .btn-back:hover {
            background: rgba(255,255,255,0.1);
        }
        
        .file-info {
            background: rgba(255,255,255,0.1);
            padding: 5px 15px;
            border-radius: 4px;
            font-size: 0.9em;
        }
        
        /* Print button styling */
        .print-btn {
            background: #ffc107;
            border-color: #ffc107;
            color: #212529;
        }
        
        .print-btn:hover {
            background: #e0a800;
            border-color: #d39e00;
            color: #212529;
        }
        
        /* Loading animation */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
        }
        
        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #0d6efd;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>

<!-- PDF Viewer Header -->
<div class="pdf-header">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h4 class="mb-0">
                    <i class="fas fa-file-pdf me-2"></i>
                    <?php echo htmlspecialchars($filename); ?>
                </h4>
                <div class="file-info d-inline-block mt-1">
                    <i class="fas fa-info-circle me-1"></i>
                    <?php echo round(filesize($pdf_path) / 1024, 2); ?> KB
                </div>
            </div>
            
            <div class="d-flex gap-2">
                <!-- Print Button -->
                <button onclick="printPDF()" class="btn print-btn btn-custom">
                    <i class="fas fa-print me-1"></i> Print
                </button>
                
                <!-- Download Button -->
                <a href="pdf-view.php?file=<?php echo urlencode($filename); ?>&action=download" 
                   class="btn btn-download btn-custom">
                    <i class="fas fa-download me-1"></i> Download PDF
                </a>
                
                <!-- Back Button -->
                <a href="d63-series-pmdc-motors.php" 
                   class="btn btn-back btn-custom">
                    <i class="fas fa-arrow-left me-1"></i> Back
                </a>
            </div>
        </div>
    </div>
</div>

<!-- PDF Viewer -->
<div class="position-relative">
    <!-- Loading indicator -->
    <div id="loading" class="loading">
        <div class="spinner"></div>
        <span class="ms-3">Loading PDF...</span>
    </div>
    
    <!-- PDF Iframe -->
    <iframe id="pdfFrame" 
            src="<?php echo $pdf_path; ?>#toolbar=1&navpanes=1&scrollbar=1&view=FitH" 
            class="pdf-container"
            title="PDF Viewer - <?php echo htmlspecialchars($filename); ?>"
            onload="hideLoading()"
            style="display: none;">
    </iframe>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Hide loading indicator when PDF is loaded
function hideLoading() {
    document.getElementById('loading').style.display = 'none';
    document.getElementById('pdfFrame').style.display = 'block';
}

// Print PDF function
function printPDF() {
    const pdfFrame = document.getElementById('pdfFrame');
    if (pdfFrame.contentWindow) {
        pdfFrame.contentWindow.print();
    } else {
        // Fallback: open PDF in new window for printing
        window.open("<?php echo $pdf_path; ?>", "_blank");
    }
}

// Add keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl+P or Cmd+P for print
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        printPDF();
    }
    
    // Ctrl+S or Cmd+S for save/download
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        // Trigger download
        window.location.href = "pdf-view.php?file=<?php echo urlencode($filename); ?>&action=download";
    }
    
    // Escape key to go back
    if (e.key === 'Escape') {
        window.location.href = "d63-series-pmdc-motors.php";
    }
});

// Show loading indicator if PDF takes time to load
setTimeout(function() {
    const loading = document.getElementById('loading');
    const pdfFrame = document.getElementById('pdfFrame');
    
    if (pdfFrame.style.display === 'none') {
        loading.innerHTML = '<div class="spinner"></div><span class="ms-3">Still loading... Please wait</span>';
    }
}, 3000);

// Show file info in console for debugging
console.log("PDF File: <?php echo $filename; ?>");
console.log("File Path: <?php echo $pdf_path; ?>");
console.log("File Size: <?php echo filesize($pdf_path); ?> bytes");
</script>

</body>
</html>