<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class IntegratePalace_Properties_Admin {
    private $plugin_name;
    private $version;

    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    public function enqueue_styles() {
         wp_enqueue_style( 'wp-color-picker' );
         wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'assets/css/ipp-admin.css', array(), $this->version, 'all' );
    }

    public function enqueue_scripts() {
        wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'assets/js/ipp-admin.js', array( 'jquery' , 'wp-color-picker' , 'media-views' ), $this->version, false );
    }

    /**
     * Fetch images from Palace API and sync gallery for a property.
     * Downloads images, creates WP attachments with thumbnails, updates gallery meta.
     */
    public function update_integrate_palace_gallery( $post_id, $property_code ) {
        if ( ! $post_id || ! $property_code ) {
            error_log( 'IPP Gallery: Missing post_id or property_code.' );
            return;
        }

        self::update_gallery_sync_status( $post_id, 'syncing', 'Fetching image list from Palace API...' );

        $username = get_option( 'integrate_palace_properties_username' );
        $password = get_option( 'integrate_palace_properties_password' );

        if ( ! $username || ! $password ) {
            error_log( 'IPP Gallery: Missing API credentials.' );
            self::update_gallery_sync_status( $post_id, 'failed', 'Missing API credentials.' );
            return;
        }

        $api_url  = "https://api.getpalace.com/Service.svc/RestService/v2AvailablePropertyImages/JSON/$property_code";
        $headers  = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ) );
        // Throttle: respect Palace API rate limits during batch operations
        $last_call = get_transient( 'ipp_gallery_api_last_call' );
        if ( $last_call && ( microtime( true ) - (float) $last_call ) < 1.5 ) {
            usleep( 1500000 ); // 1.5s minimum gap between API calls
        }

        $response = wp_remote_get( $api_url, array( 'headers' => $headers, 'timeout' => 60 ) );
        set_transient( 'ipp_gallery_api_last_call', microtime( true ), 60 );

        if ( is_wp_error( $response ) ) {
            $error_msg = $response->get_error_message();
            error_log( 'IPP Gallery: API error — ' . $error_msg );

            $retries = (int) get_post_meta( $post_id, 'ipp_gallery_sync_retries', true ) + 1;
            update_post_meta( $post_id, 'ipp_gallery_sync_retries', $retries );

            if ( $retries >= 5 ) {
                self::update_gallery_sync_status( $post_id, 'failed', 'API error after ' . $retries . ' retries: ' . $error_msg );
            } else {
                self::update_gallery_sync_status( $post_id, 'queued', 'Retry ' . $retries . '/5 — ' . $error_msg );
                if ( ! wp_next_scheduled( 'update_integrate_palace_gallery', array( $post_id, $property_code ) ) ) {
                    wp_schedule_single_event( time() + 600, 'update_integrate_palace_gallery', array( $post_id, $property_code ) );
                }
            }
            return;
        }

        $images = json_decode( wp_remote_retrieve_body( $response ), true );
        if ( empty( $images ) ) {
            error_log( 'IPP Gallery: No images returned — ' . $api_url );
            // Don't touch existing gallery — API may just have no data right now
            self::clear_gallery_sync_meta( $post_id );
            return;
        }

        // Build map of existing gallery attachments by filename
        $gallery = get_post_meta( $post_id, 'integrate_palace_gallery', true );
        if ( ! is_array( $gallery ) ) {
            $gallery = array();
        }
        $existing = array();
        foreach ( $gallery as $att_id ) {
            $url = wp_get_attachment_url( $att_id );
            if ( $url ) {
                $existing[ basename( $url ) ] = $att_id;
            }
        }

        if ( ! function_exists( 'pp_get_image_extension' ) ) {
            function pp_get_image_extension( $base64_string ) {
                $img_info = getimagesizefromstring( base64_decode( $base64_string ) );
                return $img_info ? image_type_to_extension( $img_info[2], false ) : 'jpg';
            }
        }

        $kept   = array();
        $total  = count( $images );
        $errors = array();

        self::update_gallery_sync_status( $post_id, 'syncing', 'Processing ' . $total . ' images...', 0, $total );

        require_once ABSPATH . 'wp-admin/includes/image.php';
        $processed = 0;

        foreach ( $images as $image ) {
            $image_code = sanitize_file_name( $image['PropertyImageCode'] ?? '' );
            $base64     = $image['PropertyImageBase64'] ?? '';

            if ( empty( $image_code ) || empty( $base64 ) ) {
                $errors[] = ( $image_code ?: 'unknown' ) . ': empty data';
                continue;
            }

            $file_extension = pp_get_image_extension( $base64 );
            $filename       = "$image_code.$file_extension";

            if ( isset( $existing[ $filename ] ) ) {
                $kept[] = $existing[ $filename ];
                unset( $existing[ $filename ] );
            } else {
                $image_data = base64_decode( $base64 );
                if ( empty( $image_data ) ) {
                    $errors[] = $filename . ': decode failed';
                    continue;
                }

                $upload = wp_upload_bits( $filename, null, $image_data );
                if ( $upload['error'] ) {
                    $errors[] = $filename . ': ' . $upload['error'];
                    continue;
                }

                $attach_id = wp_insert_attachment( array(
                    'post_mime_type' => wp_check_filetype( $filename )['type'],
                    'post_title'     => $image_code,
                    'post_status'    => 'inherit',
                ), $upload['file'], $post_id );

                if ( ! is_wp_error( $attach_id ) ) {
                    $meta = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
                    wp_update_attachment_metadata( $attach_id, $meta );
                    $kept[] = $attach_id;
                } else {
                    $errors[] = $filename . ': insert failed';
                }
            }

            $processed++;
            // Update progress periodically (every 3 images) to stay resource-light
            if ( $processed % 3 === 0 || $processed === $total ) {
                update_post_meta( $post_id, 'ipp_gallery_sync_processed', $processed );
            }
        }

        // Finalize gallery
        $new_gallery = $kept;
        if ( count( $new_gallery ) > 0 ) {
            set_post_thumbnail( $post_id, $new_gallery[0] );
        }

        // Save gallery
        update_post_meta( $post_id, 'integrate_palace_gallery', $new_gallery );

        // Delete orphaned old images
        foreach ( $existing as $old_id ) {
            wp_delete_attachment( $old_id, true );
        }

        // Final status
        $synced      = count( $new_gallery );
        $error_count = count( $errors );
        delete_post_meta( $post_id, 'ipp_gallery_sync_retries' );

        if ( $synced === 0 && $total > 0 ) {
            $msg = '0/' . $total . ' images saved';
            if ( $error_count > 0 ) $msg .= '. Errors: ' . implode( '; ', array_slice( $errors, 0, 3 ) );
            self::update_gallery_sync_status( $post_id, 'failed', $msg, 0, $total );
        } elseif ( $error_count > 0 ) {
            $msg = $synced . '/' . $total . ' images synced (' . $error_count . ' failed)';
            self::update_gallery_sync_status( $post_id, 'failed', $msg, $synced, $total );
        } else {
            // Full success — clear tracking meta so it disappears from progress panel
            self::clear_gallery_sync_meta( $post_id );
        }

        /** @hook ipp_gallery_updated */
        do_action( 'ipp_gallery_updated', $post_id, $new_gallery );
    }

    /**
     * Update gallery sync status metadata for a property.
     *
     * @param int    $post_id
     * @param string $status   One of: queued, syncing, failed
     * @param string $message  Human-readable status message.
     * @param int    $processed Number of images processed so far.
     * @param int    $total     Total number of images to process.
     */
    public static function update_gallery_sync_status( $post_id, $status, $message = '', $processed = 0, $total = 0 ) {
        update_post_meta( $post_id, 'ipp_gallery_sync_status', $status );
        update_post_meta( $post_id, 'ipp_gallery_sync_message', $message );
        update_post_meta( $post_id, 'ipp_gallery_sync_processed', $processed );
        update_post_meta( $post_id, 'ipp_gallery_sync_total', $total );

        if ( $status === 'syncing' && ! get_post_meta( $post_id, 'ipp_gallery_sync_started_at', true ) ) {
            update_post_meta( $post_id, 'ipp_gallery_sync_started_at', current_time( 'mysql' ) );
        }

        if ( $status === 'failed' ) {
            update_post_meta( $post_id, 'ipp_gallery_sync_completed_at', current_time( 'mysql' ) );
        }
    }

    /**
     * Remove all gallery sync tracking meta from a property.
     * Called on successful completion so it disappears from the progress panel.
     */
    public static function clear_gallery_sync_meta( $post_id ) {
        // Store a lightweight last-sync summary before clearing
        $gallery = get_post_meta( $post_id, 'integrate_palace_gallery', true );
        $image_count = is_array( $gallery ) ? count( $gallery ) : 0;
        update_post_meta( $post_id, 'ipp_gallery_last_sync', current_time( 'mysql' ) );
        update_post_meta( $post_id, 'ipp_gallery_last_sync_count', $image_count );

        delete_post_meta( $post_id, 'ipp_gallery_sync_status' );
        delete_post_meta( $post_id, 'ipp_gallery_sync_message' );
        delete_post_meta( $post_id, 'ipp_gallery_sync_processed' );
        delete_post_meta( $post_id, 'ipp_gallery_sync_total' );
        delete_post_meta( $post_id, 'ipp_gallery_sync_started_at' );
        delete_post_meta( $post_id, 'ipp_gallery_sync_completed_at' );
        delete_post_meta( $post_id, 'ipp_gallery_sync_retries' );
        delete_post_meta( $post_id, 'ipp_gallery_sync_errors' );
    }

    public function integrate_palace_properties_plugin_row_meta($links, $file){
        if (strpos($file, 'integrate-palace-properties') !== false) {
            $new_links = array(
                '<a target="_blank" href="https://wp-palace.kiwibrain.co.nz/register"><b>Go Pro</b></a>',
                '<a href="mailto:itsisaf@gmail.com">Support</a>',
                '<a target="_blank" href="https://wp-palace.kiwibrain.co.nz">View details</a>',
                '<a href="' . esc_url( admin_url( 'admin.php?page=ipp-developer-docs' ) ) . '">Developer Docs</a>',
            );
            $links = array_merge($links, $new_links);
        }
        return $links;
    }
}
