<?php

/**
 * Plugin Name: Importer for VWE
 * Text Domain: importer-for-vwe
 * Description: Receive vehicle information from VWE (via eigenwebsite.dv.nl) via a REST endpoint and automatically create Custom Posts
 * Version: 1.0.5.1
 * Author: DLK Online Media
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
add_action( 'admin_enqueue_scripts', function ( $hook ) {
    // Alleen op jouw CPT schermen, bv. "occasion"
    global $post_type;
    if ( $post_type !== impofovw_get_cpt_name() ) {
        return;
    }
    // CSS
    wp_enqueue_style(
        'importer-for-vwe-admin',
        plugin_dir_url( __FILE__ ) . 'assets/css/admin.css',
        [],
        '1.0'
    );
    // JS
    wp_enqueue_script(
        'importer-for-vwe-admin',
        plugin_dir_url( __FILE__ ) . 'assets/js/admin.js',
        ['jquery'],
        '1.0',
        true
    );
} );
function impofovw_enqueue_assets() {
    wp_register_style(
        'impofovw-gallery',
        plugin_dir_url( __FILE__ ) . 'assets/css/shortcode.css',
        [],
        filemtime( plugin_dir_path( __FILE__ ) . 'assets/css/shortcode.css' )
    );
}

add_action( 'wp_enqueue_scripts', 'impofovw_enqueue_assets' );
if ( function_exists( 'impofovw_fs' ) ) {
    impofovw_fs()->set_basename( false, __FILE__ );
} else {
    /**
     * DO NOT REMOVE THIS IF, IT IS ESSENTIAL FOR THE
     * `function_exists` CALL ABOVE TO PROPERLY WORK.
     */
    if ( !function_exists( 'impofovw_fs' ) ) {
        // Create a helper function for easy SDK access.
        function impofovw_fs() {
            global $impofovw_fs;
            if ( !isset( $impofovw_fs ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
                $impofovw_fs = fs_dynamic_init( array(
                    'id'               => '20544',
                    'slug'             => 'importer-for-vwe',
                    'premium_slug'     => 'importer-for-vwe-pro',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_1b55934b935ff83c1b7ea02712c72',
                    'is_premium'       => false,
                    'premium_suffix'   => 'Pro',
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'menu'             => array(
                        'slug'    => 'importer-for-vwe-settings',
                        'support' => false,
                    ),
                    'currency'         => 'EUR',
                    'is_org_compliant' => true,
                    'is_live'          => true,
                ) );
            }
            return $impofovw_fs;
        }

        // Init Freemius.
        impofovw_fs();
        // Signal that SDK was initiated.
        do_action( 'impofovw_fs_loaded' );
    }
    // ... Your plugin's main file logic ...
    // --- CPT naam ophalen uit settings ---
    function impofovw_get_cpt_name() {
        return get_option( 'impofovw_cpt_name', false );
        // false = nog niet ingesteld
    }

    require_once plugin_dir_path( __FILE__ ) . 'includes/register-cpt-tax-meta.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/handle-xml-import.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/shortcode.php';
    // --- 4. Meta box voor occasions ---
    add_action( 'add_meta_boxes', function () {
        $cpt = impofovw_get_cpt_name();
        add_meta_box(
            'impofovw_meta_box',
            'VWE Meta Data',
            'impofovw_render_meta_box',
            $cpt,
            'side',
            'high'
        );
    } );
    function impofovw_render_meta_box(  $post  ) {
        $meta_keys = [
            'impofovw_voertuignr_hexon'     => 'Voertuignr Hexon',
            'impofovw_type'                 => 'Type',
            'impofovw_prijs'                => 'Prijs',
            'impofovw_tellerstand'          => 'Tellerstand',
            'impofovw_tellerstand_eenheid'  => 'Tellerstand eenheid (M = mijl, K = kilometer)',
            'impofovw_bouwjaar'             => 'Bouwjaar',
            'impofovw_motorvermogen'        => 'Motervermogen (Pk)',
            'impofovw_massa'                => 'Massa (Kg)',
            'impofovw_topsnelheid'          => 'Topsnelheid (km/u)',
            'impofovw_gemiddeld_verbruik'   => 'Gemiddel verbruik (L/100km)',
            'impofovw_invoerdatum'          => 'Invoerdatum',
            'impofovw_kenteken'             => 'Kenteken',
            'impofovw_uitrustingsniveau'    => 'Uitrustingsniveau',
            'impofovw_toevoeging'           => 'Toevoeging',
            'impofovw_aantal_deuren'        => 'Aantal deuren',
            'impofovw_aantal_versnellingen' => 'Aantal versnellingen',
            'impofovw_nieuw_voertuig'       => 'Nieuw voertuig (ja/nee)',
            'impofovw_laksoort'             => 'Laksoort',
            'impofovw_btw_marge'            => 'BTW/Marge',
            'impofovw_basisinterieurkleur'  => 'Basisinterieurkleur',
            'impofovw_interieurkleur'       => 'Interieurkleur)',
            'impofovw_aantal_zitplaatsen'   => 'Aantal zitplaatsen',
            'impofovw_bekleding'            => 'Bekleding',
            'impofovw_verkocht'             => 'Verkocht',
        ];
        echo '<div style="font-size:13px;">';
        foreach ( $meta_keys as $key => $label ) {
            $value = get_post_meta( $post->ID, $key, true );
            echo '<p><strong>' . esc_html( $label ) . ':</strong> ' . esc_html( $value ) . '</p>';
        }
        echo '</div>';
    }

    // --- REST endpoint registreren ---
    add_action( 'rest_api_init', 'impofovw_register_routes' );
    function impofovw_register_routes() {
        register_rest_route( 'vwe/v1', '/import/', [
            'methods'             => 'POST',
            'callback'            => 'impofovw_handle_xml_import',
            'permission_callback' => 'impofovw_check_user_authentication',
        ] );
    }

    // --- Authenticatie REST ---
    function impofovw_check_user_authentication() {
        return current_user_can( 'edit_posts' );
    }

    // --- Admin menu & settings pagina ---
    add_action( 'admin_menu', function () {
        // Hoofdmenu
        add_menu_page(
            'Importer for VWE',
            // Page title
            'Importer for VWE',
            // Menu title
            'manage_options',
            // Capability
            'importer-for-vwe-settings',
            // Slug (ook eerste submenu)
            'impofovw_render_settings_page',
            // Callback
            plugin_dir_url( __FILE__ ) . 'assets/logo.svg'
        );
        // Submenu "Instellingen"
        add_submenu_page(
            'importer-for-vwe-settings',
            // Parent slug (zelfde als hoofdmenu)
            'Instellingen',
            // Page title
            'Instellingen',
            // Menu title
            'manage_options',
            // Capability
            'importer-for-vwe-settings',
            // Slug
            'impofovw_render_settings_page'
        );
    } );
    // --- Settings opslaan en CPT migratie ---
    function impofovw_save_settings() {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        if ( isset( $_POST['impofovw_cpt_name'] ) ) {
            check_admin_referer( 'impofovw_save_settings' );
            $new_cpt_raw = wp_unslash( $_POST['impofovw_cpt_name'] );
            $new_cpt = sanitize_key( $new_cpt_raw );
            // Check of slug geldig is
            if ( $new_cpt !== $new_cpt_raw ) {
                add_settings_error(
                    'impofovw_messages',
                    'impofovw_invalid_slug',
                    'De opgegeven CPT slug bevat ongeldige tekens. Alleen kleine letters, cijfers en underscores zijn toegestaan.',
                    'error'
                );
                return;
            }
            $old_cpt = get_option( 'impofovw_cpt_name', false );
            // Controle of CPT slug al gebruikt wordt door andere plugin/theme
            if ( post_type_exists( $new_cpt ) && $new_cpt !== $old_cpt ) {
                add_settings_error(
                    'impofovw_messages',
                    'impofovw_cpt_exists',
                    'Fout: De gekozen CPT-slug "' . esc_html( $new_cpt ) . '" wordt al gebruikt door een andere plugin of theme. Kies een andere naam.',
                    'error'
                );
                return;
            }
            update_option( 'impofovw_cpt_name', $new_cpt );
            // Alleen acties uitvoeren als slug is gewijzigd
            if ( $new_cpt !== $old_cpt ) {
                // CPT registreren
                impofovw_register_custom_post_type( $new_cpt );
                // Bestaande posts migreren
                if ( $old_cpt && post_type_exists( $old_cpt ) ) {
                    global $wpdb;
                    $updated = $wpdb->update( $wpdb->posts, [
                        'post_type' => $new_cpt,
                    ], [
                        'post_type' => $old_cpt,
                    ] );
                    if ( $updated ) {
                        // Cache flush zodat WP niet met verouderde objecten blijft werken
                        wp_cache_flush();
                    }
                }
                // Flush permalinks
                flush_rewrite_rules();
            }
            // Toon success message
            add_settings_error(
                'impofovw_messages',
                'impofovw_cpt_saved',
                'Instellingen opgeslagen en CPT bijgewerkt! Vernieuw de pagina om de wijzigen te zien.',
                'updated'
            );
        }
    }

    // --- Settings pagina renderen ---
    function impofovw_render_settings_page() {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        // Verwerk settings opslaan
        if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
            // verwerk POST
            impofovw_save_settings();
        }
        // Toon eventuele messages
        settings_errors( 'impofovw_messages' );
        $cpt_name = impofovw_get_cpt_name();
        ?>
    <div class="wrap">
        <h1>Importer for VWE Settings</h1>
        <form method="post">
            <?php 
        wp_nonce_field( 'impofovw_save_settings' );
        ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">Custom Post Type naam</th>
                    <td>
                        <input type="text" name="impofovw_cpt_name" value="<?php 
        echo esc_attr( $cpt_name );
        ?>" />
                        <p class="description">De slug voor het custom post type dat gebruikt wordt voor VWE-imports.</p>
                    </td>
                </tr>
            </table>
            <?php 
        submit_button();
        ?>
        </form>

        <h2>Endpoint</h2>
        <input type="text" 
               value="<?php 
        echo esc_url( rest_url( 'vwe/v1/import' ) );
        ?>" 
               readonly 
               style="width: 100%; background: #f5f5f5; color: #333;">
        <p class="description">Gebruik dit adres om occasions via XML te importeren.</p>
		
		<?php 
        ?>
	
	<div class="wrap">
    <h2><?php 
        esc_html_e( 'Handleiding', 'importer-for-vwe' );
        ?></h2>
	
	<?php 
        $url = "https://www.dlkonlinemedia.com/importer-for-vwe/";
        echo '<a class="button button-primary" href="' . esc_url( $url ) . '" target="_blank" rel="noopener">' . esc_html__( 'Handleiding', 'importer-for-vwe' ) . '</a>';
        ?>
	</div>
	
	<div class="wrap">
    <h2><?php 
        esc_html_e( 'Pro functies', 'importer-for-vwe' );
        ?></h2>

    <ul>
        <li>
            <?php 
        esc_html_e( 'Wijzigen op VWE automatisch verwerken', 'importer-for-vwe' );
        ?>
            <?php 
        if ( !impofovw_fs()->can_use_premium_code() ) {
            ?>
                <span style="color:#fff; background:#ff4b4b; padding:2px 5px; border-radius:3px; font-size:12px;">Pro</span>
            <?php 
        }
        ?>
        </li>

        <li>
            <?php 
        esc_html_e( 'Verwijderingen op VWE automatisch verwerken', 'importer-for-vwe' );
        ?>
            <?php 
        if ( !impofovw_fs()->can_use_premium_code() ) {
            ?>
                <span style="color:#fff; background:#ff4b4b; padding:2px 5px; border-radius:3px; font-size:12px;">Pro</span>
            <?php 
        }
        ?>
        </li>
		
		<li>
            <?php 
        esc_html_e( 'Importeer alle afbeeldingen', 'importer-for-vwe' );
        ?>
            <?php 
        if ( !impofovw_fs()->can_use_premium_code() ) {
            ?>
                <span style="color:#fff; background:#ff4b4b; padding:2px 5px; border-radius:3px; font-size:12px;">Pro</span>
            <?php 
        }
        ?>
        </li>
		
		<li>
            <?php 
        esc_html_e( 'Extra meta data (voertuigsoort)', 'importer-for-vwe' );
        ?>
            <?php 
        if ( !impofovw_fs()->can_use_premium_code() ) {
            ?>
                <span style="color:#fff; background:#ff4b4b; padding:2px 5px; border-radius:3px; font-size:12px;">Pro</span>
            <?php 
        }
        ?>
        </li>

        <li>
            <?php 
        esc_html_e( 'Licentiebeheer en automatische updates via Freemius', 'importer-for-vwe' );
        ?>
            <?php 
        if ( !impofovw_fs()->can_use_premium_code() ) {
            ?>
                <span style="color:#fff; background:#ff4b4b; padding:2px 5px; border-radius:3px; font-size:12px;">Pro</span>
            <?php 
        }
        ?>
        </li>
		
		<li>
            <?php 
        esc_html_e( 'Premium support', 'importer-for-vwe' );
        ?>
            <?php 
        if ( !impofovw_fs()->can_use_premium_code() ) {
            ?>
                <span style="color:#fff; background:#ff4b4b; padding:2px 5px; border-radius:3px; font-size:12px;">Pro</span>
            <?php 
        }
        ?>
        </li>
    </ul>

    <?php 
        if ( !impofovw_fs()->can_use_premium_code() ) {
            ?>
        <p>
            <strong><?php 
            esc_html_e( 'Om deze functies te activeren, upgrade naar Pro!', 'importer-for-vwe' );
            ?></strong>
        </p>
        <p>
		<?php 
            $checkout = "https://www.dlkonlinemedia.com/importer-for-vwe/";
            echo '<a class="button button-primary" href="' . esc_url( $checkout ) . '" target="_blank" rel="noopener">' . esc_html__( 'Upgrade naar Pro', 'importer-for-vwe' ) . '</a>';
            ?>
        </p>
    <?php 
        } else {
            ?>
        <p style="color:green;">
            <?php 
            esc_html_e( 'Pro functies zijn actief ✅', 'importer-for-vwe' );
            ?>
        </p>
    <?php 
        }
        ?>
	
</div>
	

    </div>
    <?php 
    }

    // --- Voeg Settings link toe op de plugins-pagina ---
    add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), function ( $links ) {
        $settings_link = '<a href="' . admin_url( 'admin.php?page=importer-for-vwe-settings' ) . '">Instellingen</a>';
        array_unshift( $links, $settings_link );
        return $links;
    } );
}