<?php

//=====[ download additional contents ]=====//
if (!function_exists('amJL_download_and_install_pro_features')) {
    function amJL_download_and_install_pro_features($package_url) {
        
        // download directory setting
        $upload_dir = wp_upload_dir();
        $tmp_zip_path = trailingslashit($upload_dir['basedir']) . 'auto-making-json-ld-pro.zip';

        // download additional contents
        $response = wp_remote_get($package_url);
        if (is_wp_error($response)) {
            error_log('[amJL] Pro ダウンロード失敗: ' . $package_url);
            return false;
        }

        $zip_body = wp_remote_retrieve_body($response);
        if (empty($zip_body)) {
            error_log('[amJL] Pro ZIPファイルが空です: ' . $package_url);
            return false;
        }

        // save
        if (file_put_contents($tmp_zip_path, $zip_body) === false) {
            error_log('[amJL] ZIPファイルの保存に失敗しました: ' . $tmp_zip_path);
            return false;
        }

        // directory check
        $path = amJL_define_path();
        if (!file_exists($path['contents'])) {
            if (!wp_mkdir_p($path['contents'])) {
                error_log('[amJL] 展開先ディレクトリの作成に失敗: ' . $path['contents']);
                return false;
            }
        }

        // open zip file
        $zip = new ZipArchive();
        if ($zip->open($tmp_zip_path) === true) {
            $zip->extractTo($path['contents']);
            $zip->close();
            unlink($tmp_zip_path);
            return true;
        } else {
            error_log('[amJL] ZIPの展開に失敗しました: ' . $tmp_zip_path);
            return false;
        }
    }
}

//=====[ lisence check ]=====//
if (!function_exists('amJL_is_license_valid')) {
    function amJL_is_license_valid($license_key = null) {
        if (empty($license_key)) {
            $license_key = get_option('plugin');
            // $license_key = get_option('amJL_plugin');
        }

        $plugin_slug = 'auto-making-json-ld';
        $post_data = array(
            'plugin'      => $plugin_slug,
            'license_key' => $license_key,
        );

        $path = amJL_define_path();
        $remote_url = trailingslashit($path['api_url']) . 'check-update.php';

        $response = wp_remote_post($remote_url, array(
            'body'    => $post_data,
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            error_log('[amJL] API通信エラー: ' . $response->get_error_message());
            return (object) ['valid' => false];
        }

        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body);

        if (!is_object($result) || !isset($result->valid)) {
            error_log('[amJL] API応答が無効です: ' . $body);
            return (object) ['valid' => false];
        }

        return $result;
    }
}
