<?php
/**
 * TAB: SETTINGS — Core plugin settings (map engine, default country)
 *
 * @package ParcelSelector
 * @since   3.1.1
 */

if ( ! defined( 'ABSPATH' ) ) exit;

if ( ! function_exists( 'parcselect_tab_settings' ) ) {
function parcselect_tab_settings() {
    $t       = parcselect_admin_i18n();
    $engine  = get_option( 'parcselect_map_engine', 'classic' );
    $country = get_option( 'parcselect_default_country', 'pl' );

    $countries = array(
        'pl' => 'Polska (Poland)',
    );
    ?>

    <div class="parcelselector-section">
        <h2>🛠️ <?php echo esc_html( $t['set_title'] ); ?></h2>
        <p class="description"><?php echo esc_html( $t['set_desc'] ); ?></p>
    </div>

    <form action="options.php" method="post">
        <input type="hidden" name="ps_save_group" value="parcselect_settings_group">
        <?php settings_fields( 'parcselect_settings_group' ); ?>

        <div class="parcelselector-card">
            <table class="form-table" role="presentation">
                <tr>
                    <th scope="row"><?php echo esc_html( $t['set_map_engine'] ?? 'Map Engine' ); ?></th>
                    <td>
                        <select name="ps_map_engine">
                            <option value="anunaki" <?php selected( $engine, 'anunaki' ); ?>>ANUNAKI (live data — recommended)</option>
                            <option value="classic" <?php selected( $engine, 'classic' ); ?>>Classic (lightweight UI)</option>
                        </select>
                        <p class="description">
                            <?php echo esc_html( $t['set_map_engine_desc'] ?? 'ANUNAKI = full-featured map (recommended). Classic = lightweight UI. Both load pickup points from the ParcelSelector.com server.' ); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php echo esc_html( $t['set_default_country'] ?? 'Default Country' ); ?></th>
                    <td>
                        <select name="ps_default_country">
                            <?php foreach ( $countries as $code => $label ) : ?>
                                <option value="<?php echo esc_attr( $code ); ?>" <?php selected( $country, $code ); ?>>
                                    <?php echo esc_html( $label ); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p class="description">
                            <?php echo esc_html( $t['set_default_country_desc'] ?? 'The country shown by default when the parcel map opens.' ); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e( 'Show "Powered by" credit', 'parcel-selector' ); ?></th>
                    <td>
                        <label>
                            <input type="hidden" name="ps_show_powered_by" value="no">
                            <input type="checkbox" name="ps_show_powered_by" value="yes" <?php checked( get_option( 'parcselect_show_powered_by', 'no' ), 'yes' ); ?>>
                            <?php esc_html_e( 'Display a "Powered by ParcelSelector.com" credit on public SEO pages.', 'parcel-selector' ); ?>
                        </label>
                    </td>
                </tr>
            </table>
        </div>

        <?php submit_button( $t['save_changes'] ?? 'Save Changes' ); ?>
    </form>

    <!-- ═══════════════ IMPORT / EXPORT — hidden, reserved for future use ═══════════════ -->
    <div style="display:none;">
    <div class="parcelselector-section" style="margin-top:30px;">
        <h2>&#x1F4BE; <?php echo esc_html( $t['set_import_export'] ?? 'Import / Export settings' ); ?></h2>
        <p class="description"><?php echo esc_html( $t['set_import_export_desc'] ?? 'Download or upload plugin settings as a JSON file.' ); ?></p>
    </div>

    <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap:24px; margin-top:30px;">

        <!-- EXPORT -->
        <div class="parcelselector-card">
            <h3 style="margin-top:0; font-weight:700; color:var(--ps-text); display:flex; align-items:center; gap:10px;">
                <span>⬇️</span> <?php echo esc_html( $t['set_export_btn'] ?? 'Export settings' ); ?>
            </h3>
            <p style="color:var(--ps-text-dim); font-size:14px; margin-bottom:20px; line-height:1.5;">
                <?php echo esc_html( $t['set_export_desc'] ?? 'Downloads a JSON file with current plugin settings. You can import it on another site or after a reinstall.' ); ?>
            </p>
            <button type="button" id="ps-export-btn" class="parcelselector-btn parcelselector-btn-primary" style="width:100%;">
                <?php echo esc_html( $t['set_export_btn'] ?? 'Download settings.json' ); ?>
            </button>
        </div>

        <!-- IMPORT -->
        <div class="parcelselector-card">
            <h3 style="margin-top:0; font-weight:700; color:var(--ps-text); display:flex; align-items:center; gap:10px;">
                <span>⬆️</span> <?php echo esc_html( $t['tab_settings'] ?? 'Import settings' ); ?>
            </h3>
            <p style="color:var(--ps-text-dim); font-size:14px; margin-bottom:20px; line-height:1.5;">
                <?php echo esc_html( $t['set_import_hint'] ?? 'Upload a previously exported JSON file to restore settings.' ); ?>
            </p>
            <input type="file" id="ps-import-file" accept=".json" style="display:none;">
            <div style="display:flex; flex-direction:column; gap:12px;">
                <button type="button" id="ps-import-btn" class="parcelselector-btn parcelselector-btn-secondary" style="width:100%;">
                    <?php echo esc_html( $t['set_import_btn'] ?? 'Choose file...' ); ?>
                </button>
                <span id="ps-import-filename" style="color:var(--ps-text-dim); font-size:13px; text-align:center;"></span>
            </div>
            <div id="ps-import-result" style="margin-top:12px; display:none;"></div>
        </div>

    </div>
    </div><!-- end hidden import/export -->

    <?php
    $ps_settings_js = 'jQuery(document).ready(function($) {
        $("#ps-export-btn").on("click", function() {
            $.post(ajaxurl, {
                action: "ps_export_settings",
                nonce:  ' . wp_json_encode( wp_create_nonce('parcselect_export_settings') ) . '
            }, function(response) {
                if (!response.success) {
                    alert("Export failed: " + (response.data && response.data.message ? response.data.message : "Unknown error"));
                    return;
                }
                var json = JSON.stringify(response.data.settings, null, 2);
                var blob = new Blob([json], { type: "application/json" });
                var url  = URL.createObjectURL(blob);
                var a    = document.createElement("a");
                a.href     = url;
                a.download = "parcelselector-settings-" + response.data.date + ".json";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            });
        });
        $("#ps-import-btn").on("click", function() {
            $("#ps-import-file").trigger("click");
        });
        $("#ps-import-file").on("change", function() {
            var file = this.files[0];
            if (!file) return;
            $("#ps-import-filename").text(file.name);
            var reader = new FileReader();
            reader.onload = function(e) {
                var json;
                try { json = JSON.parse(e.target.result); } catch (err) { showImportResult("error", "Invalid JSON file."); return; }
                if (!json || typeof json !== "object") { showImportResult("error", "File is not a valid settings export."); return; }
                $.post(ajaxurl, {
                    action:   "ps_import_settings",
                    nonce:    ' . wp_json_encode( wp_create_nonce('parcselect_import_settings') ) . ',
                    settings: JSON.stringify(json)
                }, function(response) {
                    if (response.success) {
                        showImportResult("success", (response.data && response.data.message ? response.data.message : "Settings imported!"));
                        setTimeout(function() { location.reload(); }, 1500);
                    } else {
                        showImportResult("error", response.data && response.data.message ? response.data.message : "Import failed.");
                    }
                }).fail(function() { showImportResult("error", "AJAX error."); });
            };
            reader.readAsText(file);
        });
        function showImportResult(type, msg) {
            var $r = $("#ps-import-result");
            var ok = type === "success";
            $r.html((ok ? "\u2705 " : "\u274C ") + msg)
              .css({ background: ok ? "#f0fdf4" : "#fff2f2", border: "1px solid " + (ok ? "#22c55e" : "#e74c3c"), padding: "10px 14px", borderRadius: "4px", color: ok ? "#166534" : "#c0392b" })
              .show();
        }
    });';
    wp_add_inline_script( 'parcselect-admin-premium-js', $ps_settings_js );
}
}
