<?php

if ( ! defined( 'ABSPATH' ) ) exit;

require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');


function docuchat_add_images_and_resources()
{
    try {
        $public_folder = plugin_dir_path(__FILE__) . '../public';
     
        $ids_images = array();

        if (!get_option(DOCUCHAT_IMAGES_IDS)) {

            foreach (scandir($public_folder) as $key => $value) {
               
                if (file_exists($public_folder . '/' . $value) &&  str_contains($value, 'docuchat_')) {
                   
                    $file_info = pathinfo($value);
                    $file_name_local = $file_info['basename'];
                    $url_local =  $public_folder . '/' . $file_name_local;

                    $upload_dir = wp_upload_dir();
                    $file_destiny_url = $upload_dir['path'] . '/' . $value;


                    if (file_exists($url_local)) {
                        if (!copy($url_local,  $file_destiny_url)) {
                            return new WP_Error('fallo_copia', 'No se pudo copiar el archivo a la carpeta de subidas.');
                        };
                    }


                    $mime_type = mime_content_type($file_destiny_url);
                    $file_data = array(
                        'guid' => $upload_dir['url'] . '/' . $file_info['filename'] . '.' . $file_info['extension'],
                        'post_mime_type' => $mime_type,
                        'post_title' => $file_info['filename'],
                        'post_status' => 'inherit'
                    );


                    $file_id = wp_insert_attachment($file_data, $file_destiny_url);


                    if (is_wp_error($file_id)) {
                        return $file_id;
                    } else {

                        $attach_data = wp_generate_attachment_metadata($file_id, $file_destiny_url);
                        wp_update_attachment_metadata($file_id, $attach_data);

                        $ids_images[$key - 2] = $file_id;
                    }
                
            }
            }

            update_option(DOCUCHAT_IMAGES_IDS, serialize($ids_images));

            if(!get_option( DOCUCHAT_ACTIVATION_SERIALIZACION )){

               add_option( DOCUCHAT_ACTIVATION_SERIALIZACION, serialize(['active', 0, 0, 0 ]) );
            }   
        }
    } catch (\Throwable $th) {
        wp_die( 'Try to add images when activate', 400);
    }
}
