<?php
declare(strict_types=1);

// 顯示錯誤（開發階段）
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

session_start();

// 檢查 vendor 目錄是否存在
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
    die('
    <html>
    <head><meta charset="UTF-8"><title>錯誤</title></head>
    <body style="font-family: Arial; padding: 40px; background: #f5f5f5;">
        <div style="background: white; padding: 30px; border-radius: 8px; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #e74c3c;">❌ 缺少依賴套件</h2>
            <p>請先安裝 Composer 依賴：</p>
            <pre style="background: #f8f9fa; padding: 15px; border-radius: 4px; overflow-x: auto;">
# 下載 Composer
php -r "copy(\'https://getcomposer.org/installer\', \'composer-setup.php\');"
php composer-setup.php
rm composer-setup.php

# 安裝依賴
php composer.phar install --no-dev</pre>
            <p>安裝完成後重新載入此頁面。</p>
        </div>
    </body>
    </html>
    ');
}

// 自動載入 Composer 依賴
require_once __DIR__ . '/vendor/autoload.php';

use PhpOffice\PhpPresentation\PhpPresentation;
use PhpOffice\PhpPresentation\IOFactory;
use PhpOffice\PhpPresentation\Style\Color;
use PhpOffice\PhpPresentation\Style\Alignment;
use PhpOffice\PhpPresentation\DocumentLayout;

// 配置
const UPLOAD_DIR = __DIR__ . '/uploads/';
const OUTPUT_DIR = __DIR__ . '/outputs/';
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

// 確保目錄存在
foreach ([UPLOAD_DIR, OUTPUT_DIR] as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
}

$error = '';
$success = '';
$pptxFile = '';

// 處理檔案上傳
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['photos'])) {
    try {
        $photos = $_FILES['photos'];
        $uploadedFiles = [];
        
        // 驗證並上傳檔案
        for ($i = 0; $i < count($photos['name']); $i++) {
            if ($photos['error'][$i] !== UPLOAD_ERR_OK) {
                continue;
            }
            
            // 驗證檔案類型
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mimeType = finfo_file($finfo, $photos['tmp_name'][$i]);
            finfo_close($finfo);
            
            if (!in_array($mimeType, ALLOWED_TYPES)) {
                throw new Exception("不支援的檔案格式: {$photos['name'][$i]}");
            }
            
            // 驗證檔案大小
            if ($photos['size'][$i] > MAX_FILE_SIZE) {
                throw new Exception("檔案太大: {$photos['name'][$i]}");
            }
            
            // 生成安全的檔名
            $extension = pathinfo($photos['name'][$i], PATHINFO_EXTENSION);
            $filename = uniqid('photo_') . '.' . $extension;
            $filepath = UPLOAD_DIR . $filename;
            
            if (move_uploaded_file($photos['tmp_name'][$i], $filepath)) {
                $uploadedFiles[] = [
                    'path' => $filepath,
                    'filename' => $filename,
                    'original' => $photos['name'][$i]
                ];
            }
        }
        
        if (empty($uploadedFiles)) {
            throw new Exception('沒有成功上傳的檔案');
        }
        
        // 生成 PPTX
        $pptxFile = generatePPTX($uploadedFiles);
        $success = '成功生成 PPTX 檔案！';
        
        // 儲存到 session 以便翻譯功能使用
        $_SESSION['last_pptx'] = $pptxFile;
        
        // 清理上傳的照片
        foreach ($uploadedFiles as $file) {
            @unlink($file['path']);
        }
        
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

function generatePPTX(array $photos): string {
    $outputFile = OUTPUT_DIR . uniqid('presentation_') . '.pptx';
    
    // 創建簡報物件
    $presentation = new PhpPresentation();
    
    // 設定為 16:9 佈局
    $presentation->getLayout()->setCX(9144000, PhpPresentation\DocumentLayout::UNIT_EMU);
    $presentation->getLayout()->setCY(6858000, PhpPresentation\DocumentLayout::UNIT_EMU);    
    // 刪除預設的第一張投影片
    $presentation->removeSlideByIndex(0);
    
    $totalPhotos = count($photos);
    
    foreach ($photos as $index => $photo) {
        // 創建新投影片
        $slide = $presentation->createSlide();
        
        // 設定背景為白色
        $slide->getBackground()->setColor(new Color('FFFFFF'));
        
        // 獲取圖片資訊
        $imagePath = $photo['path'];
        list($imgWidth, $imgHeight) = getimagesize($imagePath);
        
        // 計算圖片在投影片上的尺寸（保持比例）
        // 投影片尺寸：16:9 = 960 x 540 (單位：點)
        $slideWidth = 960;
        $slideHeight = 540;
        $margin = 40;
        
        $maxWidth = $slideWidth - ($margin * 2);
        $maxHeight = $slideHeight - ($margin * 2) - 30; // 預留頁碼空間
        
        // 計算縮放比例
        $widthRatio = $maxWidth / $imgWidth;
        $heightRatio = $maxHeight / $imgHeight;
        $ratio = min($widthRatio, $heightRatio);
        
        $finalWidth = (int)($imgWidth * $ratio);
        $finalHeight = (int)($imgHeight * $ratio);
        
        // 居中定位
        $x = (int)(($slideWidth - $finalWidth) / 2);
        $y = (int)(($slideHeight - $finalHeight - 30) / 2);
        
        // 添加圖片
        $shape = $slide->createDrawingShape();
        $shape->setName('Photo ' . ($index + 1))
              ->setDescription('Uploaded photo')
              ->setPath($imagePath)
              ->setWidth($finalWidth)
              ->setHeight($finalHeight)
              ->setOffsetX($x)
              ->setOffsetY($y);
        
        // 添加頁碼
        $pageNumber = $slide->createRichTextShape();
        $pageNumber->setHeight(20)
                   ->setWidth(100)
                   ->setOffsetX($slideWidth - 120)
                   ->setOffsetY($slideHeight - 40);
        
        $textRun = $pageNumber->createTextRun(($index + 1) . ' / ' . $totalPhotos);
        $textRun->getFont()
                ->setSize(10)
                ->setColor(new Color('666666'));
        
        $pageNumber->getActiveParagraph()
                   ->getAlignment()
                   ->setHorizontal(Alignment::HORIZONTAL_RIGHT);
    }
    
    // 儲存 PPTX
    $writer = IOFactory::createWriter($presentation, 'PowerPoint2007');
    $writer->save($outputFile);
    
    return basename($outputFile);
}

?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>照片合併 PPTX 工具</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft JhengHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }
        .header h1 { font-size: 32px; margin-bottom: 10px; font-weight: 700; }
        .header p { font-size: 16px; opacity: 0.95; }
        .content { padding: 40px; }
        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .upload-zone {
            border: 3px dashed #667eea;
            border-radius: 12px;
            padding: 60px 20px;
            text-align: center;
            background: #f8f9ff;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upload-zone:hover { border-color: #764ba2; background: #f0f2ff; transform: translateY(-2px); }
        .upload-icon { font-size: 64px; margin-bottom: 20px; }
        .upload-zone h3 { font-size: 20px; color: #333; margin-bottom: 10px; }
        .upload-zone p { color: #666; font-size: 14px; }
        .file-input { display: none; }
        .btn {
            display: inline-block;
            padding: 14px 32px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6); }
        .btn:disabled { opacity: 0.6; cursor: not-allowed; }
        .btn-secondary { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
        .result-section {
            margin-top: 30px;
            padding: 30px;
            background: #f8f9ff;
            border-radius: 12px;
            text-align: center;
        }
        .button-group { display: flex; gap: 15px; justify-content: center; flex-wrap: wrap; }
        .file-info { margin: 15px 0; padding: 15px; background: white; border-radius: 8px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📸 照片合併 PPTX 工具</h1>
            <p>上傳多張照片，一鍵生成精美簡報</p>
        </div>
        <div class="content">
            <?php if ($error): ?>
                <div class="alert alert-error">❌ <?= htmlspecialchars($error) ?></div>
            <?php endif; ?>
            
            <?php if ($success && $pptxFile): ?>
                <div class="alert alert-success">✅ <?= htmlspecialchars($success) ?></div>
                <div class="result-section">
                    <h3>🎉 PPTX 檔案已生成</h3>
                    <div class="file-info">檔案名稱: <?= htmlspecialchars($pptxFile) ?></div>
                    <div class="button-group">
                        <a href="download.php?file=<?= urlencode($pptxFile) ?>" class="btn">⬇️ 下載 PPTX</a>
                        <a href="translate.php?file=<?= urlencode($pptxFile) ?>" class="btn btn-secondary">🌏 翻譯成繁體中文</a>
                    </div>
                </div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data" style="margin-top: 30px;">
                <label for="photos" class="upload-zone" id="uploadZone">
                    <div class="upload-icon">📁</div>
                    <h3>點擊上傳照片或拖曳檔案至此</h3>
                    <p>支援 JPG、PNG、GIF、WebP 格式，單檔最大 10MB</p>
                    <p style="margin-top: 10px; font-size: 12px; color: #999;">
                        已選擇 <span id="fileCount">0</span> 個檔案
                    </p>
                </label>
                <input type="file" id="photos" name="photos[]" class="file-input" accept="image/*" multiple required>
                <div style="text-align: center; margin-top: 20px;">
                    <button type="submit" class="btn" id="submitBtn" disabled>🚀 生成 PPTX</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        const fileInput = document.getElementById('photos');
        const uploadZone = document.getElementById('uploadZone');
        const fileCount = document.getElementById('fileCount');
        const submitBtn = document.getElementById('submitBtn');
        
        fileInput.addEventListener('change', function() {
            fileCount.textContent = this.files.length;
            submitBtn.disabled = this.files.length === 0;
        });
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(e => {
            uploadZone.addEventListener(e, ev => { ev.preventDefault(); ev.stopPropagation(); });
        });
        
        uploadZone.addEventListener('drop', function(e) {
            fileInput.files = e.dataTransfer.files;
            fileInput.dispatchEvent(new Event('change'));
        });
    </script>
</body>
</html>
