<?php

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

class AIEO_Event_Invites {

    
    public static function merge_map($p, $event) {
        $event_id = (int) $event->ID;
        $title    = trim((string) ($p->title ?? ''));
        $first    = trim((string) ($p->first_name ?? ''));
        $last     = trim((string) ($p->last_name ?? ''));
        $name     = trim($first . ' ' . $last);
        $sal      = trim((string) ($p->salutation ?? ''));
        $rsvp_url = class_exists('AIEO_Event_RSVP') ? AIEO_Event_RSVP::url($p->rsvp_token) : '';

        $start    = class_exists('AIEO_Event_CPT') ? AIEO_Event_CPT::fmt_dt(get_post_meta($event_id, AIEO_Event_CPT::META_START, true)) : '';
        $location = (string) get_post_meta($event_id, AIEO_Event_CPT::META_LOCATION, true);
        $ev_url   = get_permalink($event_id);
        $map_url  = class_exists('AIEO_Event_CPT') ? AIEO_Event_CPT::map_url($event_id) : '';

        return array(
            '{salutation}'     => $sal !== '' ? $sal : ($name !== '' ? sprintf(__('Dear %s', 'ai-eshop-optimizer'), $name) : __('Hello', 'ai-eshop-optimizer')),
            '{title}'          => $title,
            '{first_name}'     => $first,
            '{last_name}'      => $last,
            '{name}'           => $name,
            '{organization}'   => trim((string) ($p->organization ?? '')),
            '{department}'     => trim((string) ($p->department ?? '')),
            '{email}'          => (string) ($p->email ?? ''),
            '{event_title}'    => get_the_title($event_id),
            '{event_date}'     => $start,
            '{event_location}' => $location,
            '{event_url}'      => $ev_url ? $ev_url : '',
            '{event_map_url}'  => $map_url,
            '{event_map_link}' => $map_url !== '' ? '<a href="' . esc_url($map_url) . '" target="_blank" rel="noopener" style="color:#1f8a4c;">' . esc_html__('View on map', 'ai-eshop-optimizer') . '</a>' : '',
            '{rsvp_url}'       => $rsvp_url,
            '{rsvp_link}'      => $rsvp_url !== '' ? self::button($rsvp_url, __('Respond to this invitation', 'ai-eshop-optimizer')) : '',
        );
    }

    
    public static function apply($text, array $map, $is_html) {
        $raw_html = array('{rsvp_link}', '{event_map_link}');
        $urls     = array('{rsvp_url}', '{event_url}', '{event_map_url}');
        $search   = array();
        $replace  = array();
        foreach ($map as $k => $v) {
            $search[] = $k;
            if (!$is_html)                       { $replace[] = $v; }
            elseif (in_array($k, $raw_html, true)) { $replace[] = $v; }
            elseif (in_array($k, $urls, true))     { $replace[] = esc_url($v); }
            else                                   { $replace[] = esc_html($v); }
        }
        return str_replace($search, $replace, (string) $text);
    }

    
    public static function render($p, $event) {
        $map         = self::merge_map($p, $event);
        $subject_raw = (string) get_post_meta($event->ID, AIEO_Event_CPT::META_INVITE_SUBJECT, true);
        $body_raw    = (string) get_post_meta($event->ID, AIEO_Event_CPT::META_INVITE_BODY, true);

        $subject = self::apply($subject_raw, $map, false);
        $inner   = wpautop(self::apply($body_raw, $map, true));

        
        
        $append = (strpos($body_raw, '{rsvp') === false && $map['{rsvp_url}'] !== '')
            ? self::button($map['{rsvp_url}'], __('Respond to this invitation', 'ai-eshop-optimizer'))
            : '';

        if ($subject === '') {
            $subject = sprintf(__('Invitation: %s', 'ai-eshop-optimizer'), get_the_title($event));
        }
        return array(
            'to'      => (string) $p->email,
            'name'    => $map['{name}'],
            'subject' => $subject,
            'html'    => self::shell(get_the_title($event), $inner, $append),
        );
    }

    
    public static function sample($event) {
        $list = class_exists('AIEO_Event_Participants') ? AIEO_Event_Participants::get_for_event($event->ID, array('limit' => 1)) : array();
        if (!empty($list)) { return self::render($list[0], $event); }
        $fake = (object) array(
            'title' => __('Dr', 'ai-eshop-optimizer'), 'salutation' => __('Dear Sir/Madam', 'ai-eshop-optimizer'),
            'first_name' => __('First', 'ai-eshop-optimizer'), 'last_name' => __('Last', 'ai-eshop-optimizer'),
            'organization' => __('Organization', 'ai-eshop-optimizer'), 'department' => __('Department', 'ai-eshop-optimizer'),
            'email' => 'sample@example.com', 'rsvp_token' => str_repeat('0', 64),
        );
        return self::render($fake, $event);
    }

    
    public static function recipients($event_id, $scope) {
        global $wpdb;
        $tbl      = AIEO_Event_Participants::table();
        $event_id = (int) $event_id;
        $where    = 'event_id = %d';
        if ($scope === 'pending')  { $where .= " AND rsvp_status = 'invited'"; }
        elseif ($scope === 'new')  { $where .= " AND (invited_at IS NULL OR invited_at = '' OR invited_at = '0000-00-00 00:00:00')"; }
        return (array) $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$tbl} WHERE {$where} ORDER BY participant_id ASC",
            $event_id
        ));
    }

    
    public static function scope_counts($event_id) {
        return array(
            'all'     => count(self::recipients($event_id, 'all')),
            'new'     => count(self::recipients($event_id, 'new')),
            'pending' => count(self::recipients($event_id, 'pending')),
        );
    }

    
    public static function deliver($to, $subject, $html) {
        if (!is_email($to)) { return false; }
        if (class_exists('Newsletter')) {
            $n = Newsletter::instance();
            if (is_object($n) && method_exists($n, 'mail')) {
                return (bool) $n->mail($to, $subject, array('html' => $html));
            }
        }
        add_filter('wp_mail_content_type', array(__CLASS__, 'html_content_type'));
        $ok = wp_mail($to, $subject, $html);
        remove_filter('wp_mail_content_type', array(__CLASS__, 'html_content_type'));
        return (bool) $ok;
    }

    public static function html_content_type() { return 'text/html'; }

    
    public static function run($event_id, $scope, $live) {
        $out   = array('scope' => $scope, 'recipients' => 0, 'sent' => 0, 'failed' => 0, 'skipped' => 0, 'live' => (bool) $live);
        $event = get_post((int) $event_id);
        if (!$event || !class_exists('AIEO_Event_CPT') || $event->post_type !== AIEO_Event_CPT::POST_TYPE) {
            $out['error'] = 'invalid_event';
            return $out;
        }
        $subject_raw = (string) get_post_meta($event->ID, AIEO_Event_CPT::META_INVITE_SUBJECT, true);
        $body_raw    = (string) get_post_meta($event->ID, AIEO_Event_CPT::META_INVITE_BODY, true);
        if ($subject_raw === '' || $body_raw === '') {
            $out['error'] = 'no_template';
            return $out;
        }

        $list = self::recipients($event->ID, $scope);
        $out['recipients'] = count($list);

        foreach ($list as $p) {
            $r = self::render($p, $event);
            if (!is_email($r['to'])) { $out['skipped']++; continue; }
            if (!$live) { continue; } 
            if (self::deliver($r['to'], $r['subject'], $r['html'])) {
                $out['sent']++;
                if (class_exists('AIEO_Event_Participants') && method_exists('AIEO_Event_Participants', 'mark_invited')) {
                    AIEO_Event_Participants::mark_invited($p->rsvp_token);
                }
            } else {
                $out['failed']++;
            }
        }
        return $out;
    }

    

    
    public static function button($url, $label) {
        return '<table role="presentation" cellpadding="0" cellspacing="0" style="margin:26px auto;"><tr>'
            . '<td style="border-radius:8px;background:#1f8a4c;">'
            . '<a href="' . esc_url($url) . '" style="display:inline-block;padding:13px 30px;font-family:Arial,Helvetica,sans-serif;font-size:16px;font-weight:bold;color:#ffffff;text-decoration:none;border-radius:8px;">'
            . esc_html($label) . '</a></td></tr></table>';
    }

    
    public static function shell($title, $inner_html, $append_html) {
        $site = get_bloginfo('name');
        ob_start();
        ?><!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?php echo esc_html($title); ?></title></head>
<body style="margin:0;padding:0;background:#f4f1ee;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f1ee;padding:24px 0;"><tr><td align="center">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;font-family:Arial,Helvetica,sans-serif;color:#2b2b2b;">
<tr><td style="padding:18px 28px;border-bottom:1px solid #efeae5;font-size:13px;letter-spacing:.12em;text-transform:uppercase;color:#9a8f86;font-weight:bold;"><?php echo esc_html($site); ?></td></tr>
<tr><td style="padding:28px;font-size:16px;line-height:1.6;"><?php
        echo $inner_html;  
        echo $append_html; 
        ?></td></tr>
<tr><td style="padding:16px 28px;border-top:1px solid #efeae5;font-size:12px;color:#9a8f86;"><?php echo esc_html($site); ?></td></tr>
</table>
</td></tr></table>
</body>
</html><?php
        return ob_get_clean();
    }
}
