<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Beveiliging tegen direct toegang
function impofovw_handle_xml_import(  WP_REST_Request $request  ) {
    $body = $request->get_body();
    if ( empty( $body ) ) {
        return new WP_REST_Response([
            'message' => 'Geen data ontvangen',
        ], 400);
    }
    // XML inlezen
    libxml_use_internal_errors( true );
    $xml = simplexml_load_string( $body );
    if ( $xml === false ) {
        return new WP_REST_Response([
            'message' => 'Ongeldige XML',
        ], 400);
    }
    // Gegevens uit XML halen
    $voertuignr_hexon = (string) $xml->voertuignr_hexon;
    if ( empty( $voertuignr_hexon ) ) {
        return new WP_REST_Response([
            'message' => 'Onvoldoende data in XML',
        ], 400);
    }
    $actie = (string) $xml['actie'];
    switch ( $actie ) {
        case 'add':
            impofovw_check_vehicle( $xml );
            if ( impofovw_post_exists_by_meta( $voertuignr_hexon ) ) {
                // Occasion bestaat al,
                return new WP_REST_Response([
                    'message' => 'Occasion bestaat al',
                    'id'      => $voertuignr_hexon,
                ], 400);
            }
            $post_id = impofovw_createOccasion( $xml );
            if ( $post_id ) {
                print "1";
                // ✅ success
                return;
            } else {
                return new WP_REST_Response([
                    'message' => 'Fout bij aanmaken van post',
                ], 500);
            }
            break;
        case 'change':
            return new WP_REST_Response([
                'message' => 'Upgrade naar Importer for VWE Pro',
            ], 500);
            break;
        case 'delete':
            return new WP_REST_Response([
                'message' => 'Upgrade naar Importer for VWE Pro',
            ], 500);
            break;
        default:
            print "0";
            wp_die();
    }
}

function impofovw_check_vehicle(  $xml  ) {
    if ( empty( $xml->afbeeldingen ) ) {
        // Foutmelding teruggeven aan server van Hexon
        print "Op de eigen website zijn alleen voertuigen met foto toegestaan";
        exit;
    }
}

function impofovw_post_exists_by_meta(  $meta_value  ) {
    $existing = get_posts( [
        'post_type'   => get_option( 'impofovw_cpt_name', 'occasions' ),
        'meta_key'    => 'impofovw_voertuignr_hexon',
        'meta_value'  => $meta_value,
        'post_status' => 'any',
        'numberposts' => 1,
    ] );
    return ( !empty( $existing ) ? $existing[0]->ID : false );
}

function impofovw_get_post_id_by_meta(  $meta_value  ) {
    $posts = get_posts( [
        'post_type'   => get_option( 'impofovw_cpt_name', 'occasions' ),
        'meta_key'    => 'impofovw_voertuignr_hexon',
        'meta_value'  => $meta_value,
        'post_status' => 'any',
        'numberposts' => 1,
    ] );
    if ( !empty( $posts ) ) {
        return $posts[0]->ID;
    }
    return false;
}

function impofovw_createOccasion(  $xml  ) {
    $uniekNummer = (string) $xml->voertuignr_hexon;
    if ( empty( $uniekNummer ) ) {
        return false;
    }
    $post_data = [
        'post_title'   => (string) $xml->merk . ' ' . (string) $xml->model,
        'post_content' => (string) $xml->opmerkingen,
        'post_type'    => get_option( 'impofovw_cpt_name', 'occasions' ),
        'post_status'  => 'publish',
    ];
    // Nieuwe aanmaken
    $post_id = wp_insert_post( $post_data );
    if ( is_wp_error( $post_id ) || !$post_id ) {
        return false;
    }
    // Repeater data opbouwen
    $repeater_data_interieur = [];
    $repeater_data_exterieur = [];
    $repeater_data_veiligheid = [];
    $repeater_data_overig = [];
    foreach ( $xml->accessoiregroepen->accessoiregroep as $accessoiregroep ) {
        $groep_naam = (string) $accessoiregroep['naam'];
        if ( trim( $groep_naam ) === "Comfort & Interieur" ) {
            foreach ( $accessoiregroep->accessoire as $accessoire ) {
                $repeater_data_interieur[] = [
                    'prioriteit'   => (int) $accessoire->prioriteit,
                    'omschrijving' => (string) $accessoire->description,
                ];
            }
        }
        if ( trim( $groep_naam ) === "Exterieur" ) {
            foreach ( $accessoiregroep->accessoire as $accessoire ) {
                $repeater_data_exterieur[] = [
                    'prioriteit'   => (int) $accessoire->prioriteit,
                    'omschrijving' => (string) $accessoire->description,
                ];
            }
        }
        if ( trim( $groep_naam ) === "Veiligheid" ) {
            foreach ( $accessoiregroep->accessoire as $accessoire ) {
                $repeater_data_veiligheid[] = [
                    'prioriteit'   => (int) $accessoire->prioriteit,
                    'omschrijving' => (string) $accessoire->description,
                ];
            }
        }
        if ( trim( $groep_naam ) === "Overig" ) {
            foreach ( $accessoiregroep->accessoire as $accessoire ) {
                $repeater_data_overig[] = [
                    'prioriteit'   => (int) $accessoire->prioriteit,
                    'omschrijving' => (string) $accessoire->description,
                ];
            }
        }
    }
    // Update repeater meta data
    update_post_meta( $post_id, 'impofovw_repeater_interieur', $repeater_data_interieur );
    update_post_meta( $post_id, 'impofovw_repeater_exterieur', $repeater_data_exterieur );
    update_post_meta( $post_id, 'impofovw_repeater_veiligheid', $repeater_data_veiligheid );
    update_post_meta( $post_id, 'impofovw_repeater_overig', $repeater_data_overig );
    if ( !empty( $xml->merk ) ) {
        wp_set_object_terms(
            $post_id,
            (string) $xml->merk,
            'impofovw_merk',
            false
        );
    }
    if ( !empty( $xml->model ) ) {
        wp_set_object_terms(
            $post_id,
            (string) $xml->model,
            'impofovw_model',
            false
        );
    }
    if ( !empty( $xml->transmissie ) ) {
        wp_set_object_terms(
            $post_id,
            (string) impofovw_enumToTransmissie( $xml->transmissie ),
            'impofovw_transmissie',
            false
        );
    }
    if ( !empty( $xml->brandstof ) ) {
        wp_set_object_terms(
            $post_id,
            (string) impofovw_enumToBrandstof( $xml->brandstof ),
            'impofovw_brandstof',
            false
        );
    }
    if ( !empty( $xml->carrosserie ) ) {
        wp_set_object_terms(
            $post_id,
            (string) $xml->carrosserie,
            'impofovw_carrosserie',
            false
        );
    }
    if ( !empty( $xml->basiskleur ) ) {
        wp_set_object_terms(
            $post_id,
            (string) $xml->basiskleur,
            'impofovw_basiskleur',
            false
        );
    }
    // Metas
    $type = (string) $xml->type;
    // Meta bijwerken
    update_post_meta( $post_id, 'impofovw_voertuignr_hexon', $uniekNummer );
    update_post_meta( $post_id, 'impofovw_type', $type );
    $price_data = impofovw_extract_price_from_xml( $xml );
    update_post_meta( $post_id, 'impofovw_prijs', (float) $price_data );
    update_post_meta( $post_id, 'impofovw_tellerstand', (int) $xml->tellerstand );
    update_post_meta( $post_id, 'impofovw_tellerstand_eenheid', (string) $xml->tellerstand['eenheid'] );
    update_post_meta( $post_id, 'impofovw_bouwjaar', (int) $xml->bouwjaar );
    update_post_meta( $post_id, 'impofovw_opmerkingen', (string) $xml->opmerkingen );
    update_post_meta( $post_id, 'impofovw_motorvermogen', (string) $xml->vermogen_motor_pk );
    update_post_meta( $post_id, 'impofovw_massa', (float) $xml->massa );
    update_post_meta( $post_id, 'impofovw_topsnelheid', (float) $xml->topsnelheid );
    update_post_meta( $post_id, 'impofovw_gemiddeld_verbruik', (string) $xml->gemiddeld_verbruik );
    update_post_meta( $post_id, 'impofovw_invoerdatum', (string) $xml->invoerdatum );
    update_post_meta( $post_id, 'impofovw_kenteken', (string) $xml->kenteken );
    update_post_meta( $post_id, 'impofovw_uitrustingsniveau', (string) $xml->uitrustingsniveau );
    update_post_meta( $post_id, 'impofovw_toevoeging', (string) $xml->toevoeging );
    update_post_meta( $post_id, 'impofovw_aantal_deuren', (int) $xml->aantal_deuren );
    update_post_meta( $post_id, 'impofovw_aantal_versnellingen', (int) $xml->aantal_versnellingen );
    update_post_meta( $post_id, 'impofovw_nieuw_voertuig', (string) impofovw_enumToJaNee( $xml->nieuw_voertuig ) );
    update_post_meta( $post_id, 'impofovw_laksoort', (string) $xml->laksoort );
    update_post_meta( $post_id, 'impofovw_btw_marge', (string) impofovw_enumToBTWMarge( $xml->btw_marge ) );
    update_post_meta( $post_id, 'impofovw_basisinterieurkleur', (string) $xml->basisinterieurkleur );
    update_post_meta( $post_id, 'impofovw_interieurkleur', (string) $xml->interieurkleur );
    update_post_meta( $post_id, 'impofovw_aantal_zitplaatsen', (int) $xml->aantal_zitplaatsen );
    update_post_meta( $post_id, 'impofovw_bekleding', (string) $xml->bekleding );
    update_post_meta( $post_id, 'impofovw_verkocht', (string) impofovw_enumToJaNee( $xml->verkocht ) );
    // Foto's ophalen
    $gallery_urls = impofovw_extract_image_urls_from_xml( $xml );
    if ( !empty( $gallery_urls ) ) {
        impofovw_import_fotos( $post_id, $gallery_urls );
    }
    return $post_id;
}

function impofovw_import_fotos(  $post_id, $foto_urls  ) {
    if ( !is_array( $foto_urls ) || empty( $foto_urls ) ) {
        return;
    }
    $new_ids = [];
    $used_urls = [];
    foreach ( $foto_urls as $index => $url ) {
        $attachment_id = impofovw_media_sideload_image( $url, $post_id );
        if ( $attachment_id ) {
            $new_ids[] = $attachment_id;
            $used_urls[] = esc_url_raw( $url );
            if ( $index === 0 ) {
                set_post_thumbnail( $post_id, $attachment_id );
            }
        }
    }
    // Alle oude foto’s ophalen die niet meer in de feed staan → verwijderen
    $old_ids = get_post_meta( $post_id, 'impofovw_occasion_fotos', true );
    if ( !empty( $old_ids ) ) {
        foreach ( $old_ids as $old_id ) {
            $source = get_post_meta( $old_id, 'impofovw_source_url', true );
            if ( !in_array( $source, $used_urls ) ) {
                wp_delete_attachment( $old_id, true );
                // fysiek verwijderen
            }
        }
    }
    update_post_meta( $post_id, 'impofovw_occasion_fotos', $new_ids );
    // extra meta met comma string
    update_post_meta( $post_id, 'impofovw_occasion_fotos_csv', implode( ',', $new_ids ) );
}

function impofovw_media_sideload_image(  $url, $post_id  ) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';
    // Bestaat deze foto al? (zoek op _source_url meta)
    $existing = get_posts( [
        'post_type'      => 'attachment',
        'meta_key'       => 'impofovw_source_url',
        'meta_value'     => esc_url_raw( $url ),
        'post_parent'    => $post_id,
        'posts_per_page' => 1,
        'fields'         => 'ids',
    ] );
    if ( !empty( $existing ) ) {
        return $existing[0];
        // al bestaand attachment
    }
    // Bestand tijdelijk ophalen
    $tmp = download_url( $url );
    if ( is_wp_error( $tmp ) ) {
        return false;
    }
    $file_array = [
        'name'     => basename( wp_parse_url( $url, PHP_URL_PATH ) ),
        'tmp_name' => $tmp,
    ];
    $id = media_handle_sideload( $file_array, $post_id );
    if ( is_wp_error( $id ) ) {
        @wp_delete_file( $file_array['tmp_name'] );
        return false;
    }
    // Bron-URL opslaan
    update_post_meta( $id, 'impofovw_source_url', esc_url_raw( $url ) );
    return $id;
}

function impofovw_extract_image_urls_from_xml(  $xml  ) {
    $image_urls = [];
    if ( !empty( $xml->afbeeldingen->afbeelding ) ) {
        foreach ( $xml->afbeeldingen->afbeelding as $afbeelding ) {
            $url = (string) $afbeelding->url;
            if ( filter_var( $url, FILTER_VALIDATE_URL ) ) {
                $image_urls[] = $url;
            }
        }
    }
    return ( !empty( $image_urls ) ? [$image_urls[0]] : [] );
}

function impofovw_enumToTransmissie(  $enum  ) {
    switch ( (string) $enum ) {
        case 'A':
            return 'Automaat';
            break;
        case 'H':
            return 'Handgeschakeld';
            break;
        case 'S':
            return 'Semi-automaat';
            break;
        case 'C':
            return 'CVT (Continu Variabele Transmissie)';
            break;
    }
    return 'Onbekend';
}

function impofovw_enumToBrandstof(  $enum  ) {
    switch ( (string) $enum ) {
        case 'B':
            return 'Benzine';
            break;
        case 'D':
            return 'Diesel';
            break;
        case 'L':
            return 'LPG / Gas';
            break;
        case '3':
            return 'LPG G3';
            break;
        case 'E':
            return 'Elektrisch';
            break;
        case "B,E":
            return 'Benzine / Elektrisch';
            break;
        case "D,E":
            return 'Diesel / Elektrisch';
            break;
        case 'H':
            return 'Hybride';
            break;
        case 'C':
            return 'Cyrogeen';
            break;
        case 'W':
            return 'Waterstof';
            break;
        case 'O':
            return 'Overig';
            break;
    }
}

function impofovw_enumToBTWMarge(  $enum  ) {
    switch ( (string) $enum ) {
        case 'B':
            return 'BTW';
            break;
        case 'M':
            return 'Marge';
            break;
        case '':
            return 'Onbekend';
            break;
    }
}

function impofovw_enumToJaNee(  $enum  ) {
    switch ( (string) $enum ) {
        case 'j':
            return 'Ja';
            break;
        case 'n':
            return 'Nee';
            break;
    }
    return 'Onebekend';
}

function impofovw_extract_price_from_xml(  $xml  ) {
    $price_data = null;
    if ( isset( $xml->verkoopprijs_particulier->prijzen->prijs ) ) {
        // Haal het bedrag en munteenheid op
        $prijs_data = $xml->verkoopprijs_particulier->prijzen->prijs;
        $bedrag = (float) $prijs_data->bedrag;
        $munteenheid = (string) $prijs_data->munteenheid;
        // Controleer of de waarde geldig is
        if ( $bedrag > 0 && !empty( $munteenheid ) ) {
            $price_data = $bedrag;
        }
    }
    // Als er geen meerdere prijzen zijn, controleer dan of er een enkele prijs buiten de prijzen-tag zit
    if ( empty( $price_data ) && isset( $xml->verkoopprijs_particulier->prijs ) ) {
        // Een enkele prijs
        $prijs = $xml->verkoopprijs_particulier->prijs;
        $bedrag = (float) $prijs->bedrag;
        $munteenheid = (string) $prijs->munteenheid;
        if ( $bedrag > 0 && !empty( $munteenheid ) ) {
            $price_data = $bedrag;
        }
    }
    return $price_data;
}
