<?php

//add_action('excluir_fotos_nao_usadas', 'excluir_fotos_nao_usadas');


add_action('wp_ajax_fotos_nao_usadas', 'excluir_fotos_nao_usadas');
//do_action('excluir_fotos_nao_usadas');

function excluir_fotos_nao_usadas()
{

    global $wpdb;

    $baseurl = wp_upload_dir(false);
    $dir = $baseurl['basedir'];
    $baseURL = $baseurl['baseurl'];

    $it = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::FOLLOW_SYMLINKS);
    $display = Array('jpeg', 'jpg', 'png');


    $arquivos_excluidos = [];


    remove_all_attachments();


    foreach (new \RecursiveIteratorIterator($it) as $file) {

        $arquivo = $file->getPathname();
        $name_file = $file->getFilename();


        if (in_array(strtolower(array_pop(explode('.', $arquivo))), $display)) {


            $sn_encontrado = false;

            $image_src = $baseURL . _wp_relative_upload_path($arquivo);

            $url = str_replace("\\", '/', $image_src);
            $arrData = explode('-', $url);
            array_pop($arrData);
            //verificar se possui alguma descricao de tamanho adicional ao nome do arquivo, se sim ignorar
            $name_file_new = str_replace('.', '-', $name_file);

            $regex = '/-[0-9]{3,4}x[0-9]{3}/';
            $info = preg_split($regex, $name_file_new);
            //$name_file = $info[0];
            $name_file_new = $info[0];



            $query = "SELECT COUNT(*) FROM {$wpdb->posts} 
                        WHERE 
                            (post_name LIKE '%$name_file_new%' or guid like '%$name_file%') 
                            and 
                            (post_type = 'attachment')";
            $count = intval($wpdb->get_var($query));



            if ($count != 0) {
                $sn_encontrado = true;

            }

            $query = "SELECT COUNT(*) FROM {$wpdb->postmeta}
                        INNER JOIN {$wpdb->posts} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id
                        WHERE 
                            (meta_value LIKE '%$name_file_new%' or meta_value like '%$name_file%')
                            and 
                            ({$wpdb->posts}.post_status = 'inherit' OR {$wpdb->posts}.post_status = 'publish')";
            $count = intval($wpdb->get_var($query));



            if ($count != 0) {
                $sn_encontrado = true;
            }


            $query = "SELECT COUNT(*) FROM {$wpdb->termmeta} WHERE meta_value LIKE '%$name_file_new%' or meta_value like '%$name_file%'";

            $count = intval($wpdb->get_var($query));
            if ($count != 0) {
                $sn_encontrado = true;
            }



            if ($sn_encontrado == false) {
                //print_r($arquivo);
                unlink($arquivo);
                $arquivos_excluidos[] = $arquivo;
            }

        }

    }
    pr($arquivos_excluidos);
    die;
}

function remove_all_attachments() {
    global $wpdb;
    $ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN (SELECT ID FROM {$wpdb->posts} i WHERE i.post_type = 'attachment'
        AND NOT EXISTS (SELECT * FROM {$wpdb->posts} p WHERE p.ID = i.post_parent)
        AND NOT EXISTS (SELECT * FROM {$wpdb->postmeta} pm WHERE pm.meta_key = '_thumbnail_id' AND pm.meta_value = i.ID)
        AND NOT EXISTS (SELECT * FROM {$wpdb->postmeta} pm WHERE pm.meta_key = '_product_image_gallery' AND pm.meta_value LIKE CONCAT('%', i.ID,'%'))
        AND NOT EXISTS (SELECT * FROM {$wpdb->posts} p WHERE p.post_type <> 'attachment' AND p.post_content LIKE CONCAT('%', i.guid,'%'))
        AND NOT EXISTS (SELECT * FROM {$wpdb->postmeta} pm WHERE pm.meta_value LIKE CONCAT('%', i.guid,'%')))");


    if ( empty($ids) ) return;
    $remove = implode(',', $ids);


    // remove post meta
    $query_meta = "DELETE FROM $wpdb->postmeta WHERE post_id IN ({$remove})";
    $wpdb->query($query_meta);
    // remove posts
    $query_post = "DELETE FROM $wpdb->posts WHERE ID IN ({$remove})";
    $wpdb->query($query_post);


}
