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

add_action( 'init', 'elementsell_maybe_sync_publish_endpoint_to_webroot', 1 );
add_action( 'admin_init', 'elementsell_maybe_sync_publish_endpoint_to_webroot_on_admin', 1 );

/**
 * @return string[]
 */
function elementsell_get_publish_sync_hosts() {
    return (array) apply_filters(
        'elementsell_publish_sync_hosts',
        [
            'platebniformular.cz',
            'www.platebniformular.cz',
            'elementsell.cz',
            'www.elementsell.cz',
        ]
    );
}

/**
 * @return bool
 */
function elementsell_should_sync_publish_endpoint() {
    if ( ! function_exists( 'home_url' ) ) {
        return false;
    }

    $host = strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) );

    return in_array( $host, elementsell_get_publish_sync_hosts(), true );
}

/**
 * Zkopíruje soubor z pluginu do kořene webu, pokud chybí nebo je zastaralý.
 *
 * @param string $source
 * @param string $target
 * @return bool True pokud došlo ke kopii.
 */
function elementsell_copy_publish_endpoint_if_stale( $source, $target ) {
    if ( ! file_exists( $source ) ) {
        return false;
    }

    $should_copy = ! file_exists( $target );

    if ( ! $should_copy ) {
        $source_mtime = (int) @filemtime( $source );
        $target_mtime = (int) @filemtime( $target );

        if ( $source_mtime > $target_mtime ) {
            $should_copy = true;
        } elseif ( $source_mtime === $target_mtime && $source_mtime > 0 ) {
            $source_hash = @md5_file( $source );
            $target_hash = @md5_file( $target );

            $should_copy = is_string( $source_hash )
                && is_string( $target_hash )
                && $source_hash !== $target_hash;
        }
    }

    if ( ! $should_copy ) {
        return false;
    }

    return (bool) @copy( $source, $target );
}

/**
 * Zkopíruje publish endpointy z pluginu do kořene webu (kvůli POST z hostingu).
 *
 * Secret soubor NESMÍ být v pluginu — na serveru ručně vytvořte v kořeni webu:
 * - elementsell-secrets.php (viz remote-server/elementsell-secrets.php.example)
 * Sync kopíruje jen PHP endpointy; elementsell-secrets.php se nikdy nepřepisuje.
 *
 * @return bool True pokud byl synchronizován alespoň jeden soubor.
 */
function elementsell_sync_publish_endpoint_files() {
    $copied = false;

    $copied = elementsell_copy_publish_endpoint_if_stale(
        PF_PLUGIN_DIR . 'remote-server/elementsell_publish_update.php',
        trailingslashit( ABSPATH ) . 'elementsell_publish_update.php'
    ) || $copied;

    $copied = elementsell_copy_publish_endpoint_if_stale(
        PF_PLUGIN_DIR . 'remote-server/elementsell_stats.php',
        trailingslashit( ABSPATH ) . 'elementsell_stats.php'
    ) || $copied;

    $copied = elementsell_copy_publish_endpoint_if_stale(
        PF_PLUGIN_DIR . 'remote-server/platebniformular-publish.php',
        trailingslashit( ABSPATH ) . 'platebniformular-publish.php'
    ) || $copied;

    $data_dir = trailingslashit( ABSPATH ) . 'data';

    if ( ! is_dir( $data_dir ) ) {
        wp_mkdir_p( $data_dir );
    }

    $data_htaccess_source = PF_PLUGIN_DIR . 'remote-server/data/.htaccess';
    $data_htaccess_target = $data_dir . '/.htaccess';

    if ( file_exists( $data_htaccess_source ) && ! file_exists( $data_htaccess_target ) ) {
        $copied = (bool) copy( $data_htaccess_source, $data_htaccess_target ) || $copied;
    }

    $releases_dir = trailingslashit( ABSPATH ) . 'releases';

    if ( ! is_dir( $releases_dir ) ) {
        wp_mkdir_p( $releases_dir );
    }

    $htaccess_source = PF_PLUGIN_DIR . 'remote-server/releases/.htaccess';
    $htaccess_target = $releases_dir . '/.htaccess';

    if ( file_exists( $htaccess_source ) && ! file_exists( $htaccess_target ) ) {
        $copied = (bool) copy( $htaccess_source, $htaccess_target ) || $copied;
    }

    return $copied;
}

/**
 * @return void
 */
function elementsell_maybe_sync_publish_endpoint_to_webroot() {
    if ( ! elementsell_should_sync_publish_endpoint() ) {
        return;
    }

    if ( function_exists( 'elementsell_get_release_logic_version' ) ) {
        $current = elementsell_get_release_logic_version();
        $stored  = (string) get_option( 'elementsell_release_logic_version', '' );

        if ( $current !== '' && $current !== $stored ) {
            delete_transient( 'elementsell_publish_endpoint_synced' );

            if ( elementsell_sync_publish_endpoint_files() ) {
                update_option( 'elementsell_release_logic_version', $current, false );
            }
        }
    }

    if ( get_transient( 'elementsell_publish_endpoint_synced' ) ) {
        return;
    }

    elementsell_sync_publish_endpoint_files();
    set_transient( 'elementsell_publish_endpoint_synced', 1, HOUR_IN_SECONDS );
}

/**
 * Při načtení WP adminu vždy zkontroluje, zda endpoint ve webrootu není zastaralý.
 *
 * @return void
 */
function elementsell_maybe_sync_publish_endpoint_to_webroot_on_admin() {
    if ( ! elementsell_should_sync_publish_endpoint() ) {
        return;
    }

    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( elementsell_sync_publish_endpoint_files() ) {
        delete_transient( 'elementsell_publish_endpoint_synced' );
    }

    if ( function_exists( 'elementsell_sync_plugin_version_to_deployed' ) ) {
        elementsell_sync_plugin_version_to_deployed();
    }

    set_transient( 'elementsell_publish_endpoint_synced', 1, HOUR_IN_SECONDS );
}

/**
 * @return string
 */
function elementsell_get_update_server_public_base_url() {
    if ( elementsell_should_sync_publish_endpoint() ) {
        return (string) apply_filters(
            'elementsell_update_server_public_base_url',
            'https://elementsell.cz'
        );
    }

    return (string) apply_filters(
        'elementsell_update_server_public_base_url',
        'https://elementsell.cz'
    );
}

/**
 * Statický JSON manifest pro kontrolu aktualizací (GET).
 *
 * @return string
 */
function elementsell_get_update_manifest_filename() {
    return 'elementsell-update.json';
}

/**
 * PHP endpoint pro vypuštění nové verze (POST).
 *
 * @return string
 */
function elementsell_get_update_server_publish_filename() {
    return 'elementsell_publish_update.php';
}

/**
 * Cesta k lokálnímu manifestu na update serveru (webroot).
 *
 * @return string
 */
function elementsell_get_local_update_manifest_path() {
    if ( ! elementsell_should_sync_publish_endpoint() ) {
        return '';
    }

    return trailingslashit( ABSPATH ) . elementsell_get_update_manifest_filename();
}

/**
 * Načte manifest z disku (update server — bez HTTP loopback).
 *
 * @return array<string, mixed>|null
 */
function elementsell_read_local_update_manifest() {
    $path = elementsell_get_local_update_manifest_path();

    if ( $path === '' || ! is_readable( $path ) ) {
        return null;
    }

    $data = json_decode( (string) file_get_contents( $path ), true );

    if ( ! is_array( $data ) || empty( $data['version'] ) || empty( $data['download_url'] ) ) {
        return null;
    }

    return $data;
}

/**
 * URL POST endpointu pro vypuštění ZIP na update server.
 *
 * @return string
 */
function elementsell_get_release_publish_url() {
    $base = rtrim( elementsell_get_update_server_public_base_url(), '/' );

    return (string) apply_filters(
        'elementsell_release_publish_url',
        $base . '/' . elementsell_get_update_server_publish_filename()
    );
}

/**
 * @return void
 */
function elementsell_force_sync_publish_endpoint_to_webroot() {
    delete_transient( 'elementsell_publish_endpoint_synced' );
    elementsell_sync_publish_endpoint_files();

    if ( function_exists( 'elementsell_get_release_logic_version' ) ) {
        $current = elementsell_get_release_logic_version();

        if ( $current !== '' ) {
            update_option( 'elementsell_release_logic_version', $current, false );
        }
    }
}
