<?php
/**
 * PDF to Image Converter
 * Converts PDF pages to high-quality JPG images for the viewer
 */

class PDFConverter {
    private $pdfDir = 'pdf/';
    private $cacheDir = 'pdf/cache/';
    private $quality = 95; // High quality (0-100)
    private $dpi = 150; // DPI for rendering (higher = better quality)
    
    public function __construct() {
        // Create cache directory if it doesn't exist
        if (!file_exists($this->cacheDir)) {
            mkdir($this->cacheDir, 0755, true);
        }
    }
    
    /**
     * Convert PDF to images using ImageMagick
     */
    public function convertPDF($pdfFile) {
        $pdfPath = $this->pdfDir . $pdfFile;
        
        if (!file_exists($pdfPath)) {
            return ['error' => 'PDF file not found'];
        }
        
        // Get PDF page count
        $pageCount = $this->getPageCount($pdfPath);
        
        // Generate cache filename base
        $cacheBase = $this->cacheDir . pathinfo($pdfFile, PATHINFO_FILENAME);
        
        $images = [];
        
        // Convert each page
        for ($i = 0; $i < $pageCount; $i++) {
            $imageFile = $cacheBase . '_page_' . ($i + 1) . '.jpg';
            
            // Check if image already exists
            if (!file_exists($imageFile)) {
                // Convert using ImageMagick
                $command = sprintf(
                    'convert -density %d -quality %d "%s[%d]" -flatten "%s" 2>&1',
                    $this->dpi,
                    $this->quality,
                    $pdfPath,
                    $i,
                    $imageFile
                );
                
                exec($command, $output, $returnCode);
                
                if ($returnCode !== 0) {
                    // Try Ghostscript as fallback
                    $this->convertWithGhostscript($pdfPath, $i, $imageFile);
                }
            }
            
            if (file_exists($imageFile)) {
                // Use forward slashes for web URLs
                $webUrl = str_replace('\\', '/', $imageFile);
                $images[] = [
                    'page' => $i + 1,
                    'url' => $webUrl,
                    'size' => filesize($imageFile)
                ];
            }
        }
        
        return [
            'pdf' => $pdfFile,
            'totalPages' => $pageCount,
            'images' => $images
        ];
    }
    
    /**
     * Fallback: Convert using Ghostscript
     */
    private function convertWithGhostscript($pdfPath, $pageNum, $outputFile) {
        $command = sprintf(
            'gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -dJPEGQ=%d -r%d -dFirstPage=%d -dLastPage=%d -sOutputFile="%s" "%s" 2>&1',
            $this->quality,
            $this->dpi,
            $pageNum + 1,
            $pageNum + 1,
            $outputFile,
            $pdfPath
        );
        
        exec($command, $output, $returnCode);
        return $returnCode === 0;
    }
    
    /**
     * Get PDF page count
     */
    private function getPageCount($pdfPath) {
        // Try with pdfinfo
        exec("pdfinfo \"$pdfPath\" 2>&1 | grep Pages", $output);
        if (!empty($output)) {
            preg_match('/Pages:\s+(\d+)/', $output[0], $matches);
            if (isset($matches[1])) {
                return (int)$matches[1];
            }
        }
        
        // Fallback: Try with identify
        exec("identify -format '%n\n' \"$pdfPath\" 2>&1", $output);
        if (!empty($output)) {
            return (int)$output[0];
        }
        
        // Default fallback
        return 1;
    }
    
    /**
     * Get all available PDFs
     */
    public function getAvailablePDFs() {
        $pdfs = glob($this->pdfDir . '*.pdf');
        return array_map('basename', $pdfs);
    }
    
    /**
     * Get all existing JPG/JPEG images directly in the PDF folder
     */
    public function getExistingImages() {
        $jpgImages = glob($this->pdfDir . '*.jpg');
        $jpegImages = glob($this->pdfDir . '*.jpeg');
        $allImages = array_merge($jpgImages, $jpegImages);
        
        // Exclude cache directory
        $result = [];
        foreach ($allImages as $image) {
            // Skip if it's in the cache directory
            if (strpos($image, $this->cacheDir) === false) {
                // Use forward slashes for web URLs
                $webUrl = str_replace('\\', '/', $image);
                $result[] = [
                    'page' => count($result) + 1,
                    'url' => $webUrl,
                    'size' => filesize($image),
                    'name' => basename($image)
                ];
            }
        }
        
        // Sort by filename to maintain order
        usort($result, function($a, $b) {
            return strcmp($a['url'], $b['url']);
        });
        
        return $result;
    }
    
    /**
     * Get cached images for a PDF
     */
    public function getCachedImages($pdfFile) {
        $cacheBase = $this->cacheDir . pathinfo($pdfFile, PATHINFO_FILENAME);
        $images = glob($cacheBase . '_page_*.jpg');
        
        if (empty($images)) {
            // Not cached yet, convert now
            return $this->convertPDF($pdfFile);
        }
        
        $result = [];
        foreach ($images as $image) {
            preg_match('/_page_(\d+)\.jpg$/', $image, $matches);
            // Use forward slashes for web URLs
            $webUrl = str_replace('\\', '/', $image);
            $result[] = [
                'page' => (int)$matches[1],
                'url' => $webUrl,
                'size' => filesize($image)
            ];
        }
        
        // Sort by page number
        usort($result, function($a, $b) {
            return $a['page'] - $b['page'];
        });
        
        return [
            'pdf' => $pdfFile,
            'totalPages' => count($result),
            'images' => $result
        ];
    }
}

// API endpoint
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    
    $converter = new PDFConverter();
    
    switch ($_GET['action']) {
        case 'list':
            // Get all PDFs and their cached images
            $pdfFiles = $converter->getAvailablePDFs();
            $result = [
                'success' => true,
                'pdfs' => []
            ];
            
            foreach ($pdfFiles as $pdfFile) {
                $cached = $converter->getCachedImages($pdfFile);
                if (isset($cached['images']) && !empty($cached['images'])) {
                    $result['pdfs'][] = [
                        'pdf' => $pdfFile,
                        'totalPages' => $cached['totalPages'],
                        'pages' => $cached['images']
                    ];
                }
            }
            
            // Also get existing JPG/JPEG images directly in the pdf folder
            $existingImages = $converter->getExistingImages();
            if (!empty($existingImages)) {
                $result['pdfs'][] = [
                    'pdf' => 'existing_images',
                    'totalPages' => count($existingImages),
                    'pages' => $existingImages
                ];
            }
            
            echo json_encode($result);
            break;
            
        case 'convert':
            if (isset($_GET['pdf'])) {
                echo json_encode($converter->convertPDF($_GET['pdf']));
            } else {
                echo json_encode(['error' => 'PDF filename required']);
            }
            break;
            
        case 'get':
            if (isset($_GET['pdf'])) {
                echo json_encode($converter->getCachedImages($_GET['pdf']));
            } else {
                echo json_encode(['error' => 'PDF filename required']);
            }
            break;
            
        default:
            echo json_encode(['error' => 'Invalid action']);
    }
    exit;
}
?>

