<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Vérification sécurité AJAX
 */
function wpvg_check_ajax_security() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => 'Permission refusée.' ) );
    }

    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'wpvg_admin_nonce' ) ) {
        wp_send_json_error( array( 'message' => 'Nonce invalide.' ) );
    }
}

/**
 * Liste les vCards (active, pending, off)
 */
add_action( 'wp_ajax_wpvg_list_vcards', 'wpvg_list_vcards' );
function wpvg_list_vcards() {

    wpvg_check_ajax_security();

    $search    = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
    $page      = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $per_page  = 50;

    $base_dir = ABSPATH . 'vcards/';

    $results = array(
        'active'  => array(),
        'pending' => array(),
        'off'     => array(),
    );

    /**
     * 1. vCards ACTIVES
     */
    foreach ( scandir( $base_dir ) as $folder ) {

        if ( $folder === '.' || $folder === '..' ) continue;
        if ( $folder === 'pending' || $folder === 'off' ) continue;

        $vcard_dir = $base_dir . $folder . '/';
        $data_path = $vcard_dir . 'private/data.json';

        if ( ! file_exists( $data_path ) ) continue;

        $json = json_decode( file_get_contents( $data_path ), true );
        if ( ! $json ) continue;
		
		$meta_path = $vcard_dir . 'private/meta.json';
		if ( ! file_exists( $meta_path ) ) continue;

		$meta = json_decode( file_get_contents( $meta_path ), true );
		if ( ! $meta ) continue;


				// Recherche simple
				if ( $search ) {
					$haystack = strtolower( $json['firstName'] . ' ' . $json['lastName'] . ' ' . $json['vcardId'] );
					if ( strpos( $haystack, strtolower( $search ) ) === false ) continue;
				}

				// Dates
				$created = date( 'Y-m-d H:i:s', filectime( $vcard_dir ) );
				$updated = date( 'Y-m-d H:i:s', filemtime( $data_path ) );

		$results['active'][] = array(
			'vcardId'   => $json['vcardId'],
			'name'      => $json['firstName'] . ' ' . $json['lastName'],
			'email'     => $json['email'] ?? '',
			'phone'     => $json['mobile'] ?? '',
			'url'       => site_url( '/vcards/' . $json['vcardId'] . '/index.html' ),
			'token'     => $meta['renew_token'],
			'zip'       => site_url( '/wp-content/plugins/wp-vcard-generator/download.php?id=' . $json['vcardId'] . '&file=zip&token=' . $meta['renew_token'] ),
			'folder'    => $vcard_dir,
			'created'   => $created,
			'updated'   => $updated,
		);
    }

    /**
     * 2. vCards PENDING
     */
    $pending_dir = $base_dir . 'pending/';
    if ( is_dir( $pending_dir ) ) {
        foreach ( scandir( $pending_dir ) as $folder ) {

            if ( $folder === '.' || $folder === '..' ) continue;

            $meta_path = $pending_dir . $folder . '/meta.json';
            if ( ! file_exists( $meta_path ) ) continue;

            $meta = json_decode( file_get_contents( $meta_path ), true );

            if ( $search ) {
                if ( strpos( strtolower( $folder ), strtolower( $search ) ) === false ) continue;
            }

            $created = $meta['created'] ?? date( 'Y-m-d H:i:s', filectime( $pending_dir . $folder ) );
            $updated = date( 'Y-m-d H:i:s', filemtime( $meta_path ) );

            $results['pending'][] = array(
                'token'    => $folder,
                'email'    => $meta['email'] ?? '',
                'created'  => $created,
                'updated'  => $updated,
                'folder'   => $pending_dir . $folder . '/',
            );
        }
    }

    /**
     * 3. vCards OFF
     */
    $off_dir = $base_dir . 'off/';
    if ( is_dir( $off_dir ) ) {
        foreach ( scandir( $off_dir ) as $folder ) {

            if ( $folder === '.' || $folder === '..' ) continue;

            $vcard_dir = $off_dir . $folder . '/';
            $data_path = $vcard_dir . 'data.json';
            $meta_off  = $vcard_dir . 'meta_off.json';

            if ( ! file_exists( $data_path ) ) continue;

            $json = json_decode( file_get_contents( $data_path ), true );
            if ( ! $json ) continue;

            if ( $search ) {
                $haystack = strtolower( $json['firstName'] . ' ' . $json['lastName'] . ' ' . $json['vcardId'] );
                if ( strpos( $haystack, strtolower( $search ) ) === false ) continue;
            }

            $created     = date( 'Y-m-d H:i:s', filectime( $vcard_dir ) );
            $updated     = date( 'Y-m-d H:i:s', filemtime( $data_path ) );
            $deactivated = file_exists( $meta_off )
                ? ( json_decode( file_get_contents( $meta_off ), true )['deactivated'] ?? $created )
                : $created;

            $results['off'][] = array(
                'vcardId'     => $json['vcardId'],
                'name'        => $json['firstName'] . ' ' . $json['lastName'],
                'email'       => $json['email'] ?? '',
                'phone'		  => $json['mobile'] ?? '',
                'folder'      => $vcard_dir,
                'created'     => $created,
                'updated'     => $updated,
                'deactivated' => $deactivated,
            );
        }
    }

    wp_send_json_success( $results );
}

/**
 * Désactiver une vCard (active → off)
 */
add_action( 'wp_ajax_wpvg_action_disable', 'wpvg_action_disable' );
function wpvg_action_disable() {

    wpvg_check_ajax_security();

    $vcardId = sanitize_text_field( $_POST['vcardId'] );

    $src = ABSPATH . 'vcards/' . $vcardId;
    $dst = ABSPATH . 'vcards/off/' . $vcardId;

    rename( $src, $dst );

    // Enregistrer la date de désactivation
    $meta = array(
        'deactivated' => current_time( 'mysql' )
    );

    file_put_contents(
        $dst . '/meta_off.json',
        wp_json_encode( $meta, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE )
    );

    wp_send_json_success( array( 'message' => 'vCard désactivée.' ) );
}

/**
 * Réactiver une vCard (off → active)
 */
add_action( 'wp_ajax_wpvg_action_enable', 'wpvg_action_enable' );
function wpvg_action_enable() {

    wpvg_check_ajax_security();

    $vcardId = sanitize_text_field( $_POST['vcardId'] );

    $src = ABSPATH . 'vcards/off/' . $vcardId;
    $dst = ABSPATH . 'vcards/' . $vcardId;

    rename( $src, $dst );

    wp_send_json_success( array( 'message' => 'vCard réactivée.' ) );
}

/**
 * Activer un pending (pending → active)
 */
add_action( 'wp_ajax_wpvg_action_activate_pending', 'wpvg_action_activate_pending' );
function wpvg_action_activate_pending() {

    wpvg_check_ajax_security();

    $token   = sanitize_text_field( $_POST['token'] );
    $vcardId = sanitize_text_field( $_POST['vcardId'] );

    $src = ABSPATH . 'vcards/pending/' . $token;
    $dst = ABSPATH . 'vcards/' . $vcardId;

    rename( $src, $dst );

    wp_send_json_success( array( 'message' => 'vCard activée.' ) );
}

/**
 * Supprimer définitivement une vCard (off → supprimée)
 */
add_action( 'wp_ajax_wpvg_action_delete', 'wpvg_action_delete' );
function wpvg_action_delete() {

    wpvg_check_ajax_security();

    $vcardId = sanitize_text_field( $_POST['vcardId'] );

    $dir = ABSPATH . 'vcards/off/' . $vcardId;

    if ( ! is_dir( $dir ) ) {
        wp_send_json_error( array( 'message' => 'Dossier introuvable.' ) );
    }

    // Utilise la fonction existante du plugin
    if ( function_exists( 'wpvg_rrmdir' ) ) {
        wpvg_rrmdir( $dir );
    } else {
        // fallback ultra simple
        @unlink( $dir . '/data.json' );
        @unlink( $dir . '/meta_off.json' );
        @rmdir( $dir );
    }

    wp_send_json_success( array( 'message' => 'vCard supprimée définitivement.' ) );
}

/**
 * Téléchargement miniature YouTube / Vimeo — VERSION EXACTE demandée
 * Stockage dans :
 *   /vcards/gdpr-youtube/
 *   /vcards/gdpr-vimeo/
 */
add_action('wp_ajax_wpvg_download_video_thumbnail', 'wpvg_download_video_thumbnail');
add_action('wp_ajax_nopriv_wpvg_download_video_thumbnail', 'wpvg_download_video_thumbnail');

function wpvg_download_video_thumbnail() {

    $provider = sanitize_text_field($_POST['provider']);
    $videoId  = sanitize_text_field($_POST['videoId']);
    $itemId   = sanitize_text_field($_POST['itemId']); // pour différencier plusieurs vidéos

    if (!$provider || !$videoId) {
        wp_send_json([
            'success' => false,
            'error'   => 'missing params'
        ]);
    }

    // ✔️ CHEMIN EXACTEMENT COMME TU L’AS DEMANDÉ
    $base = ABSPATH . "vcards";

    if ($provider === "youtube") {
        $folder = "$base/gdpr-youtube";
        $url    = "https://img.youtube.com/vi/$videoId/hqdefault.jpg";
    } else {
        $folder = "$base/gdpr-vimeo";
        $url    = "https://vumbnail.com/$videoId.jpg";
    }

    // ✔️ Création automatique des dossiers
    if (!file_exists($folder)) {
        wp_mkdir_p($folder);
    }

    // ✔️ Nom unique
    $suffix   = $itemId ? "_{$itemId}" : '';
    $filename = "{$provider}_{$videoId}{$suffix}.jpg";
    $target   = "$folder/$filename";

    // ✔️ Téléchargement
    $response = wp_remote_get($url);

    if (is_wp_error($response)) {
        wp_send_json([
            'success' => false,
            'error'   => 'download failed'
        ]);
    }

    file_put_contents($target, wp_remote_retrieve_body($response));

    // ✔️ URL publique EXACTE
    $public_url = site_url("vcards/" . basename($folder) . "/$filename");

    wp_send_json([
        'success'         => true,
        'local_thumbnail' => $public_url
    ]);
}

/**
 * Nettoyage manuel des miniatures GDPR
 */
add_action('wp_ajax_wpvg_clean_gdpr_thumbnails', function() {

    wpvg_check_ajax_security();

    $dirs = [
        ABSPATH . 'vcards/gdpr-youtube/',
        ABSPATH . 'vcards/gdpr-vimeo/'
    ];

    $deleted = 0;

    foreach ($dirs as $dir) {
        if (!is_dir($dir)) continue;

        foreach (scandir($dir) as $file) {
            if ($file === '.' || $file === '..') continue;

            $path = $dir . $file;

            if (is_file($path) && preg_match('/\.jpg$/i', $file)) {
                if (@unlink($path)) {
                    $deleted++;
                }
            }
        }
    }

    wp_send_json_success([
        'message' => "Miniatures supprimées : $deleted"
    ]);
});
