<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class IntegratePalace_Properties_Admin_Ajax {

    public static function init() {
        add_action( 'wp_ajax_ipp_trigger_sync', array( __CLASS__, 'trigger_sync' ) );
        add_action( 'wp_ajax_ipp_get_sync_status', array( __CLASS__, 'get_sync_status' ) );
        add_action( 'wp_ajax_ipp_test_connection', array( __CLASS__, 'test_connection' ) );
        add_action( 'wp_ajax_ipp_gallery_sync_progress', array( __CLASS__, 'gallery_sync_progress' ) );
        add_action( 'wp_ajax_ipp_gallery_sync_run', array( __CLASS__, 'gallery_sync_run' ) );
        add_action( 'wp_ajax_ipp_resync_galleries', array( __CLASS__, 'resync_galleries' ) );
    }

    /**
     * Trigger a property sync via the Laravel API.
     */
    public static function trigger_sync() {
        check_ajax_referer( 'ipp_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'integrate-palace-properties' ) );
        }

        $api_base = defined( 'IPP_API_URL' ) ? IPP_API_URL : 'https://wp-palace.kiwibrain.co.nz';
        $sub_key  = get_option( 'integrate_palace_properties_subscription_key', '' );

        if ( empty( $sub_key ) ) {
            wp_send_json_error( __( 'No subscription key configured.', 'integrate-palace-properties' ) );
        }

        // Call the Laravel API to trigger sync
        $response = wp_remote_post( $api_base . '/api/sync/trigger', array(
            'method'  => 'POST',
            'headers' => array(
                'Content-Type'       => 'application/json',
                'X-Subscription-Key' => sanitize_text_field( $sub_key ),
            ),
            'body'    => wp_json_encode( array(
                'subscription_key' => sanitize_text_field( $sub_key ),
            ) ),
            'timeout' => 30,
        ) );

        $prop_count = wp_count_posts( 'palace-properties' );
        $count      = isset( $prop_count->publish ) ? $prop_count->publish : 0;

        if ( is_wp_error( $response ) ) {
            wp_send_json_error( sprintf(
                /* translators: %s: error message */
                __( 'Sync request failed: %s. You have %d properties locally.', 'integrate-palace-properties' ),
                $response->get_error_message(),
                $count
            ) );
        }

        $status_code = wp_remote_retrieve_response_code( $response );

        if ( $status_code < 200 || $status_code >= 300 ) {
            wp_send_json_error( sprintf(
                /* translators: %d: HTTP status code, %d: property count */
                __( 'Sync request returned HTTP %1$d. You have %2$d properties locally.', 'integrate-palace-properties' ),
                $status_code,
                $count
            ) );
        }

        // Only update last sync time on actual success
        update_option( 'ipp_last_sync_time', current_time( 'mysql' ) );
        update_option( 'ipp_last_sync_count', $count );

        wp_send_json_success( array(
            'message' => __( 'Resync requested from Palace server.', 'integrate-palace-properties' ),
            'count'      => $count,
            'api_status' => $status_code,
        ) );
    }

    /**
     * Get current sync status.
     */
    public static function get_sync_status() {
        check_ajax_referer( 'ipp_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'integrate-palace-properties' ) );
        }

        $prop_count = wp_count_posts( 'palace-properties' );
        $count = isset( $prop_count->publish ) ? $prop_count->publish : 0;
        $last_sync = get_option( 'ipp_last_sync_time', '' );

        wp_send_json_success( array(
            'count'     => $count,
            'last_sync' => $last_sync ? human_time_diff( strtotime( $last_sync ), current_time( 'timestamp' ) ) . ' ago' : __( 'Never', 'integrate-palace-properties' ),
        ) );
    }

    /**
     * Test Palace API connection.
     */
    public static function test_connection() {
        check_ajax_referer( 'ipp_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'integrate-palace-properties' ) );
        }

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

        if ( empty( $username ) || empty( $password ) ) {
            wp_send_json_error( __( 'API credentials not configured.', 'integrate-palace-properties' ) );
        }

        $token = base64_encode( $username . ':' . $password );
        $api_url = 'https://api.getpalace.com/Service.svc/RestService/v2GetCompanyDetailsByAPICredentials/JSON';

        $response = wp_remote_get( $api_url, array(
            'headers' => array( 'Authorization' => 'Basic ' . $token ),
            'timeout' => 15,
        ) );

        if ( is_wp_error( $response ) ) {
            wp_send_json_error( $response->get_error_message() );
        }

        $code = wp_remote_retrieve_response_code( $response );
        $body = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( $code === 200 && ! empty( $body ) ) {
            wp_send_json_success( array(
                'message'  => __( 'Connection successful!', 'integrate-palace-properties' ),
                'company'  => isset( $body['CompanyName'] ) ? sanitize_text_field( $body['CompanyName'] ) : '',
                'country'  => isset( $body['Country'] ) ? sanitize_text_field( $body['Country'] ) : '',
            ) );
        }

        wp_send_json_error( sprintf(
            /* translators: %d: HTTP status code */
            __( 'Connection failed (HTTP %d).', 'integrate-palace-properties' ),
            $code
        ) );
    }

    /**
     * Get gallery sync progress for all properties with active sync status.
     */
    public static function gallery_sync_progress() {
        check_ajax_referer( 'ipp_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'integrate-palace-properties' ) );
        }

        // Query properties with active sync status (exclude completed)
        $properties = get_posts( array(
            'post_type'      => 'palace-properties',
            'posts_per_page' => 100,
            'post_status'    => 'any',
            'meta_query'     => array(
                array(
                    'key'     => 'ipp_gallery_sync_status',
                    'value'   => 'completed',
                    'compare' => '!=',
                ),
            ),
            'orderby'        => 'meta_value',
            'meta_key'       => 'ipp_gallery_sync_started_at',
            'order'          => 'DESC',
        ) );

        $items = array();
        $summary = array( 'queued' => 0, 'syncing' => 0, 'failed' => 0 );

        foreach ( $properties as $prop ) {
            $status    = get_post_meta( $prop->ID, 'ipp_gallery_sync_status', true );
            $message   = get_post_meta( $prop->ID, 'ipp_gallery_sync_message', true );
            $processed = (int) get_post_meta( $prop->ID, 'ipp_gallery_sync_processed', true );
            $total     = (int) get_post_meta( $prop->ID, 'ipp_gallery_sync_total', true );
            $started   = get_post_meta( $prop->ID, 'ipp_gallery_sync_started_at', true );
            $completed = get_post_meta( $prop->ID, 'ipp_gallery_sync_completed_at', true );
            $retries   = (int) get_post_meta( $prop->ID, 'ipp_gallery_sync_retries', true );

            if ( ! $status ) continue;

            if ( isset( $summary[ $status ] ) ) {
                $summary[ $status ]++;
            }

            $items[] = array(
                'post_id'      => $prop->ID,
                'title'        => $prop->post_title,
                'edit_url'     => get_edit_post_link( $prop->ID, 'raw' ),
                'status'       => $status,
                'message'      => $message,
                'processed'    => $processed,
                'total'        => $total,
                'retries'      => $retries,
                'started_at'   => $started ? human_time_diff( strtotime( $started ), current_time( 'timestamp' ) ) . ' ago' : '',
                'completed_at' => $completed ? human_time_diff( strtotime( $completed ), current_time( 'timestamp' ) ) . ' ago' : '',
            );
        }

        // Sort: failed first (needs attention), then syncing, then queued
        $order = array( 'failed' => 0, 'syncing' => 1, 'queued' => 2 );
        usort( $items, function( $a, $b ) use ( $order ) {
            return ( $order[ $a['status'] ] ?? 9 ) - ( $order[ $b['status'] ] ?? 9 );
        } );

        wp_send_json_success( array(
            'summary' => $summary,
            'items'   => $items,
        ) );
    }

    /**
     * Manually trigger processing of queued gallery syncs (bypasses WP-Cron wait).
     * Processes one property at a time per request to avoid timeouts.
     */
    public static function gallery_sync_run() {
        check_ajax_referer( 'ipp_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'integrate-palace-properties' ) );
        }

        // Find the next property that needs gallery sync (any active status)
        $pending = get_posts( array(
            'post_type'      => 'palace-properties',
            'posts_per_page' => 1,
            'post_status'    => 'any',
            'meta_query'     => array(
                array(
                    'key'     => 'ipp_gallery_sync_status',
                    'value'   => array( 'queued', 'syncing' ),
                    'compare' => 'IN',
                ),
            ),
            'orderby'        => 'meta_value',
            'meta_key'       => 'ipp_gallery_sync_started_at',
            'order'          => 'ASC',
        ) );

        if ( empty( $pending ) ) {
            wp_send_json_success( array(
                'done'    => true,
                'message' => __( 'No pending syncs remaining.', 'integrate-palace-properties' ),
            ) );
        }

        $post = $pending[0];
        $property_code = get_post_meta( $post->ID, 'ipp_property_code', true );
        if ( empty( $property_code ) ) {
            $property_code = get_post_meta( $post->ID, 'information_property_code', true );
        }

        if ( empty( $property_code ) ) {
            IntegratePalace_Properties_Admin::update_gallery_sync_status(
                $post->ID, 'failed', 'No property code found.'
            );
            wp_send_json_success( array(
                'done'      => false,
                'processed' => $post->post_title,
                'status'    => 'failed',
                'message'   => 'No property code found.',
            ) );
        }

        // Unschedule cron event since we are processing it now
        $args = array( $post->ID, $property_code );
        $next = wp_next_scheduled( 'update_integrate_palace_gallery', $args );
        if ( $next ) {
            wp_unschedule_event( $next, 'update_integrate_palace_gallery', $args );
        }

        // Run gallery sync directly (fetches images from API, processes inline)
        $admin = new IntegratePalace_Properties_Admin( 'integrate-palace-properties', defined( 'INTEGRATE_PALACE_P_VERSION' ) ? INTEGRATE_PALACE_P_VERSION : '1.0' );
        $admin->update_integrate_palace_gallery( $post->ID, $property_code );

        $final_status = get_post_meta( $post->ID, 'ipp_gallery_sync_status', true );
        $final_msg    = get_post_meta( $post->ID, 'ipp_gallery_sync_message', true );

        wp_send_json_success( array(
            'done'      => false,
            'processed' => $post->post_title,
            'status'    => $final_status ?: 'completed',
            'message'   => $final_msg ?: 'Synced.',
        ) );
    }

    /**
     * Queue gallery syncs for all properties — forces re-download of images.
     */
    public static function resync_galleries() {
        check_ajax_referer( 'ipp_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'integrate-palace-properties' ) );
        }

        $properties = get_posts( array(
            'post_type'      => 'palace-properties',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'fields'         => 'ids',
        ) );

        $queued = 0;
        foreach ( $properties as $post_id ) {
            $property_code = get_post_meta( $post_id, 'ipp_property_code', true );
            if ( empty( $property_code ) ) {
                $property_code = get_post_meta( $post_id, 'information_property_code', true );
            }
            if ( empty( $property_code ) ) continue;

            // Clear old gallery so images are re-downloaded fresh
            delete_post_meta( $post_id, 'integrate_palace_gallery' );

            IntegratePalace_Properties_Admin::update_gallery_sync_status( $post_id, 'queued', 'Queued for gallery resync.' );
            update_post_meta( $post_id, 'ipp_gallery_sync_started_at', current_time( 'mysql' ) );
            $queued++;
        }

        wp_send_json_success( array(
            'message' => sprintf( '%d properties queued for gallery resync. Click Process Now to start.', $queued ),
            'count'   => $queued,
        ) );
    }
}
