<?php
/**
 * Plugin Name: TEC → Events Manager Migration
 * Description: Auto migration of The Events Calendar to Events Manager.
 * Version: 1.0
 */

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

class TEC_To_EM_Migration {

    const DRY_RUN = false;
    const LOG_FILE = WP_CONTENT_DIR . '/tec-em-migration.log';

    public function __construct() {
        add_action('admin_menu', [$this, 'add_admin_page']);
    }

    public function add_admin_page() {
        add_menu_page(
            'Migration TEC → EM',
            'TEC → EM',
            'manage_options',
            'tec-em-migration',
            [$this, 'admin_page']
        );
    }

    public function admin_page() {
        if (isset($_POST['run_migration'])) {
            $this->log("=== START MIGRATION ===");
            $this->migrate_events();
            $this->log("=== END MIGRATION ===");
            echo "<div class='updated'><p>Migration finished. See log file.</p></div>";
        }

        echo '<h1>Migration TEC → Events Manager</h1>';
        echo '<form method="post">';
        echo '<p><strong>DRY RUN :</strong> ' . (self::DRY_RUN ? 'YES' : 'NO') . '</p>';
        echo '<input type="submit" name="run_migration" class="button button-primary" value="Start migration">';
        echo '</form>';
    }

    private function migrate_events() {
        $events = get_posts([
            'post_type'      => 'tribe_events',
            'post_status' => 'publish',
            'posts_per_page' => -1,
        ]);

        foreach ($events as $event) {
            $this->log("The Event Calendar: {$event->post_title}");

            // Dates
            $start = get_post_meta($event->ID, '_EventStartDate', true);
            $end   = get_post_meta($event->ID, '_EventEndDate', true);

            // Location
            $venue_id = get_post_meta($event->ID, '_EventVenueID', true);
            $location_id = $this->migrate_location($venue_id);

            // Create EM event
            $new_post_id = $this->create_em_event($event, $start, $end, $location_id);

            // Thumbnail
            $thumbnail_id = get_post_thumbnail_id($event->ID);
            set_post_thumbnail($new_post_id, $thumbnail_id);
        }
    }

    private function migrate_location($venue_id) {
        if (!$venue_id) return 0;

        $venue = get_post($venue_id);
        if (!$venue) return 0;

        $address = get_post_meta($venue_id, '_VenueAddress', true);
        $city    = get_post_meta($venue_id, '_VenueCity', true);
        $country = 'FR';

        $this->log(" → Location: {$venue->post_title}");

        if (self::DRY_RUN) return 0;

        global $wpdb;
        $existing_id = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT location_id FROM {$wpdb->prefix}em_locations WHERE location_name = %s LIMIT 1", $venue->post_title
            )
        );
 
        if ($existing_id) {
            $this->log("   → Existing location, ID = {$existing_id}");
            return $existing_id;
        } else {

            $EM_Location = new EM_Location();

            $EM_Location->location_name    = $venue->post_title;
            $EM_Location->location_address = $address;
            $EM_Location->location_town    = $city;
            $EM_Location->location_country = $country;

            $lat = get_post_meta($venue_id, '_VenueLatitude', true);
            $lng = get_post_meta($venue_id, '_VenueLongitude', true);
            if ($lat && $lng) {
                $EM_Location->location_latitude  = $lat;
                $EM_Location->location_longitude = $lng;
            }

            $EM_Location->save();

            $this->log("   → New location created, ID = {$EM_Location->location_id}");

            return $EM_Location->location_id;
        }
    }

    private function extract_time($datetime) {
        if (!$datetime) return '00:00:00';

        // Normalize datetime
        $datetime = str_replace('T', ' ', $datetime);

        // Extract hours
        $parts = explode(' ', trim($datetime));
        if (count($parts) < 2) return '00:00:00';

        $time = $parts[1];

        // Add missing seconds
        if (preg_match('/^\d{2}:\d{2}$/', $time)) {
            $time .= ':00';
        }

        // Only keep HH:MM:SS
        if (preg_match('/^\d{2}:\d{2}:\d{2}/', $time, $m)) {
            return $m[0];
        }

        return '00:00:00';
    }

    private function create_em_event($event, $start, $end, $location_id) {
        $this->log(" → Creating EM: {$event->post_title}");

        $start_date = substr($start, 0, 10);
        $end_date   = substr($end, 0, 10);

        $start_time = $this->extract_time($start);
        $end_time   = $this->extract_time($end);

        if (self::DRY_RUN) return 0;

        // Create new EM event

        $EM_Event = new EM_Event();
        $EM_Event->event_type = 'single';
        $EM_Event->event_archetype = 'event';
        $EM_Event->event_name = $event->post_title;
        $EM_Event->post_content = $event->post_content;
        $EM_Event->event_date_created = $event->post_date;
        $EM_Event->event_start_date = $start_date;
        $EM_Event->event_start_time = $start_time;
        $EM_Event->event_end_date = $end_date;
        $EM_Event->event_end_time = $end_time;
        $EM_Event->start = strtotime($EM_Event->event_start_date.' '.$EM_Event->event_start_time);
        $EM_Event->end = strtotime($EM_Event->event_end_date.' '.$EM_Event->event_end_time);
        $EM_Event->event_rsvp = false;
        $EM_Event->event_rsvp_time = $start_time;
        $EM_Event->location_id = $location_id;
        $EM_Event->event_status = 1;
        $EM_Event->save();

        return $EM_Event->post_id;
    }

    private function log($msg) {
        file_put_contents(self::LOG_FILE, date('[Y-m-d H:i:s] ') . $msg . "\n", FILE_APPEND);
    }
}

new TEC_To_EM_Migration();