<?php

if ( ! defined('ABSPATH') ) {
    require_once dirname(__DIR__, 4) . '/wp-load.php';
}

do_action('acf/init');

$data = json_decode(file_get_contents(__DIR__ . '/migration-data.json'), true);
if (!$data) {
    fwrite(STDERR, "migration-data.json invalid\n");
    exit(1);
}

$routes = [
    'home' => 'accueil',
    'municipality' => 'municipalite',
    'mayor' => 'mot-du-maire',
    'council' => 'conseil-municipal',
    'services' => 'services-municipaux-et-publics',
    'documents' => 'documents-importants',
    'community' => 'notre-communaute',
    'communityPhotos' => 'album-photos-communaute',
    'activitiesPhotos' => 'album-photos-activites',
    'developmentPlan' => 'plan-de-developpement',
    'townMap' => 'carte-de-la-ville',
    'businesses' => 'entreprises-locales',
    'events' => 'evenements',
    'publicNotices' => 'avis-publics',
    'minutes' => 'proces-verbaux',
    'newsletters' => 'bulletins',
];

function lval($value, $lang, $fallback = '') {
    if (is_array($value) && isset($value[$lang])) return $value[$lang];
    if (is_string($value)) return $value;
    return $fallback;
}

function rich($value, $lang) {
    $v = lval($value, $lang);
    return is_string($v) ? $v : '';
}

function flatten_items($items): array {
    $out = [];
    foreach ((array) $items as $item) {
        if (!is_array($item)) continue;
        $label_fr = $item['name'] ?? lval($item['title'] ?? $item['label'] ?? '', 'fr');
        $label_en = $item['name'] ?? lval($item['title'] ?? $item['label'] ?? '', 'en');
        $out[] = [
            'label_fr' => is_string($label_fr) ? $label_fr : '',
            'label_en' => is_string($label_en) ? $label_en : '',
            'content_fr' => wp_json_encode($item, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'content_en' => wp_json_encode($item, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ];
    }
    return $out;
}

function map_section(array $section): array {
    $layout = str_replace('-', '_', $section['type'] ?? 'wysiwyg');
    $row = ['acf_fc_layout' => $layout];
    if (isset($section['title'])) {
        $row['title_fr'] = lval($section['title'], 'fr');
        $row['title_en'] = lval($section['title'], 'en');
    }
    if (isset($section['body'])) {
        $row['body_fr'] = rich($section['body'], 'fr');
        $row['body_en'] = rich($section['body'], 'en');
    }
    if (isset($section['intro'])) {
        $row['body_fr'] = trim(($row['body_fr'] ?? '') . "\n" . rich($section['intro'], 'fr'));
        $row['body_en'] = trim(($row['body_en'] ?? '') . "\n" . rich($section['intro'], 'en'));
    }
    if (isset($section['subtitle'])) {
        $row['body_fr'] = trim(($row['body_fr'] ?? '') . "\n" . rich($section['subtitle'], 'fr'));
        $row['body_en'] = trim(($row['body_en'] ?? '') . "\n" . rich($section['subtitle'], 'en'));
    }
    if ($layout === 'hero_carousel') $row['slides'] = flatten_items($section['slides'] ?? []);
    if ($layout === 'services_list') $row['services'] = flatten_items($section['services'] ?? []);
    if ($layout === 'events_list') $row['events'] = flatten_items($section['events'] ?? []);
    if ($layout === 'businesses_list') $row['categories'] = flatten_items($section['categories'] ?? []);
    if ($layout === 'council_grid') $row['members'] = flatten_items($section['members'] ?? []);
    if ($layout === 'documents_list') $row['groups'] = flatten_items($section['groups'] ?? []);
    if ($layout === 'photo_gallery') {
        $row['title_fr'] = $row['title_fr'] ?? '';
        $row['title_en'] = $row['title_en'] ?? '';
        $row['_source_photos_json'] = wp_json_encode($section['photos'] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    if ($layout === 'pdf_embed') {
        $row['_source_pdf_href'] = $section['href'] ?? '';
    }
    $row['_source_json'] = wp_json_encode($section, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    return $row;
}

$updated = 0;
foreach ($data['pages'] as $key => $page) {
    if (!isset($routes[$key])) continue;
    $post = get_page_by_path($routes[$key], OBJECT, 'page');
    if (!$post) continue;

    $sections = array_map('map_section', $page['sections'] ?? []);
    update_field('sections', $sections, $post->ID);
    update_post_meta($post->ID, '_react_sections_json', wp_json_encode($page['sections'] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    update_post_meta($post->ID, '_seo_title_fr', lval($page['seo']['title'] ?? '', 'fr'));
    update_post_meta($post->ID, '_seo_title_en', lval($page['seo']['title'] ?? '', 'en'));
    update_post_meta($post->ID, '_seo_description_fr', lval($page['seo']['description'] ?? '', 'fr'));
    update_post_meta($post->ID, '_seo_description_en', lval($page['seo']['description'] ?? '', 'en'));
    wp_update_post(['ID' => $post->ID, 'post_excerpt' => lval($page['seo']['description'] ?? '', 'fr')]);
    $updated++;
}

update_field('municipality_name_fr', $data['siteSettings']['municipality']['name']['fr'] ?? '', 'option');
update_field('municipality_name_en', $data['siteSettings']['municipality']['name']['en'] ?? '', 'option');
update_field('phone', $data['siteSettings']['contact']['phone'] ?? '', 'option');
update_field('email', $data['siteSettings']['contact']['email'] ?? '', 'option');
update_field('address_fr', $data['siteSettings']['contact']['address']['fr'] ?? '', 'option');
update_field('address_en', $data['siteSettings']['contact']['address']['en'] ?? '', 'option');
update_field('hours_fr', $data['siteSettings']['contact']['hours']['fr'] ?? '', 'option');
update_field('hours_en', $data['siteSettings']['contact']['hours']['en'] ?? '', 'option');
update_field('facebook_url', $data['siteSettings']['social']['facebook'] ?? '', 'option');

function upsert_post_by_title(string $type, string $title, array $args = []): int {
    $query = new WP_Query([
        'post_type' => $type,
        'title' => $title,
        'post_status' => 'any',
        'posts_per_page' => 1,
        'fields' => 'ids',
        'no_found_rows' => true,
    ]);
    $existing_id = $query->posts[0] ?? 0;
    $postarr = array_merge([
        'post_type' => $type,
        'post_status' => 'publish',
        'post_title' => $title,
    ], $args);
    if ($existing_id) {
        $postarr['ID'] = $existing_id;
        wp_update_post($postarr);
        return (int) $existing_id;
    }
    return (int) wp_insert_post($postarr);
}

$business_count = 0;
foreach (($data['pages']['businesses']['sections'] ?? []) as $section) {
    if (($section['type'] ?? '') !== 'businesses-list') continue;
    foreach (($section['categories'] ?? []) as $category) {
        foreach (($category['businesses'] ?? []) as $business) {
            $id = upsert_post_by_title('local_business', $business['name'] ?? 'Entreprise', [
                'post_content' => lval($business['description'] ?? '', 'fr'),
                'post_excerpt' => lval($business['description'] ?? '', 'en'),
            ]);
            update_post_meta($id, 'phone', $business['phone'] ?? '');
            update_post_meta($id, 'email', $business['email'] ?? '');
            update_post_meta($id, 'website', $business['website'] ?? '');
            update_post_meta($id, 'address', $business['address'] ?? '');
            update_post_meta($id, '_source_json', wp_json_encode($business, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $business_count++;
        }
    }
}

$event_count = 0;
foreach (($data['pages']['home']['sections'] ?? []) as $section) {
    if (($section['type'] ?? '') !== 'events-list') continue;
    foreach (($section['events'] ?? []) as $event) {
        $id = upsert_post_by_title('event', lval($event['title'] ?? '', 'fr', 'Événement'), [
            'post_content' => lval($event['description'] ?? '', 'fr'),
            'post_excerpt' => lval($event['description'] ?? '', 'en'),
        ]);
        update_post_meta($id, 'event_date', $event['date'] ?? '');
        update_post_meta($id, 'location_fr', lval($event['location'] ?? '', 'fr'));
        update_post_meta($id, 'location_en', lval($event['location'] ?? '', 'en'));
        update_post_meta($id, '_source_json', wp_json_encode($event, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $event_count++;
    }
}
foreach (($data['pages']['events']['sections'] ?? []) as $section) {
    if (($section['type'] ?? '') !== 'text-intro') continue;
    $title = lval($section['title'] ?? '', 'fr');
    if (!$title) continue;
    $id = upsert_post_by_title('event', $title, [
        'post_content' => lval($section['body'] ?? '', 'fr'),
        'post_excerpt' => lval($section['body'] ?? '', 'en'),
    ]);
    update_post_meta($id, '_source_json', wp_json_encode($section, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    $event_count++;
}

$gallery_count = 0;
foreach (['communityPhotos' => 'Album photos communauté', 'activitiesPhotos' => 'Album photos activités'] as $page_key => $fallback_title) {
    foreach (($data['pages'][$page_key]['sections'] ?? []) as $section) {
        if (($section['type'] ?? '') !== 'photo-gallery') continue;
        $section_title = lval($section['title'] ?? '', 'fr');
        $title = 'Galerie - ' . ($section_title ?: $fallback_title);
        $id = upsert_post_by_title('gallery', $title, ['post_content' => lval($section['intro'] ?? '', 'fr')]);
        update_post_meta($id, '_source_photos_json', wp_json_encode($section['photos'] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        update_post_meta($id, '_source_json', wp_json_encode($section, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $gallery_count++;
    }
}

echo "updated_pages={$updated}\n";
echo "businesses={$business_count}\n";
echo "events={$event_count}\n";
echo "galleries={$gallery_count}\n";
