<?php
ob_start();
/* START: INCLUDE FOLDER SETTING & ASSETS */
$pathToAssets = array("elements/css", "elements/images", "elements/video", "elements/fonts", "elements/js", "elements/tz_mail");
$filename = "tmp/leadgen.zip"; //use the /tmp folder to circumvent any permission issues on the root folder
if (file_exists($filename)) {
    unlink($filename);
}
/* END: INCLUDE FOLDER SETTING & ASSETS */
/* START: API KEYS & VARIABLES */
$export_type = $_POST['export_type'];
$recaptcha = $_POST['g-recaptcha-secret-key'];
$tz_email = $_POST['tz_email'];
$tz_from_email = $_POST['tz_email_from'];
$tz_subject = $_POST['tz_subject'];
$tz_cm_apikey = $_POST['cm_api_key'];
$tz_cm_listid = $_POST['cm_list_id'];
$tz_mc_apikey = $_POST['mailchimp_api_key'];
$tz_mc_listid = $_POST['mailchimp_api_listid'];
$tz_gr_apikey = $_POST['getresponse_api_key'];
$tz_gr_campaign = $_POST['getresponse_campaign_token'];
$tz_active_url = $_POST['ac_api_url'];
$tz_active_api_key = $_POST['ac_api_key'];
$tz_active_list_id = $_POST['ac_api_listid'];
$tz_aw_listname = $_POST['aweber_list_name'];
$tz_mailerlite_api_key = $_POST['ml_api_key'];
$tz_mailerlite_group_id = $_POST['ml_groupid'];
/* END: API KEYS & VARIABLES */
/* CONFIG SETTINGS */
$file_config = 'elements/export/api-config.php';
$get_config = htmlspecialchars(file_get_contents($file_config));
$arr_keys_php = array('&#039;');
$arr_value_php = array("'");

$themezaa_config_php = str_replace($arr_keys_php, $arr_value_php, $get_config);

$arr_keys = array('export_type', 'custom_email','custom_from_email','custom_subject', 'g-recaptcha-secret-key', 'mc_config_apikey', 'mc_config_listid', 'cm_config_apikey', 'cm_config_listid', 'gr_config_apikey', 'gr_config_token', 'aw_config_listname', 'ac_config_url', 'ac_config_apikey', 'ac_config_listid', 'ml_config_apikey', 'ml_config_groupid', '&lt;', '&gt;');
$arr_values = array($export_type, $tz_email,$tz_from_email,$tz_subject, $recaptcha, $tz_mc_apikey, $tz_mc_listid, $tz_cm_apikey, $tz_cm_listid, $tz_gr_apikey, $tz_gr_campaign, $tz_aw_listname, $tz_active_url, $tz_active_api_key, $tz_active_list_id, $tz_mailerlite_api_key, $tz_mailerlite_group_id, '<', '>');
$themezaa_config = str_replace($arr_keys, $arr_values, $themezaa_config_php);


/* END CONFIG SETTINGS */
/* JS SETTINGS */
$file_js = 'elements/export/main.js';
$get_js_config = htmlspecialchars(file_get_contents($file_js));
$arr_keys_js = array('&quot;', '&lt;', '&gt;','&amp;', '&#039;');
$arr_value_js = array('"', '<', '>','&', "'");
$themezaa_config_js = str_replace($arr_keys_js, $arr_value_js, $get_js_config);
/* END JS SETTINGS */
$zip = new ZipArchive();
$zip->open($filename, ZipArchive::CREATE);
/* add folder structure */
foreach ($pathToAssets as $thePath) {
    /* Create recursive directory iterator */
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($thePath), RecursiveIteratorIterator::LEAVES_ONLY
        );
    foreach ($files as $name => $file) {
        if ($file->getFilename() != '.' && $file->getFilename() != '..') {
            /* Get real path for current file */
            $filePath = $file->getRealPath();
            $temp = explode("/", $name);
            array_shift($temp);
            $newName = implode("/", $temp);
            /* Add current file to archive */
            $zip->addFile($filePath, $newName);
        }
    }
}
foreach ($_POST['pages'] as $page => $content) {
    $html_header = file_get_contents('elements/export/header.html');
    $html_footer = htmlspecialchars(file_get_contents('elements/export/footer.html'));

    /* SEO, OPEN GRAPH Y VCF */
    $tz_seo_meta = isset($_POST['tz_seo'][$page]) ? $_POST['tz_seo'][$page] : '';
    $tz_seo = $tz_seo_meta !== '' ? explode('1_@_2_@', $tz_seo_meta) : array();

    $seo_title       = isset($tz_seo[0]) && $tz_seo[0] !== '' ? $tz_seo[0] : 'LinkCards';
    $seo_description = isset($tz_seo[1]) ? $tz_seo[1] : '';
    $seo_keywords    = isset($tz_seo[2]) ? $tz_seo[2] : '';
    $seo_author      = isset($tz_seo[3]) ? $tz_seo[3] : '';

    $og_site_name    = isset($tz_seo[4]) && $tz_seo[4] !== '' ? $tz_seo[4] : $seo_title;
    $og_url          = isset($tz_seo[5]) ? $tz_seo[5] : '';
    $og_image        = isset($tz_seo[6]) ? $tz_seo[6] : '';
    $og_image_alt    = isset($tz_seo[7]) && $tz_seo[7] !== '' ? $tz_seo[7] : $seo_title;

    $vcf_contact     = isset($tz_seo[8]) ? trim($tz_seo[8]) : '';
    $vcf_company     = isset($tz_seo[9]) ? trim($tz_seo[9]) : '';
    $vcf_job_title   = isset($tz_seo[10]) ? trim($tz_seo[10]) : '';
    $vcf_phone       = isset($tz_seo[11]) ? trim($tz_seo[11]) : '';
    $vcf_whatsapp    = isset($tz_seo[12]) ? trim($tz_seo[12]) : '';
    $vcf_email       = isset($tz_seo[13]) ? trim($tz_seo[13]) : '';
    $vcf_website     = isset($tz_seo[14]) ? trim($tz_seo[14]) : '';
    $vcf_instagram   = isset($tz_seo[15]) ? trim($tz_seo[15]) : '';
    $vcf_address     = isset($tz_seo[16]) ? trim($tz_seo[16]) : '';
    $vcf_path        = 'images/contacto.vcf';

    /*
     * Compatibilidad reforzada para instalaciones donde builder.js todavía
     * no envía los campos VCF dentro de tz_seo. Primero intenta leer posibles
     * campos POST directos y, si siguen vacíos, recupera teléfono, WhatsApp,
     * correo e Instagram desde los enlaces presentes en la página exportada.
     */
    $lc_post_value = function ($names) {
        foreach ($names as $name) {
            if (isset($_POST[$name]) && !is_array($_POST[$name])) {
                $value = trim((string) $_POST[$name]);
                if ($value !== '') {
                    return $value;
                }
            }
        }
        return '';
    };

    if ($vcf_contact === '') {
        $vcf_contact = $lc_post_value(array('vcf_contact', 'tz_vcf_contact', 'lc_vcf_contact', 'vcf_name'));
    }
    if ($vcf_company === '') {
        $vcf_company = $lc_post_value(array('vcf_company', 'tz_vcf_company', 'lc_vcf_company'));
    }
    if ($vcf_job_title === '') {
        $vcf_job_title = $lc_post_value(array('vcf_job_title', 'tz_vcf_job_title', 'lc_vcf_job_title', 'vcf_title'));
    }
    if ($vcf_phone === '') {
        $vcf_phone = $lc_post_value(array('vcf_phone', 'tz_vcf_phone', 'lc_vcf_phone'));
    }
    if ($vcf_whatsapp === '') {
        $vcf_whatsapp = $lc_post_value(array('vcf_whatsapp', 'tz_vcf_whatsapp', 'lc_vcf_whatsapp'));
    }
    if ($vcf_email === '') {
        $vcf_email = $lc_post_value(array('vcf_email', 'tz_vcf_email', 'lc_vcf_email'));
    }
    if ($vcf_website === '') {
        $vcf_website = $lc_post_value(array('vcf_website', 'tz_vcf_website', 'lc_vcf_website'));
    }
    if ($vcf_instagram === '') {
        $vcf_instagram = $lc_post_value(array('vcf_instagram', 'tz_vcf_instagram', 'lc_vcf_instagram'));
    }
    if ($vcf_address === '') {
        $vcf_address = $lc_post_value(array('vcf_address', 'tz_vcf_address', 'lc_vcf_address'));
    }

    $lc_page_source = html_entity_decode(stripslashes((string) $content), ENT_QUOTES, 'UTF-8');

    if ($vcf_phone === '' && preg_match('/href=[\"\']tel:([^\"\'#?]+)/i', $lc_page_source, $lc_match)) {
        $vcf_phone = rawurldecode(trim($lc_match[1]));
    }
    if ($vcf_whatsapp === '' && preg_match('~https?://(?:api\.)?wa\.me/(?:send\?phone=)?([0-9+]+)~i', $lc_page_source, $lc_match)) {
        $vcf_whatsapp = trim($lc_match[1]);
    }
    if ($vcf_email === '' && preg_match('/href=[\"\']mailto:([^\"\'?]+)/i', $lc_page_source, $lc_match)) {
        $vcf_email = rawurldecode(trim($lc_match[1]));
    }
    if ($vcf_instagram === '' && preg_match('~https?://(?:www\.)?instagram\.com/[^\"\'\s<]+~i', $lc_page_source, $lc_match)) {
        $vcf_instagram = rtrim($lc_match[0], '/');
    }

    /* Valores seguros de respaldo para que Android no reciba un VCF vacío. */
    if ($vcf_contact === '') {
        $vcf_contact = $seo_title !== '' ? $seo_title : $og_site_name;
    }
    if ($vcf_company === '' && $og_site_name !== $vcf_contact) {
        $vcf_company = $og_site_name;
    }
    if ($vcf_website === '') {
        $vcf_website = $og_url;
    }

    /* Escapar los valores antes de insertarlos en etiquetas HTML */
    $seo_title_safe       = htmlspecialchars($seo_title, ENT_QUOTES, 'UTF-8');
    $seo_description_safe = htmlspecialchars($seo_description, ENT_QUOTES, 'UTF-8');
    $seo_keywords_safe    = htmlspecialchars($seo_keywords, ENT_QUOTES, 'UTF-8');
    $seo_author_safe      = htmlspecialchars($seo_author, ENT_QUOTES, 'UTF-8');
    $og_site_name_safe    = htmlspecialchars($og_site_name, ENT_QUOTES, 'UTF-8');
    $og_url_safe          = htmlspecialchars($og_url, ENT_QUOTES, 'UTF-8');
    $og_image_safe        = htmlspecialchars($og_image, ENT_QUOTES, 'UTF-8');
    $og_image_alt_safe    = htmlspecialchars($og_image_alt, ENT_QUOTES, 'UTF-8');
    $vcf_contact_safe     = htmlspecialchars($vcf_contact, ENT_QUOTES, 'UTF-8');
    $vcf_path_safe        = htmlspecialchars($vcf_path, ENT_QUOTES, 'UTF-8');

    /* Favicon */
    $tz_fav_icon = isset($_POST['tz_favicon_icon']) ? $_POST['tz_favicon_icon'] : '';
    $favicon_path = 'images/icon/favicon.png';

    if ($tz_fav_icon !== '') {
        $tz_new_icon = explode('./elements/', $tz_fav_icon);

        if (isset($tz_new_icon[1]) && $tz_new_icon[1] !== '') {
            $favicon_path = $tz_new_icon[1];
        }
    }

    $meta_keys = array(
        'LC_META_TITLE',
        'LC_META_DESCRIPTION',
        'LC_META_KEYWORDS',
        'LC_META_AUTHOR',
        'LC_OG_SITE_NAME',
        'LC_OG_URL',
        'LC_OG_IMAGE',
        'LC_OG_IMAGE_ALT',
        'images/icon/favicon.png'
    );

    $meta_values = array(
        $seo_title_safe,
        $seo_description_safe,
        $seo_keywords_safe,
        $seo_author_safe,
        $og_site_name_safe,
        $og_url_safe,
        $og_image_safe,
        $og_image_alt_safe,
        $favicon_path
    );

    $meta_seo_values = str_replace($meta_keys, $meta_values, $html_header);

    /* End SEO, OPEN GRAPH Y VCF */
    $tz_html_array = array('&quot;','%20','contact-submit');
    $tz_html_keys = array("'","","tz_submit");
    $tz_html_content = str_replace($tz_html_array, $tz_html_keys, $content);

    /* Permite usar LC_VCF_PATH y LC_VCF_CONTACT_NAME dentro de los botones o enlaces */
    $tz_html_content = str_replace(
        array('LC_VCF_PATH', 'LC_VCF_CONTACT_NAME'),
        array($vcf_path_safe, $vcf_contact_safe),
        $tz_html_content
    );
    $tz_footer_keys = array('&lt;','&gt;');
    $tz_footer_values = array('<','>');
    $tz_html_footer = str_replace($tz_footer_keys, $tz_footer_values, $html_footer);
    /* Protección disuasoria para la página exportada.
       No puede impedir al 100% que un usuario técnico vea el código,
       pero bloquea clic derecho, copiar, arrastrar y accesos rápidos comunes. */
    $lc_protection = <<<'LCSECURITY'
<script>
(function () {
    'use strict';

    document.addEventListener('contextmenu', function (event) {
        event.preventDefault();
    }, false);

    document.addEventListener('copy', function (event) {
        event.preventDefault();
    }, false);

    document.addEventListener('cut', function (event) {
        event.preventDefault();
    }, false);

    document.addEventListener('dragstart', function (event) {
        if (event.target && (event.target.tagName === 'IMG' || event.target.tagName === 'A')) {
            event.preventDefault();
        }
    }, false);

    document.addEventListener('keydown', function (event) {
        var key = String(event.key || '').toLowerCase();
        var blocked =
            key === 'f12' ||
            (event.ctrlKey && key === 'u') ||
            (event.ctrlKey && key === 's') ||
            (event.ctrlKey && key === 'c') ||
            (event.ctrlKey && event.shiftKey && (key === 'i' || key === 'j' || key === 'c'));

        if (blocked) {
            event.preventDefault();
            event.stopPropagation();
            return false;
        }
    }, true);
})();
</script>
<style>
html, body {
    -webkit-user-select: none;
    user-select: none;
}
input, textarea, select, [contenteditable="true"] {
    -webkit-user-select: text;
    user-select: text;
}
img {
    -webkit-user-drag: none;
    user-drag: none;
}
</style>
LCSECURITY;

    /* Insertar protección antes del cierre de body cuando sea posible. */
    if (stripos($tz_html_footer, '</body>') !== false) {
        $tz_html_footer = str_ireplace('</body>', $lc_protection . "\n</body>", $tz_html_footer);
    } else {
        $tz_html_footer .= $lc_protection;
    }

    $tz_content = $meta_seo_values . stripslashes($tz_html_content) . $tz_html_footer;
    $zip->addFromString($page . ".html", stripslashes($tz_content));

    /* Crear automáticamente images/contacto.vcf — versión universal Android/iPhone/Google */
    $vcf_escape = function ($value) {
        return str_replace(
            array("\\", ";", ",", "\r\n", "\r", "\n"),
            array("\\\\", "\\;", "\\,", "\\n", "\\n", "\\n"),
            trim((string) $value)
        );
    };

    /* El teléfono se guarda una sola vez. WhatsApp solo sirve como respaldo. */
    $vcf_main_phone = trim($vcf_phone !== '' ? $vcf_phone : $vcf_whatsapp);
    if ($vcf_main_phone !== '') {
        $phone_has_plus = strpos($vcf_main_phone, '+') !== false;
        $vcf_main_phone = preg_replace('/[^0-9]/', '', $vcf_main_phone);
        if ($phone_has_plus && $vcf_main_phone !== '') {
            $vcf_main_phone = '+' . $vcf_main_phone;
        }
    }

    /* Separar nombre y apellido para la agenda del teléfono. */
    $full_name = trim($vcf_contact);
    $name_parts = preg_split('/\s+/u', $full_name, -1, PREG_SPLIT_NO_EMPTY);
    $family_name = '';
    $given_name = $full_name;

    if (count($name_parts) > 1) {
        $family_name = array_pop($name_parts);
        $given_name = implode(' ', $name_parts);
    }

    $vcf_lines = array(
        'BEGIN:VCARD',
        'VERSION:3.0',
        'PRODID:-//LinkCards//Contacto Digital//ES',
        'FN;CHARSET=UTF-8:' . $vcf_escape($full_name),
        'N;CHARSET=UTF-8:' . $vcf_escape($family_name) . ';' . $vcf_escape($given_name) . ';;;'
    );

    if ($vcf_company !== '') {
        $vcf_lines[] = 'ORG;CHARSET=UTF-8:' . $vcf_escape($vcf_company);
    }
    if ($vcf_job_title !== '') {
        $vcf_lines[] = 'TITLE;CHARSET=UTF-8:' . $vcf_escape($vcf_job_title);
    }
    if ($vcf_main_phone !== '') {
        $vcf_lines[] = 'TEL;TYPE=CELL:' . $vcf_escape($vcf_main_phone);
    }
    if ($vcf_email !== '') {
        $vcf_lines[] = 'EMAIL;TYPE=INTERNET:' . $vcf_escape($vcf_email);
    }
    if ($vcf_website !== '') {
        $vcf_lines[] = 'URL:' . $vcf_escape($vcf_website);
    }

    /* Dirección compatible: separar por líneas o comas; si viene en una sola línea, conservarla completa. */
    if ($vcf_address !== '') {
        $address_parts = preg_split('/(?:\r\n|\r|\n|,)+/u', $vcf_address, -1, PREG_SPLIT_NO_EMPTY);
        $address_parts = array_values(array_map('trim', $address_parts));

        if (count($address_parts) >= 3) {
            $street = $address_parts[0];
            $city = $address_parts[1];
            $country = implode(', ', array_slice($address_parts, 2));
        } elseif (count($address_parts) === 2) {
            $street = $address_parts[0];
            $city = $address_parts[1];
            $country = '';
        } else {
            $street = trim($vcf_address);
            $city = '';
            $country = '';
        }

        $vcf_lines[] = 'ADR;TYPE=WORK;CHARSET=UTF-8:;;' .
            $vcf_escape($street) . ';' .
            $vcf_escape($city) . ';;;' .
            $vcf_escape($country);
    }

    /* Logo o foto: primero imagen Open Graph; después logo/perfil de la tarjeta. */
    $photo_candidates = array();
    if ($og_image !== '') {
        $photo_candidates[] = $og_image;
    }
    if (preg_match_all('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $lc_page_source, $img_matches)) {
        foreach ($img_matches[1] as $img_src) {
            if (preg_match('/(?:logo|profile|perfil)/i', $img_src)) {
                $photo_candidates[] = $img_src;
            }
        }
    }

    $photo_file = '';
    foreach ($photo_candidates as $candidate) {
        $candidate = html_entity_decode(trim($candidate), ENT_QUOTES, 'UTF-8');
        $candidate_path = parse_url($candidate, PHP_URL_PATH);
        if (!$candidate_path) {
            $candidate_path = $candidate;
        }
        $candidate_path = ltrim(str_replace('\\', '/', $candidate_path), '/');
        $possible_paths = array();

        if (strpos($candidate_path, 'elements/') === 0) {
            $possible_paths[] = $candidate_path;
        }
        if (strpos($candidate_path, 'images/') === 0) {
            $possible_paths[] = 'elements/' . $candidate_path;
        }
        if (strpos($candidate_path, 'Builder/elements/') !== false) {
            $possible_paths[] = substr($candidate_path, strpos($candidate_path, 'Builder/elements/') + strlen('Builder/'));
        }

        $base_name = basename($candidate_path);
        if ($base_name !== '') {
            $possible_paths[] = 'elements/images/uploads/' . $base_name;
            $possible_paths[] = 'elements/images/' . $base_name;
            $possible_paths[] = 'elements/images/icon/' . $base_name;
        }

        foreach (array_unique($possible_paths) as $possible_path) {
            /* Mantener la foto por debajo de 1.5 MB para mejor compatibilidad móvil. */
            if (is_file($possible_path) && filesize($possible_path) > 0 && filesize($possible_path) <= 1572864) {
                $photo_file = $possible_path;
                break 2;
            }
        }
    }

    if ($photo_file !== '') {
        $image_info = @getimagesize($photo_file);
        $photo_type = '';

        if ($image_info && isset($image_info['mime'])) {
            if ($image_info['mime'] === 'image/jpeg') {
                $photo_type = 'JPEG';
            } elseif ($image_info['mime'] === 'image/png') {
                $photo_type = 'PNG';
            }
        }

        if ($photo_type !== '') {
            $photo_base64 = base64_encode(file_get_contents($photo_file));
            $photo_chunks = str_split($photo_base64, 72);

            if (!empty($photo_chunks)) {
                $vcf_lines[] = 'PHOTO;ENCODING=b;TYPE=' . $photo_type . ':' . array_shift($photo_chunks);
                foreach ($photo_chunks as $photo_chunk) {
                    $vcf_lines[] = ' ' . $photo_chunk;
                }
            }
        }
    }

    $vcf_lines[] = 'REV:' . gmdate('Ymd\THis\Z');
    $vcf_lines[] = 'END:VCARD';

    /* CRLF y UTF-8 sin BOM: máxima compatibilidad entre Android, iPhone y Google Contacts. */
    $vcf_content = implode("\r\n", $vcf_lines) . "\r\n";
    $zip->deleteName($vcf_path);
    $zip->addFromString($vcf_path, $vcf_content);
}
foreach ($_POST['pages'] as $page => $img_content) {
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($img_content);
    $dom->preserveWhiteSpace = false;
    $tags_videos = $dom->getElementsByTagName('video');
    foreach($dom->getElementsByTagName('img') as $all_tags_img)
    {
        $images[] = $all_tags_img->getAttribute('src');
    }
    foreach($tags_videos as $all_tags_video)
    {
        $videos[] = $all_tags_video;
    }
    $files = glob('elements/images/*.{jpg,jpeg,png,gif,PNG,JPG,JPEG,GIF}', GLOB_BRACE);
    foreach($files as $file) {
        $img_folder[] = explode('/', $file);
    }
    $bg_reg = '/url\(([\'\"]?.*[\'\"]?)\)/i';
    preg_match_all($bg_reg, $img_content,$matches);
    foreach($matches[1] as $mat_value) {
        $bg_mat_img[] = $mat_value;
    }
}
if(empty($videos))
{
    $folder_video_delete = 'video/';
    for ($i = 0; $i < $zip->numFiles; $i++){
        $video_info = $zip->statIndex($i);
        if (substr($video_info["name"], 0, strlen($folder_video_delete)) == $folder_video_delete){
            $zip->deleteIndex($i);
        }
    }
}
if(!empty($bg_mat_img))
{
    foreach($bg_mat_img as $value) {
        $char_val = array("&quot;","'");
        $bg_value = str_replace($char_val,"",$value);
        $bg_img = explode('/', $bg_value);
        $bg_ex_img[] = $bg_img[2];
         
        $bg_files = glob('elements/images/bg-image/*.{jpg,jpeg,png,gif,PNG,JPG,JPEG,GIF}', GLOB_BRACE);
        foreach ($bg_files as $bg_file) {
            $bg_folder = explode('/', $bg_file);
            $bg_folder_img[] = $bg_folder[3];
        }
    }
    if(!empty($bg_ex_img))
    {
        $bg_results = array_diff($bg_folder_img,$bg_ex_img);
        foreach ($bg_results as $bg_res) 
        {
            $bg_img_path = 'images/bg-image/' . $bg_res;
            $zip->deleteName($bg_img_path);
        }
    }else{
        $bg_files = glob('elements/images/bg-image/*.{jpg,jpeg,png,gif,PNG,JPG,JPEG,GIF}', GLOB_BRACE);
        foreach ($bg_files as $bg_file) {
            $bg_folder = explode('/', $bg_file);
            $bg_img_path = 'images/bg-image/' . $bg_folder[3];
            $zip->deleteName($bg_img_path);
        } 
    }
}else{
        $bg_files = glob('elements/images/bg-image/*.{jpg,jpeg,png,gif,PNG,JPG,JPEG,GIF}', GLOB_BRACE);
        foreach ($bg_files as $bg_file) {
            $bg_folder = explode('/', $bg_file);
            $bg_img_path = 'images/bg-image/' . $bg_folder[3];
            $zip->deleteName($bg_img_path);
        } 
}
if(!empty($images))
{
    foreach($images as $img) 
    {
        $img_ex = explode('/', $img);
        if(empty($img_ex[2]))
        {
           $temp_img[] = $img_ex[1];
        }else{
           $temp_img[] = $img_ex[2];
        }
        
        foreach ($img_folder as $zip_folder) {
            $exp_img[] = $zip_folder[2];
        }
    }
    $result = array_diff($exp_img, $temp_img);
    foreach ($result as $res) 
    {
        $img_path = 'images/' . $res;
        $zip->deleteName($img_path);
    }
}else{
    foreach($img_folder as $zip_folder) 
    {
        $img_path = 'images/' . $zip_folder[2];
        $zip->deleteName($img_path);        
    }
}
if(!empty($bg_ex_img) && !empty($temp_img))
{
    $all_img = array_merge($bg_ex_img,$temp_img);
}elseif(!empty($bg_ex_img)){
    $all_img = $bg_ex_img;
}else if(!empty($temp_img)){
    $all_img = $temp_img;
}
if(!empty($all_img))
{
    $upload_files = glob('elements/images/uploads/*.{jpg,jpeg,png,gif,PNG,JPG,JPEG,GIF}', GLOB_BRACE);
    foreach ($upload_files as $upload_file) {
        $upload_folder = explode('/', $upload_file);
        $up_folder_img[] = $upload_folder[3];
    }
    if(!empty($up_folder_img))
    {
        $upload_results = array_diff($up_folder_img, $all_img);
        foreach ($upload_results as $up_res) 
        {
            $upload_folder = explode('/', $up_res);
            $up_img_path = 'images/uploads/' . $up_res;
            $zip->deleteName($up_img_path);
        }
    }
}else{
    $upload_files = glob('elements/images/uploads/*.{jpg,jpeg,png,gif,PNG,JPG,JPEG,GIF}', GLOB_BRACE);
    foreach ($upload_files as $upload_file) {
        $upload_folder = explode('/', $upload_file);
        $up_img_path = 'images/uploads/' . $upload_folder[3];
        $zip->deleteName($up_img_path);
    }
}
$folder_to_delete = 'images/thumbs/';
for ($i = 0; $i < $zip->numFiles; $i++) {
    $image_info = $zip->statIndex($i);
    if (substr($image_info["name"], 0, strlen($folder_to_delete)) == $folder_to_delete) {
        $zip->deleteIndex($i);
    }
}
$fileToModify = 'tz_mail/api-config.php';
$fileToJs = 'js/main.js';
$zip->deleteName($fileToJs);
$zip->deleteName($fileToModify);
$zip->addFromString($fileToJs, $themezaa_config_js);
$zip->addFromString($fileToModify, $themezaa_config);
$zip->close();
$yourfile = $filename;
$file_name = basename($yourfile);
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($yourfile));
ob_end_clean();
readfile($yourfile);
unlink('tmp/leadgen.zip');
exit;
?>