<?php
// api-upload.php

/**
 * Suppression récursive d’un dossier
 */
function wpvg_rrmdir($dir) {
    if (!is_dir($dir)) {
        return;
    }

    $items = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($items as $item) {
        if ($item->isDir()) {
            rmdir($item->getRealPath());
        } else {
            unlink($item->getRealPath());
        }
    }

    rmdir($dir);
}

/**
 * Handler principal : upload + extraction + écrasement
 */
function wpvg_upload_vcard() {

    if (empty($_FILES['file']) || empty($_FILES['file']['tmp_name'])) {
        wp_send_json([
            'success' => false,
            'error'   => 'Aucun fichier reçu'
        ]);
    }

    // Email utilisateur
    $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
    if (empty($email) || !is_email($email)) {
        wp_send_json([
            'success' => false,
            'error'   => 'Adresse email invalide'
        ]);
    }

    // ID vCard (slug final)
    $vcard_id = isset($_POST['vcardId']) ? sanitize_title($_POST['vcardId']) : '';
    if (empty($vcard_id)) {
        $vcard_id = 'vcard-' . wp_generate_password(8, false);
    }

    // Token de validation
    $token = wp_generate_password(20, false, false);

    // Dossier pending : /vcards/pending/{token}/
    $vcards_root = trailingslashit(ABSPATH) . 'vcards/';
    $pending_dir = $vcards_root . 'pending/' . $token . '/';

    if (is_dir($pending_dir)) {
        wpvg_rrmdir($pending_dir);
    }

    if (!wp_mkdir_p($pending_dir)) {
        wp_send_json([
            'success' => false,
            'error'   => 'Impossible de créer le dossier pending'
        ]);
    }

    // ZIP final dans pending
    $zip_path = $pending_dir . $vcard_id . '.zip';

    if (!move_uploaded_file($_FILES['file']['tmp_name'], $zip_path)) {
        wp_send_json([
            'success' => false,
            'error'   => 'Impossible de déplacer le fichier'
        ]);
    }

    // 1) Extraction du ZIP dans pending/
    if (class_exists('ZipArchive')) {
        $zip = new ZipArchive();
        if ($zip->open($zip_path) === true) {
            $zip->extractTo($pending_dir);
            $zip->close();
        }
    }

// ------------------------------------------------------
// MINIATURES VIDÉO POUR LE MODE ZIP (offline)
// ------------------------------------------------------
$vcard_extract_dir = $pending_dir;

// On cherche le JSON de sauvegarde
$saved_json = null;
foreach (glob($vcard_extract_dir . '*.json') as $json_file) {
    $saved_json = $json_file;
    break;
}

$providers     = ['youtube', 'vimeo'];
$vcards_root   = trailingslashit(ABSPATH) . 'vcards/';
$allowedThumbs = [];

if ($saved_json && file_exists($saved_json)) {

    $data = json_decode(file_get_contents($saved_json), true);

    // Liste des miniatures attendues pour CETTE vCard
    if (isset($data['featuredItems']) && is_array($data['featuredItems'])) {
        foreach ($data['featuredItems'] as $item) {

            if (empty($item['type']) || empty($item['url']) || empty($item['id'])) continue;
            if ($item['type'] !== 'youtube' && $item['type'] !== 'vimeo') continue;

            // Extraction ID vidéo
            $videoId = null;

            if ($item['type'] === 'youtube') {
                if (preg_match('/(?:v=|youtu\.be\/|embed\/)([A-Za-z0-9_-]+)/', $item['url'], $m)) {
                    $videoId = $m[1];
                }
            } else {
                if (preg_match('/vimeo\.com\/(?:video\/)?([0-9]+)/', $item['url'], $m)) {
                    $videoId = $m[1];
                }
            }

            if (!$videoId) continue;

            $itemId   = $item['id'];
            $filename = "{$item['type']}_{$videoId}_{$itemId}.jpg";

            $allowedThumbs[] = $filename;
        }
    }

    // MINIATURE PDF ONLINE
    foreach ($data['featuredItems'] as $item) {
        if (!empty($item['pdfThumb']) && preg_match('/^data:image\/([^;]+);base64,(.+)$/', $item['pdfThumb'], $m)) {
            $ext      = strtolower($m[1]) === 'jpeg' ? 'jpg' : $m[1];
            $filename = "pdf_thumb_{$item['id']}.$ext";
            file_put_contents($pending_dir . $filename, base64_decode($m[2]));
        }
    }

    // Génération des miniatures offline (téléchargement)
    if (is_array($data)) {
        foreach ($data as $item) {

            if (empty($item['type']) || empty($item['url'])) continue;
            if ($item['type'] !== 'youtube' && $item['type'] !== 'vimeo') continue;

            // Extraction ID vidéo
            $videoId = null;

            if ($item['type'] === 'youtube') {
                if (preg_match('/(?:v=|youtu\.be\/|embed\/)([A-Za-z0-9_-]+)/', $item['url'], $m)) {
                    $videoId = $m[1];
                }
            } else {
                if (preg_match('/vimeo\.com\/(?:video\/)?([0-9]+)/', $item['url'], $m)) {
                    $videoId = $m[1];
                }
            }

            if (!$videoId) continue;

            $itemId   = !empty($item['id']) ? $item['id'] : time();
            $filename = "{$item['type']}_{$videoId}_{$itemId}.jpg";
            $target   = $vcard_extract_dir . $filename;

            // Téléchargement offline
            $thumb_url = ($item['type'] === 'youtube')
                ? "https://img.youtube.com/vi/$videoId/hqdefault.jpg"
                : "https://vumbnail.com/$videoId.jpg";

            $response = wp_remote_get($thumb_url, ['sslverify' => false]);
            if (!is_wp_error($response)) {
                file_put_contents($target, wp_remote_retrieve_body($response));
            }
        }
    }
}

// ------------------------------------------------------
// COPIE DES MINIATURES YOUTUBE / VIMEO DEPUIS LE CACHE GDPR
// (SEULEMENT CELLES DE CETTE VCARD)
// ------------------------------------------------------
foreach ($providers as $provider) {

    $cache_dir = $vcards_root . "gdpr-{$provider}/";

    if (!is_dir($cache_dir)) continue;

    foreach (glob($cache_dir . "{$provider}_*_*.jpg") as $src) {

        $basename = basename($src);

        // On ne copie QUE les miniatures de CETTE vCard
        if (!in_array($basename, $allowedThumbs, true)) {
            continue;
        }

        $dest = $pending_dir . $basename;
        @copy($src, $dest);
    }
}


    // 3) Création du meta.json
    $meta = [
        'id'              => $vcard_id,
        'email'           => $email,
        'created_at'      => time(),
        'last_validation' => null,
        'last_visit'      => null,
        'validity_days'   => 90,
        'pending_token'   => $token,
        'renew_token'     => wp_generate_password(20, false, false),
        'status'          => 'pending'
    ];

    file_put_contents($pending_dir . 'meta.json', json_encode($meta, JSON_PRETTY_PRINT));

    // 4) Reconstruction du ZIP avec TOUT (HTML, CSS, JSON, miniatures…)
    $zip = new ZipArchive();
    if ($zip->open($zip_path, ZipArchive::OVERWRITE) === true) {

        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($pending_dir, RecursiveDirectoryIterator::SKIP_DOTS)
        );

		foreach ($files as $file) {
			$filePath     = $file->getRealPath();
			$relativePath = substr($filePath, strlen($pending_dir));

			// ❌ On n'ajoute PAS le ZIP lui-même
			if ($relativePath === $vcard_id . '.zip') {
				continue;
			}

			$zip->addFile($filePath, $relativePath);
		}

        $zip->close();
    }

    // 5) Email d’activation
    $site_url       = rtrim(get_site_url(), '/');
    $activation_url = $site_url . '/?wpvg-activate=' . $token;

    add_filter('wp_mail_content_type', 'wpvg_mail_content_type');
    add_filter('wp_mail_from', function () {
        return 'info@chefprojetdigital.fr';
    });
    add_filter('wp_mail_from_name', function () {
        return 'Votre vCard';
    });

    $subject = "Activez votre vCard";

    $message = <<<HTML
    <p style="font-size:14px;color:#555;">
    Cet email vous est envoyé automatiquement suite à la création de votre vCard sur notre site.
    </p>

    <p>Bonjour,</p>
    
    <p>Votre carte de visite numérique est prête.</p>
    
    <p>Pour y accéder, cliquez simplement sur le bouton ci‑dessous :</p>

    <!--[if mso]>
    <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" href="{$activation_url}"
    style="height:45px;v-text-anchor:middle;width:260px;" arcsize="10%" stroke="f" fillcolor="#2271b1">
    <w:anchorlock/>
    <center style="color:#ffffff;font-family:Arial,sans-serif;font-size:16px;font-weight:bold;">
    Activer ma vCard
    </center>
    </v:roundrect>
    <![endif]-->

    <!--[if !mso]><!-- -->
    <a href="{$activation_url}" 
       style="display:inline-block;
              padding:14px 22px;
              background:#2271b1;
              color:#ffffff !important;
              text-decoration:none;
              border-radius:6px;
              font-size:16px;
              font-weight:600;
              font-family:Arial,sans-serif;">
       Activer ma vCard
    </a>
    <!--<![endif]-->

    <p>Vous recevrez ensuite un second message contenant :</p>
    <ul>
        <li>le lien public de votre vCard</li>
        <li>le téléchargement ZIP</li>
        <li>le lien de désactivation si nécessaire</li>
    </ul>

    <p>Merci et bonne journée !</p>
    HTML;

    wp_mail($email, $subject, $message);

    remove_filter('wp_mail_content_type', 'wpvg_mail_content_type');

    wp_send_json([
        'success'  => true,
        'message'  => 'vCard en attente de validation',
        'token'    => $token,
        'activate' => $activation_url
    ]);
}

// Hooks admin-post
add_action('admin_post_wpvg_upload', 'wpvg_upload_vcard');
add_action('admin_post_nopriv_wpvg_upload', 'wpvg_upload_vcard');
