<?php

class RTImage
{
    /**
     * @param array $rentalImgIds
     * @return array
     */
    public function getImages(array $rentalImgIds)
    {
        global $wpdb, $rental_tables;
        $rental_image_relations = $wpdb->prefix . $rental_tables["image_relations"];

        $existedImages = [];
        $newImages = [];
        foreach ($rentalImgIds as $rentalImgId) {
            $imgId = $wpdb->get_var("SELECT `id` FROM $rental_image_relations WHERE `rental_id` = $rentalImgId");
            if ($imgId) {
                $existedImages[$rentalImgId] = $imgId;
            } else {
                $newImages[] = $rentalImgId;
            }
        }
        if ( !empty($newImages)) {
            $newImages = $this->uploadNewImages($newImages);
            foreach ($newImages as $rentalImgId => $imgId) {
                $existedImages[$rentalImgId] = $imgId;
            }
        }

        return $existedImages;
    }

    /**
     * @param array $imgIds
     * @return array
     */
    public function uploadNewImages(array $imgIds)
    {
        global $wpdb, $rental_tables;
        $rental_image_relations = $wpdb->prefix . $rental_tables["image_relations"];

        $images = $this->getImagesFromRentopian($imgIds);
        if (empty($images)) {
            return [];
        }

        $existedImages = [];
        foreach ($images as $image) {
            if ( !$image->url) {
                continue;
            }

            // Download the image from the URL to a temporary file
            if ( ! function_exists('download_url') ) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
            }
            $tmp_file = download_url( $image->url );
            if ( is_wp_error( $tmp_file ) ) {

                ErrorHandler::registerErrorInLog(
                    "Download failed for image {$image->id}: " . $tmp_file->get_error_message(),
                    __FILE__, __LINE__,
                    RentalException::TYPE_SYNC_RUNTIME
                );

                // Download failed; skip this image
                continue;
            }

            // Prepare an array similar to PHP $_FILES for sideloading
            $file_array = array(
                'name'     => basename( $image->url ),
                'tmp_name' => $tmp_file,
            );

            // Sideload the image into the Media Library
            // $attach_id = media_handle_sideload($file_array, $image->id);
            // if ( is_wp_error($attach_id) ) {

            //     ErrorHandler::registerErrorInLog(
            //         "Sideload failed for image {$image->id}: " . $attach_id->get_error_message(),
            //         __FILE__, __LINE__,
            //         RentalException::TYPE_SYNC_RUNTIME
            //     );

            //     if ( file_exists( $file_array['tmp_name'] ) ) {
            //         @unlink( $file_array['tmp_name'] );
            //     }
            
            //     continue;
            // }

            $upload = wp_upload_bits(basename( $image->url ), null, file_get_contents( $tmp_file ));

            if ( $upload['error'] ) {
                throw new Exception("Upload error: " . $upload['error']);

                ErrorHandler::registerErrorInLog(
                    "Upload error: " . $upload['error'],
                    __FILE__, __LINE__,
                    RentalException::TYPE_SYNC_RUNTIME
                );
            }
            
            $wp_upload_dir = wp_upload_dir();

            if (isset($upload['file'])) {

                $attachment = [
                    'guid' => $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path($upload['file']),
                    'post_mime_type' => $image->mime,
                    'post_title' => $image->label,
                    'post_content' => $image->description? $image->description: "",
                    'post_status' => 'inherit'
                ];


                $attach_id = wp_insert_attachment($attachment, $upload['file'], 0);

                if (is_wp_error($attach_id)) {

                    perf_point( "attach error - continuing");

                    ErrorHandler::registerErrorInLog(
                        "wp_insert_attachment failed for image {$image->id}: " . $attach_id->get_error_message(),
                        __FILE__, __LINE__,
                        RentalException::TYPE_SYNC_RUNTIME
                    );
    
                    if ( file_exists( $file_array['tmp_name'] ) ) {
                        @unlink( $file_array['tmp_name'] );
                    }
                
                    continue;
                }
                

                require_once(ABSPATH . 'wp-admin/includes/image.php');
        
                $szs = rental_make_image_subsizes( $upload['file'], $attach_id );

                $existedImages[$image->id] = $attach_id;
                $image_relations_sql[] = "($attach_id, $image->id)";
            }

            // require_once(ABSPATH . 'wp-admin/includes/image.php');
            // $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
            // wp_update_attachment_metadata($attach_id, $attach_data);

            // $existedImages[$image->id] = $attach_id;
            // $image_relations_sql[] = "($attach_id, $image->id)";

        }

        if ( !empty($image_relations_sql)) {
            $image_relations_sql = implode(", ", $image_relations_sql);
            $wpdb->query("INSERT INTO `$rental_image_relations` (`id`, `rental_id`) VALUES $image_relations_sql");
        }

        return $existedImages;
    }

    public function uploadNewImages_OLD(array $imgIds)
    {
        global $wpdb, $rental_tables;
        $rental_image_relations = $wpdb->prefix . $rental_tables["image_relations"];

        $images = $this->getImagesFromRentopian($imgIds);
        if (empty($images)) {
            return [];
        }
        $existedImages = [];
        foreach ($images as $image) {
            if ( !$image->img_content) {
                continue;
            }

            $upload = wp_upload_bits($image->filename, null, base64_decode($image->img_content));

            $attach_id = wp_insert_attachment([
                'guid' => $upload['url'],
                'post_mime_type' => $image->mime,
                'post_title' => $image->label,
                'post_content' => $image->description? $image->description: "",
                'post_status' => 'inherit'
            ], $upload['file']);

            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
            wp_update_attachment_metadata($attach_id, $attach_data);

            $existedImages[$image->id] = $attach_id;
            $image_relations_sql[] = "($attach_id, $image->id)";
        }

        if ( !empty($image_relations_sql)) {
            $image_relations_sql = implode(", ", $image_relations_sql);
            $wpdb->query("INSERT INTO `$rental_image_relations` (`id`, `rental_id`) VALUES $image_relations_sql");
        }

        return $existedImages;
    }

    /**
     * @param array $imgIds
     * @return mixed
     */
    public function getImagesFromRentopian(array $imgIds)
    {
        $api_key = get_option('rental_api_key');
        // return rental_curl('files/images', $api_key, true, ['images' => json_encode($imgIds)]);
        
        try {

            return rental_curl('files/images/stream', $api_key, true, ['images' => json_encode($imgIds)]);

        } catch (RentalException $e) {

            ErrorHandler::registerErrorInLog(
                "API fetch failed in webhooks : " . $e->getMessage(),
                __FILE__, __LINE__,
                $e->getType(),   // preserve type
                null,
                $e->getStatusCode(),
                serialize(['imgIds' => $imgIds])
            );
            throw $e;
        }

        
    }
}