<?php
// pdf-to-word.php
$page_title = 'PDF en Word - PDFMaster';

define('UPLOAD_DIR', __DIR__ . '/uploads/');
define('OUTPUT_DIR', __DIR__ . '/outputs/');
define('MAX_FILE_SIZE', 50 * 1024 * 1024);

if (!is_dir(UPLOAD_DIR)) mkdir(UPLOAD_DIR, 0755, true);
if (!is_dir(OUTPUT_DIR)) mkdir(OUTPUT_DIR, 0755, true);

// === TRAITEMENT AJAX ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['pdf_file'])) {
    header('Content-Type: application/json');
    $file = $_FILES['pdf_file'];
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'error' => 'Erreur d\'upload (code: ' . $file['error'] . ')']);
        exit();
    }
    
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if ($mime !== 'application/pdf') {
        echo json_encode(['success' => false, 'error' => 'Le fichier doit être au format PDF']);
        exit();
    }
    
    if ($file['size'] > MAX_FILE_SIZE) {
        echo json_encode(['success' => false, 'error' => 'Le fichier dépasse 50 Mo']);
        exit();
    }
    
    $unique_id = uniqid('pdf_', true);
    $pdf_path = UPLOAD_DIR . $unique_id . '.pdf';
    $docx_path = OUTPUT_DIR . $unique_id . '.docx';
    
    if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
        echo json_encode(['success' => false, 'error' => 'Impossible de sauvegarder le fichier']);
        exit();
    }
    
    // Conversion LibreOffice
    function convertWithLibreOffice($pdf_path, $docx_path) {
        $libreoffice_cmd = null;
        $possible_commands = ['libreoffice', 'soffice', '/usr/bin/libreoffice', '/usr/bin/soffice', '/usr/bin/lowriter'];
        
        foreach ($possible_commands as $cmd) {
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                $win_paths = [
                    'C:\Program Files\LibreOffice\program\soffice.exe',
                    'C:\Program Files (x86)\LibreOffice\program\soffice.exe'
                ];
                foreach ($win_paths as $wp) {
                    if (file_exists($wp)) { $libreoffice_cmd = '"' . $wp . '"'; break 2; }
                }
            } else {
                $output = []; $return_var = 0;
                exec("which " . escapeshellarg($cmd) . " 2>/dev/null", $output, $return_var);
                if ($return_var === 0) { $libreoffice_cmd = $cmd; break; }
            }
        }
        
        if (!$libreoffice_cmd) return ['success' => false, 'error' => 'LibreOffice n\'est pas installé'];
        
        $output_dir = dirname($docx_path);
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $command = sprintf('%s --headless --convert-to docx --outdir "%s" "%s" 2>&1', $libreoffice_cmd, $output_dir, $pdf_path);
        } else {
            $command = sprintf('%s --headless --convert-to docx --outdir %s %s 2>&1', escapeshellcmd($libreoffice_cmd), escapeshellarg($output_dir), escapeshellarg($pdf_path));
        }
        
        $output = []; $return_var = 0;
        exec($command, $output, $return_var);
        
        $generated_file = $output_dir . '/' . basename($pdf_path, '.pdf') . '.docx';
        if (file_exists($generated_file)) {
            rename($generated_file, $docx_path);
            return ['success' => true, 'file' => $docx_path];
        }
        return ['success' => false, 'error' => 'Échec', 'debug' => implode("\n", $output)];
    }
    
    $result = convertWithLibreOffice($pdf_path, $docx_path);
    
    if ($result['success'] && file_exists($result['file'])) {
        $original_name = pathinfo($file['name'], PATHINFO_FILENAME);
        $download_name = $original_name . '_converted.docx';
        $final_docx_path = OUTPUT_DIR . $unique_id . '_' . $download_name;
        copy($result['file'], $final_docx_path);
        
        echo json_encode([
            'success' => true,
            'download_url' => '?download=' . urlencode(basename($final_docx_path)),
            'filename' => $download_name
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => $result['error'] ?? 'Échec', 'debug' => $result['debug'] ?? null]);
    }
    exit();
}

// === TÉLÉCHARGEMENT ===
if (isset($_GET['download'])) {
    $filename = basename($_GET['download']);
    $filepath = OUTPUT_DIR . $filename;
    if (!file_exists($filepath)) { http_response_code(404); die('Fichier introuvable'); }
    
    header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($filepath));
    readfile($filepath);
    exit();
}

include_once 'includes/header.php';
?>

<main class="py-12 lg:py-20">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <!-- Fil d'ariane -->
        <nav class="mb-6 text-sm text-slate-600">
            <a href="index.php" class="hover:text-blue-600">Accueil</a>
            <span class="mx-2">/</span>
            <span class="text-slate-900 font-medium">PDF en Word</span>
        </nav>
        
        <div class="text-center mb-10 slide-up">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-blue-500 to-blue-700 rounded-2xl mb-4 shadow-lg shadow-blue-500/30">
                <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                </svg>
            </div>
            <h1 class="text-4xl lg:text-5xl font-bold text-slate-900 mb-4">
                Convertir <span class="text-blue-600">PDF en Word</span>
            </h1>
            <p class="text-lg text-slate-600 max-w-2xl mx-auto">
                Transformez vos fichiers PDF en documents Word éditables en quelques secondes.
            </p>
        </div>

        <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-8 lg:p-12">
            
            <!-- État initial : Upload -->
            <div id="upload-state">
                <div class="border-2 border-dashed border-slate-300 rounded-xl p-12 text-center transition-all duration-300 hover:border-blue-400" id="drop-zone">
                    <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg class="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
                        </svg>
                    </div>
                    <h3 class="text-xl font-semibold text-slate-900 mb-2">Glissez-déposez votre PDF ici</h3>
                    <p class="text-slate-600 mb-6">ou</p>
                    <button class="bg-blue-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors shadow-sm" onclick="document.getElementById('file-input').click()">
                        Sélectionner un fichier PDF
                    </button>
                    <input type="file" id="file-input" class="hidden" accept=".pdf,application/pdf" onchange="handleFileSelect(event)">
                    <p class="text-xs text-slate-500 mt-4">Format PDF uniquement • Taille maximale : 50 Mo</p>
                </div>
            </div>

            <!-- État : Fichier sélectionné -->
            <div id="file-selected-state" class="hidden">
                <div class="flex items-center justify-between bg-slate-50 p-4 rounded-lg border border-slate-200">
                    <div class="flex items-center space-x-3">
                        <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                            <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                            </svg>
                        </div>
                        <div>
                            <p id="file-name" class="font-medium text-slate-900 text-sm">nom_du_fichier.pdf</p>
                            <p id="file-size" class="text-xs text-slate-500">0 Mo</p>
                        </div>
                    </div>
                    <button class="text-slate-400 hover:text-red-600 transition-colors" onclick="resetUpload()">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                    </button>
                </div>
                <div class="mt-6 flex justify-center space-x-4">
                    <button class="text-slate-600 hover:text-slate-900 font-medium transition-colors px-6 py-3" onclick="resetUpload()">Annuler</button>
                    <button id="convert-btn" class="bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors shadow-sm" onclick="startConversion()">Convertir en Word</button>
                </div>
            </div>

            <!-- État : Traitement -->
            <div id="processing-state" class="hidden">
                <div class="text-center py-8">
                    <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4 animate-pulse">
                        <svg class="w-8 h-8 text-blue-600 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                        </svg>
                    </div>
                    <h3 class="text-xl font-semibold text-slate-900 mb-4">Conversion en cours...</h3>
                    <div class="w-full bg-slate-200 rounded-full h-3 mb-2 max-w-md mx-auto">
                        <div id="progress-bar" class="bg-blue-600 h-3 rounded-full progress-bar-fill" style="width: 0%"></div>
                    </div>
                    <p id="progress-text" class="text-sm text-slate-600">0%</p>
                </div>
            </div>

            <!-- État : Succès -->
            <div id="success-state" class="hidden">
                <div class="text-center py-8">
                    <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg class="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                    </div>
                    <h3 class="text-2xl font-semibold text-slate-900 mb-2">Conversion réussie !</h3>
                    <p class="text-slate-600 mb-6">Votre fichier Word est prêt à être téléchargé</p>
                    <div class="flex justify-center space-x-4">
                        <button class="border border-slate-300 text-slate-700 px-6 py-3 rounded-lg font-semibold hover:bg-slate-50 transition-colors" onclick="resetUpload()">Nouveau fichier</button>
                        <a id="download-link" href="#" class="bg-green-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-green-700 transition-colors shadow-sm inline-flex items-center">
                            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                            Télécharger
                        </a>
                    </div>
                </div>
            </div>

            <!-- État : Erreur -->
            <div id="error-state" class="hidden">
                <div class="text-center py-8">
                    <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg class="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                    </div>
                    <h3 class="text-2xl font-semibold text-slate-900 mb-2">Erreur de conversion</h3>
                    <p id="error-message" class="text-slate-600 mb-6">Une erreur est survenue</p>
                    <div id="error-debug" class="text-left bg-slate-100 p-4 rounded-lg mb-6 text-sm text-slate-700 hidden">
                        <strong>Détails techniques :</strong>
                        <pre id="error-debug-text" class="mt-2 whitespace-pre-wrap"></pre>
                    </div>
                    <button class="bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors shadow-sm" onclick="resetUpload()">Réessayer</button>
                </div>
            </div>

        </div>

        <!-- Autres outils -->
        <div class="mt-12">
            <h3 class="text-xl font-bold text-slate-900 mb-6 text-center">Vous pourriez aussi avoir besoin de</h3>
            <div class="grid sm:grid-cols-3 gap-4">
                <a href="compress.php" class="bg-white p-5 rounded-xl border border-slate-200 hover:border-green-500 hover:shadow-md transition-all flex items-center space-x-3">
                    <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0">
                        <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path></svg>
                    </div>
                    <div>
                        <div class="font-semibold text-slate-900 text-sm">Compresser PDF</div>
                        <div class="text-xs text-slate-500">Réduire la taille</div>
                    </div>
                </a>
                <a href="merge.php" class="bg-white p-5 rounded-xl border border-slate-200 hover:border-purple-500 hover:shadow-md transition-all flex items-center space-x-3">
                    <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center flex-shrink-0">
                        <svg class="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path></svg>
                    </div>
                    <div>
                        <div class="font-semibold text-slate-900 text-sm">Fusionner PDF</div>
                        <div class="text-xs text-slate-500">Combiner plusieurs</div>
                    </div>
                </a>
                <a href="split.php" class="bg-white p-5 rounded-xl border border-slate-200 hover:border-orange-500 hover:shadow-md transition-all flex items-center space-x-3">
                    <div class="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center flex-shrink-0">
                        <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.121 14.121L19 19m-7-7l7-7m-7 7l-2.879 2.879M12 12L9.121 9.121m0 5.758a3 3 0 10-4.243 4.243 3 3 0 004.243-4.243zm0-5.758a3 3 0 10-4.243-4.243 3 3 0 004.243 4.243z"></path></svg>
                    </div>
                    <div>
                        <div class="font-semibold text-slate-900 text-sm">Diviser PDF</div>
                        <div class="text-xs text-slate-500">Extraire des pages</div>
                    </div>
                </a>
            </div>
        </div>

    </div>
</main>

<script>
    let selectedFile = null;
    const dropZone = document.getElementById('drop-zone');
    const fileInput = document.getElementById('file-input');

    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, (e) => { e.preventDefault(); e.stopPropagation(); dropZone.classList.add('drop-zone-active'); });
    });
    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, (e) => { e.preventDefault(); e.stopPropagation(); dropZone.classList.remove('drop-zone-active'); });
    });
    dropZone.addEventListener('drop', (e) => {
        const files = e.dataTransfer.files;
        if (files.length > 0) handleFile(files[0]);
    });

    function handleFileSelect(event) {
        if (event.target.files.length > 0) handleFile(event.target.files[0]);
    }

    function handleFile(file) {
        if (file.type !== 'application/pdf') { showError('Veuillez sélectionner un fichier PDF valide.'); return; }
        if (file.size > 50 * 1024 * 1024) { showError('Le fichier dépasse la taille maximale de 50 Mo.'); return; }
        selectedFile = file;
        document.getElementById('file-name').textContent = file.name;
        document.getElementById('file-size').textContent = (file.size / 1024 / 1024).toFixed(2) + ' Mo';
        showState('file-selected-state');
    }

    function resetUpload() {
        selectedFile = null;
        fileInput.value = '';
        showState('upload-state');
    }

    function showState(stateId) {
        ['upload-state', 'file-selected-state', 'processing-state', 'success-state', 'error-state'].forEach(id => {
            document.getElementById(id).classList.add('hidden');
        });
        document.getElementById(stateId).classList.remove('hidden');
    }

    async function startConversion() {
        if (!selectedFile) { showError('Aucun fichier sélectionné'); return; }
        showState('processing-state');
        let progress = 0;
        const progressBar = document.getElementById('progress-bar');
        const progressText = document.getElementById('progress-text');
        const progressInterval = setInterval(() => {
            progress += Math.random() * 10;
            if (progress > 90) progress = 90;
            progressBar.style.width = progress + '%';
            progressText.textContent = Math.round(progress) + '%';
        }, 300);

        const formData = new FormData();
        formData.append('pdf_file', selectedFile);

        try {
            const response = await fetch(window.location.href, { method: 'POST', body: formData });
            const result = await response.json();
            clearInterval(progressInterval);
            progressBar.style.width = '100%';
            progressText.textContent = '100%';
            setTimeout(() => {
                if (result.success) {
                    document.getElementById('download-link').href = result.download_url;
                    showState('success-state');
                } else {
                    let errorMsg = result.error || 'Une erreur est survenue';
                    if (result.debug) {
                        document.getElementById('error-debug').classList.remove('hidden');
                        document.getElementById('error-debug-text').textContent = result.debug;
                    }
                    showError(errorMsg);
                }
            }, 500);
        } catch (error) {
            clearInterval(progressInterval);
            showError('Erreur de communication : ' + error.message);
        }
    }

    function showError(message) {
        document.getElementById('error-message').textContent = message;
        showState('error-state');
    }
</script>

<?php include_once 'includes/footer.php'; ?>