<?php
defined('ABSPATH') || exit;

class Termin_Kalender_Functions
{



    public function __construct()
    {
        add_action('wp_ajax_get_calendar_events', [$this, 'get_calendar_events']);
        add_action('wp_ajax_save_calendar_event', [$this, 'save_calendar_event']);
        add_action('wp_ajax_delete_calendar_event', [$this, 'delete_calendar_event']);
        add_action('wp_ajax_get_categories', [$this, 'get_categories']);
        add_action('wp_ajax_save_category', [$this, 'save_category']);
        add_action('wp_ajax_delete_category', [$this, 'delete_category']);
    }

    public function get_calendar_events()
    {
        check_ajax_referer('termin_kalender_nonce', 'nonce');
        $events = $this->get_events();
        wp_send_json_success($events);
    }

    public function save_calendar_event()
    {
        check_ajax_referer('termin_kalender_nonce', 'nonce');
        if (!current_user_can('termin_kalender_edit')) {
            wp_send_json_error(array('message' => esc_html__('Permission denied.', 'termin-kalender')));
            wp_die();
        }
        $id = isset($_POST['id']) ? sanitize_text_field(wp_unslash($_POST['id'])) : null;
        $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : null;
        //--------------------------
        $start = isset($_POST['start']) ? sanitize_text_field(wp_unslash($_POST['start'])) : null;
        $end = isset($_POST['end']) ? sanitize_text_field(wp_unslash($_POST['end'])) : null;
        $until = isset($_POST['until']) ? sanitize_text_field(wp_unslash($_POST['until'])) : null;
        $allday = isset($_POST['allDay']) && sanitize_text_field(wp_unslash($_POST['allDay'])) === 'true'; // allDay nur setzen wenn checkbox gesetzt (true)
        //--------------------------
        $freq = isset($_POST['freq']) ? sanitize_text_field(wp_unslash($_POST['freq'])) : '';
        $byweekday = isset($_POST['byweekday']) ? sanitize_text_field(wp_unslash($_POST['byweekday'])) : '';  // als liste einlesen
        $exdate = isset($_POST['exdate']) ? sanitize_text_field(wp_unslash($_POST['exdate'])) : '';
        $interval = isset($_POST['interval']) ? max(1, absint(wp_unslash($_POST['interval']))) : 1;
        $bysetpos = isset($_POST['bysetpos']) ? (int) sanitize_text_field(wp_unslash($_POST['bysetpos'])) : null;
        //--------------------------
        $details = isset($_POST['details']) ? wp_kses_post(wp_unslash($_POST['details'])) : '';
        $notes = isset($_POST['notes']) ? sanitize_text_field(wp_unslash($_POST['notes'])) : '';
        $location = isset($_POST['location']) ? sanitize_text_field(wp_unslash($_POST['location'])) : '';
        $category = isset($_POST['category']) ? sanitize_text_field(wp_unslash($_POST['category'])) : '';
        $textColor = isset($_POST['textColor']) ? sanitize_text_field(wp_unslash($_POST['textColor'])) : '';
        $backgroundColor = isset($_POST['backgroundColor']) ? sanitize_text_field(wp_unslash($_POST['backgroundColor'])) : '';
        //--------------------------
        $create_post = isset($_POST['create_post']) ? sanitize_text_field(wp_unslash($_POST['create_post'])) : '';
        $post_link = isset($_POST['post_link']) ? sanitize_text_field(wp_unslash($_POST['post_link'])) : '';
        //----------------------------------------------------------------------------------
        $events = $this->get_events();
        $category_data = null;
        $categories = json_decode(get_option('termin_kalender_kategorien', '[]'), true);
        foreach ($categories as $cat) {
            if ($cat['label'] === $category) {
                $category_data = $cat;
                break;
            }
        }
        $id_group_id = $id ?: (string) uniqid();
        //----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
/*// create post if request is yes
if ($create_post === 'yes') {
    // 1. Array mit Event-Daten vorbereiten (die Keys müssen mit dem Manager übereinstimmen)

    $post_event_data = [
        'title'           => $title,
        'description'     => $details,
        'start'           => $start,
        'end'             => $end,
        'until'           => $until,
        'allDay'          => $allday,
        'location'        => $location,
        'category'        => $category,
        'uid'             => $id_group_id,
        'freq'       => $freq,
        'byweekday'  => $byweekday,
        'exdate'     => $exdate,
        'interval'   => $interval,
        'bysetpos'   => $bysetpos,
        'textColor'       => $category_data['textColor'],
        'backgroundColor' => $category_data['backgroundColor'],
        'icon'            => $category_data['icon'],
        'category_data'   => $category_data,
    ];

    try {

        // 2. Manager aufrufen und Post erstellen/updaten
        if (class_exists('Termin_Kalender_Event_Posts_Main')) {
            // Gibt bei Erfolg den Permalink (String) zurück, bei Fehler ein WP_Error Objekt
            $manager = new Termin_Kalender_Event_Posts_Main();
            $result  = $manager->sync_event_to_post($post_event_data);
            // error_log('result: ' . print_r($result, true));
            if (is_wp_error($result)) {
                // Fehler-Handling
                $notes .= ' -Fehler beim erstellen des Posts- ';
                TK_Error_Handler::log(['level' => 'error', 'module' => 'Event Posts', 'message' => $result->get_error_message()]);
            } else {
                // $result enthält jetzt den generierten Link zum Post (z.B. https://deinewebsite.de/termin-kalender/mein-neues-event)
                $post_link = $result['permalink'];
                $notes .= ' -- Post erstellt: '.$post_link.' -- ';
                $notes .= ' --  <a href="'.$post_link.'" target="_blank">'.$title.'</a> -- ';
            }
        }

    } catch (Throwable $e) {

        TK_Error_Handler::log(['level' => 'error', 'module' => 'Event Posts', 'message' => $e->getMessage()]);
    }
}
if (!empty($post_link)) {
    // TODO: if we stored an event link here we must check if the post still exist and eventually delete the link if not
    // Prüfen ob der Post mit dem gespeicherten Link noch existiert
    try {
        $post_id = url_to_postid($post_link);
        if ($post_id === 0) {
            // Post existiert nicht mehr – Link entfernen
            $post_link = '';
            $notes .= ' -- Post-Link ungültig, Post nicht gefunden – Link entfernt -- ';
        } else {
            $post_status = get_post_status($post_id);
            if ($post_status === false || in_array($post_status, ['trash', 'auto-draft'], true)) {
                // Post im Papierkorb oder ungültig – Link entfernen
                $post_link = '';
                $notes .= ' -- Post-Link ungültig (Status: ' . esc_html($post_status ?: 'nicht gefunden') . ') – Link entfernt -- ';
            }
        }
    } catch (Throwable $e) {
        TK_Error_Handler::log([
            'level'   => 'warning',
            'module'  => 'Event Posts',
            'message' => 'Post-Link-Prüfung fehlgeschlagen: ' . $e->getMessage(),
            'file'    => $e->getFile(),
            'line'    => $e->getLine(),
        ]);
    }
}*/

        //---------------------------------------------------------------------------------------------------------
        try {
            if (class_exists('Termin_Kalender_Event_Posts_Main')) {
                $manager = new Termin_Kalender_Event_Posts_Main();
                // ter_kal_: Hole Post ID via UID (existierende Funktion in deiner Klasse)
                // Beachte: Wir verlassen uns auf die UID, da sich der Permalink geändert haben könnte.
                $existing_post_id = $manager->get_post_by_uid($id_group_id);
                //---------------------------------------------------------------------------------------------------------
                $post_event_data = [
                    'title' => $title,
                    'description' => $details,
                    'start' => $start,
                    'end' => $end,
                    'until' => $until,
                    'allDay' => $allday,
                    'location' => $location,
                    'category' => $category,
                    'uid' => $id_group_id,
                    'freq' => $freq,
                    'byweekday' => $byweekday,
                    'exdate' => $exdate,
                    'interval' => $interval,
                    'bysetpos' => $bysetpos,
                    'textColor' => $category_data['textColor'],
                    'backgroundColor' => $category_data['backgroundColor'],
                    'icon' => $category_data['icon'],
                    'category_data' => $category_data,
                ];
                //--------------------------------------------------------
// create post if request is yes and no post exist
                if ($create_post === 'yes' && empty($existing_post_id)) {
                    $result = $manager->sync_event_to_post($post_event_data, 'new');
                    // error_log('result: ' . print_r($result, true));
                    if (is_wp_error($result)) {
                        $notes .= ' -Fehler beim erstellen des Posts- ';
                        TK_Error_Handler::log(['level' => 'error', 'module' => 'Event Posts', 'message' => $result->get_error_message()]);
                    } else {
                        // $result enthält jetzt den generierten Link zum Post (z.B. https://deinewebsite.de/termin-kalender/mein-neues-event)
                        $post_link = $result['permalink'];
                        $notes .= ' -- Post erstellt: ' . $post_link . ' -- ';
                    }
                } elseif ($create_post === 'yes' && !empty($existing_post_id)) {

                    $result = $manager->sync_event_to_post($post_event_data, 'update');


                } elseif ($create_post !== 'yes' && !empty($post_link) && empty($existing_post_id)) {
                    // Post existiert nicht mehr – Link entfernen
                    $post_link = '';
                    $notes .= ' -- Post nicht gefunden – Link entfernt -- ';
                    //$post_status = get_post_status($existing_post_id);  // Post im Papierkorb oder ungültig – Link entfernen
                }

                //---------------------------------------------------------------------------------------------------------
            }
        } catch (Throwable $e) {
            TK_Error_Handler::log(['level' => 'error', 'module' => 'Event Posts', 'message' => $e->getMessage()]);
        }
        //---------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//---------------------------------------------------------------------------

        $eventData = [
            'id' => $id_group_id,
            'groupId' => $id_group_id,
            'title' => $title,
            'start' => $start,
            'end' => $end,
            'textColor' => $textColor ?: $category_data['textColor'],
            'backgroundColor' => $backgroundColor ?: $category_data['backgroundColor'],
            'extendedProps' => [
                'details' => $details,
                'notes' => $notes,
                'category' => $category_data,
                'location' => $location,
                'post_link' => $post_link,
            ]
        ];


        if (!empty($freq)) {
            $eventData['extendedProps']['freq'] = $freq;
            $eventData['extendedProps']['until'] = $until;
            $eventData['extendedProps']['dtstart'] = $start;
            $eventData['extendedProps']['interval'] = $interval;
            $rrule = [
                'freq' => $freq,
                'until' => $until,
                'dtstart' => $start,
                'interval' => $interval,
            ];
            //-------

            //-------
            if (!empty($exdate)) {
                $exdate_array = explode(',', $exdate);
                if ($start && strpos($start, 'T') !== false) {
                    $timePart = substr($start, strpos($start, 'T')); // z.B. T01:23
                    foreach ($exdate_array as &$d) {
                        // Falls noch keine Uhrzeit enthalten, anhängen
                        if (strpos($d, 'T') === false) {
                            $d .= $timePart;
                        }
                    }
                    unset($d);
                }
                $eventData['exdate'] = $exdate_array;
                $eventData['extendedProps']['exdate'] = $exdate;
            }
            //-------
            if ($freq === 'WEEKLY' || $freq === 'MONTHLY') {
                if (!empty($byweekday)) {
                    $eventData['extendedProps']['byweekday'] = $byweekday;
                    $rrule['byweekday'] = explode(',', $byweekday);
                }
                if (!empty($bysetpos)) {
                    $eventData['extendedProps']['bysetpos'] = $bysetpos;
                    $rrule['bysetpos'] = intval($bysetpos);
                    // Ensure single weekday: use first
                    $weekdays = !empty($byweekday) ? explode(',', $byweekday) : [];
                    if (!empty($weekdays)) {
                        if (count($weekdays) > 1) {
                            $weekdays = [reset($weekdays)];
                        }
                        $eventData['extendedProps']['byweekday'] = $weekdays[0];
                        $rrule['byweekday'] = $weekdays;
                    }
                    // interval nicht zusammen mit bysetpos zulassen
                    unset($eventData['extendedProps']['interval'], $rrule['interval']);
                }
            }
            //--------------------------------------------------------
            $eventData['rrule'] = $rrule;
            //--------------------------------------------------------
        } // end if not empty freq
        //---------------------------------------------------------------------------
        if ($allday) {
            $eventData['allDay'] = $allday;
        }
        //---------------------------------------------------------------------------
        if ($id) {
            foreach ($events as &$event) {
                if ($event['id'] === $id) {
                    if (!empty($freq)) {
                        if (!empty($event['extendedProps']['dtstart'])) {
                            $dtstart = $event['extendedProps']['dtstart'];
                            $event['start'] = $dtstart;
                            $event['extendedProps']['dtstart'] = $dtstart;
                            $event['rrule']['dtstart'] = $dtstart;
                        }
                    } else {
                        unset(
                            $event['rrule'],
                            $event['exdate'],
                            $event['extendedProps']['rrule'],
                            $event['extendedProps']['freq'],
                            $event['extendedProps']['exdate'],
                            $event['extendedProps']['dtstart'],
                            $event['extendedProps']['bysetpos'],
                            $event['extendedProps']['until'],
                            $event['extendedProps']['byweekday'],
                            $event['extendedProps']['interval']
                        );
                    }
                    // unset bestehendes allDay !
                    if (!$allday) {
                        unset($event['allDay']);
                    }
                    $event = array_merge($event, $eventData);  // bringt event und evendData zusammen wenn event besteht

                    break;
                }
            }
            unset($event);
        } else {
            $events[] = $eventData;
        }
        //----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
        $this->save_events($events);
        wp_send_json_success(array('id' => $id_group_id, 'message' => esc_html__('New event saved successfully', 'termin-kalender')));
    } // end save_calendar_event

    //----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
    public function delete_calendar_event()
    {
        check_ajax_referer('termin_kalender_nonce', 'nonce');
        if (!current_user_can('termin_kalender_delete')) {
            wp_send_json_error(array('message' => esc_html__('Permission denied.', 'termin-kalender')));
            wp_die();
        }

        $event_id = isset($_POST['id']) ? sanitize_text_field(wp_unslash($_POST['id'])) : ''; //Sanitize the event ID

        if (!empty($event_id)) {
            $events = $this->get_events();

            // Filter out the event to be deleted
            $events = array_filter($events, function ($event) use ($event_id) {
                return $event['id'] !== $event_id;
            });
            // NEW: Delete associated event page
/*            $page_manager = Termin_Kalender_Event_Page_Manager::get_instance();
            $existing_post_id = $this->get_post_id_by_uid($event_id);
            if ($existing_post_id) {
                wp_delete_post($existing_post_id, true); // true = force delete (skip trash)
            }*/
            // Save the updated events array
            //$this->save_events($events);  hier muss array_values verwendet werden, wegen filter
            update_option('termin_kalender_events', json_encode(array_values($events)), false);

            wp_send_json_success();
        } else {
            wp_send_json_error('Invalid event ID.');
        }

        wp_die();
    }
    // Helper function to get post ID by UID
/*    private function get_post_id_by_uid($uid) {
        $args = [
            'post_type'      => 'termin_kalender',
            'post_status'    => 'any',
            'posts_per_page' => 1,
            'meta_query'     => [
                [
                    'key'     => '_ter_kal_uid',
                    'value'   => $uid,
                    'compare' => '='
                ]
            ],
            'fields'         => 'ids',
        ];
        $posts = get_posts($args);
        return !empty($posts) ? $posts[0] : null;
    }*/



    public function get_categories()
    {
        check_ajax_referer('termin_kalender_nonce', 'nonce');
        $categories = json_decode(get_option('termin_kalender_kategorien', '[]'), true);
        if (empty($categories)) {
            $categories = [
                [
                    'categoryID' => (string) uniqid(),
                    'backgroundColor' => '#0000FF',
                    'textColor' => '#FFFFFF',
                    'label' => 'Neue Kategorie',
                    'icon' => 'dashicons-plus'
                ]
            ];
            update_option('termin_kalender_kategorien', json_encode($categories), false);
        }
        wp_send_json_success($categories);
    }

    public function save_category()
    {
        check_ajax_referer('termin_kalender_nonce', 'nonce');
        if (!current_user_can('termin_kalender_edit')) {
            wp_send_json_error(array('message' => esc_html__('Permission denied.', 'termin-kalender')));
            wp_die();
        }
        $categories = json_decode(get_option('termin_kalender_kategorien', '[]'), true);
        $category = [
            'categoryID' => isset($_POST['categoryID']) ? sanitize_text_field(wp_unslash($_POST['categoryID'])) : '',
            'backgroundColor' => isset($_POST['backgroundColor']) ? sanitize_text_field(wp_unslash($_POST['backgroundColor'])) : '',
            'textColor' => isset($_POST['textColor']) ? sanitize_text_field(wp_unslash($_POST['textColor'])) : '',
            'label' => isset($_POST['label']) ? sanitize_text_field(wp_unslash($_POST['label'])) : '',
            'icon' => isset($_POST['icon']) ? sanitize_text_field(wp_unslash($_POST['icon'])) : ''
        ];
        // Generate a new categoryID if empty so that a new category doesn't override an existing one.
        if (empty($category['categoryID'])) {
            $category['categoryID'] = (string) uniqid();
        }
        $index = array_search($category['categoryID'], array_column($categories, 'categoryID'));
        if ($index !== false) {
            $categories[$index] = $category;
        } else {
            $categories[] = $category;
        }
        update_option('termin_kalender_kategorien', json_encode($categories), false);

        // ============================================================
        // ✅ Änderung: Events mit gleicher categoryID synchronisieren
        // ============================================================
        try {
            $all_events = $this->get_events();
            $changed_events = 0;
            $events_updated = false;
            $target_category_id = (string) $category['categoryID'];

            foreach ($all_events as &$event) {
                if (!is_array($event)) {
                    continue;
                }

                $extendedProps = $event['extendedProps'] ?? [];
                if (!is_array($extendedProps)) {
                    continue;
                }

                $event_category = $extendedProps['category'] ?? null;
                $event_category_id = '';
                
                if (is_array($event_category) && isset($event_category['categoryID'])) {
                    $event_category_id = (string) $event_category['categoryID'];
                }

                if ($event_category_id !== $target_category_id) {
                    continue;
                }

                $extendedProps['category'] = $category;
                $event['textColor'] = sanitize_text_field($category['textColor'] ?? '');
                $event['backgroundColor'] = sanitize_text_field($category['backgroundColor'] ?? '');
                $event['extendedProps'] = $extendedProps;

                $changed_events++;
                $events_updated = true;
            }
            unset($event);

            if ($events_updated) {
                $this->save_events($all_events);
                if (class_exists('Termin_Kalender_Event_Repository')) {
                    // Update in database tracking if repo exists
                    foreach ($all_events as $updated_event) {
                        $event_id = $updated_event['id'] ?? ($updated_event['uid'] ?? '');
                        if (!empty($event_id)) {
                             Termin_Kalender_Event_Repository::save_event($updated_event);
                        }
                    }
                }
            }

            if (class_exists('TK_Error_Handler') && $changed_events > 0) {
                TK_Error_Handler::log([
                    'level' => 'notice',
                    'module' => 'category-updater',
                    'message' => 'Resynced legacy events after category update: ' . $changed_events,
                    'file' => __FILE__,
                    'line' => __LINE__,
                ]);
            }
        } catch (Throwable $e) {
            if (class_exists('TK_Error_Handler')) {
                TK_Error_Handler::log([
                    'level' => 'error',
                    'module' => 'category-updater',
                    'message' => $e->getMessage(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ]);
            }
        }

        wp_send_json_success();
    }

    public function delete_category()
    {
        check_ajax_referer('termin_kalender_nonce', 'nonce');
        if (!current_user_can('termin_kalender_delete')) {
            wp_send_json_error(array('message' => esc_html__('Permission denied.', 'termin-kalender')));
            wp_die();
        }
        $categories = json_decode(get_option('termin_kalender_kategorien', '[]'), true);
        $categoryID = isset($_POST['categoryID']) ? sanitize_text_field(wp_unslash($_POST['categoryID'])) : '';
        $categories = array_filter($categories, function ($cat) use ($categoryID) {
            return $cat['categoryID'] !== $categoryID;
        });
        update_option('termin_kalender_kategorien', json_encode(array_values($categories)), false);
        wp_send_json_success();
    }

    private function get_events()
    {
        $events = json_decode(get_option('termin_kalender_events', '[]'), true);
        return $events ?: [];
    }

    private function save_events($events)
    {
        update_option('termin_kalender_events', json_encode($events), false);
    }


    //--------------------------------
} // end Termin_Kalender_Functions
//--------------------------------

