<?php
/**
 * Proto Preview — Stakeholder Email Notification Engine
 * Sends instant, beautifully formatted review notifications when feedback is left or replied to.
 * Brand Identity: Bowden Works
 */

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

class Proto_Preview_Notifications {

    /**
     * Resolves project, screen, and layout details for a given layout_id
     */
    public static function resolve_layout_context($layout_id) {
        $posts = get_posts([
            'post_type'      => 'proto_project',
            'post_status'    => 'publish',
            'posts_per_page' => -1
        ]);

        foreach ($posts as $post) {
            $screens = get_post_meta($post->ID, '_proto_screens', true);
            if (is_array($screens)) {
                foreach ($screens as $screen) {
                    if (isset($screen['layouts']) && is_array($screen['layouts'])) {
                        foreach ($screen['layouts'] as $layout) {
                            if ((int)$layout['id'] === (int)$layout_id) {
                                return [
                                    'project_id'   => $post->ID,
                                    'project_name' => $post->post_title,
                                    'screen_id'    => $screen['id'] ?? 1,
                                    'screen_name'  => $screen['name'] ?? 'Screen',
                                    'layout_id'    => $layout['id'],
                                    'layout_name'  => $layout['name'] ?? 'Option',
                                    'layout_ver'   => $layout['version'] ?? 'Opt 1'
                                ];
                            }
                        }
                    }
                }
            }
        }

        // Fallback to first available project
        if (!empty($posts)) {
            return [
                'project_id'   => $posts[0]->ID,
                'project_name' => $posts[0]->post_title,
                'screen_id'    => 1,
                'screen_name'  => 'Homepage',
                'layout_id'    => $layout_id,
                'layout_name'  => 'Variation',
                'layout_ver'   => 'Opt 1'
            ];
        }

        return null;
    }

    /**
     * Collects all recipient email addresses assigned to a project (excluding sender)
     */
    public static function get_project_recipients($project_id, $exclude_email = '') {
        $recipients = [];

        // 1. Assigned WordPress Users
        $assigned_user_ids = get_post_meta($project_id, '_proto_assigned_users', true);
        if (is_array($assigned_user_ids) && !empty($assigned_user_ids)) {
            foreach ($assigned_user_ids as $u_id) {
                $user = get_user_by('id', (int)$u_id);
                if ($user && !empty($user->user_email)) {
                    $recipients[] = trim($user->user_email);
                }
            }
        } else {
            // Default to site admin if none specifically assigned
            $admin_email = get_option('admin_email');
            if (!empty($admin_email)) {
                $recipients[] = trim($admin_email);
            }
        }

        // 2. Additional Stakeholder / Client Notification Emails
        $custom_emails_raw = get_post_meta($project_id, '_proto_notification_emails', true);
        if (!empty($custom_emails_raw)) {
            $split_emails = preg_split('/[,;\s]+/', $custom_emails_raw);
            foreach ($split_emails as $em) {
                $em = trim($em);
                if (is_email($em)) {
                    $recipients[] = $em;
                }
            }
        }

        // Clean, unique, and exclude the author
        $recipients = array_unique(array_filter($recipients, 'is_email'));
        if (!empty($exclude_email)) {
            $recipients = array_diff($recipients, [trim($exclude_email)]);
        }

        return array_values($recipients);
    }

    /**
     * Sends an email notification when a new comment pin is dropped
     */
    public static function notify_new_comment($comment_id, $layout_id, $text, $author_id = 0, $guest_name = '', $guest_email = '') {
        $context = self::resolve_layout_context($layout_id);
        if (!$context) return false;

        $project_id = $context['project_id'];

        // Check if notifications enabled for this project
        $notifications_enabled = get_post_meta($project_id, '_proto_enable_notifications', true);
        if ($notifications_enabled === '0') return false;

        $author = $author_id ? get_user_by('id', $author_id) : null;
        $author_name = $author ? $author->display_name : ($guest_name ?: 'Reviewer');
        $author_email = $author ? $author->user_email : ($guest_email ?: '');
        $author_role = ($author && user_can($author->ID, 'manage_options')) ? 'Lead Designer' : 'Client Reviewer';
        $author_avatar = $author ? get_avatar_url($author->ID) : 'https://ui-avatars.com/api/?name=' . urlencode(substr($author_name, 0, 1)) . '&background=b02b2b&color=ffffff&bold=true';

        $recipients = self::get_project_recipients($project_id, $author_email);
        if (empty($recipients)) return false;

        $project_name = $context['project_name'];
        $screen_name  = $context['screen_name'];
        $layout_name  = $context['layout_name'];

        // Direct Deep Link into Player
        $player_url = add_query_arg([
            'proto_preview' => '1',
            'project'       => $project_id,
            'page'          => $context['screen_id'],
            'layout'        => $layout_id,
            'mode'          => 'comment'
        ], home_url('/'));

        $subject = sprintf('[%s] New feedback on "%s" by %s', $project_name, $screen_name, $author_name);

        $body = self::get_email_template([
            'badge_title'     => 'New Prototype Feedback',
            'project_name'    => $project_name,
            'screen_name'     => $screen_name,
            'layout_name'     => $layout_name,
            'author_name'     => $author_name,
            'author_role'     => $author_role,
            'author_avatar'   => $author_avatar,
            'content_heading' => 'New Feedback Pin Added',
            'message_text'    => $text,
            'cta_url'         => $player_url,
            'cta_label'       => 'View & Reply on Canvas ➔'
        ]);

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: Bowden Works Prototype Reviewer <' . get_option('admin_email') . '>'
        ];

        return wp_mail($recipients, $subject, $body, $headers);
    }

    /**
     * Sends an email notification when a reply is added to a comment thread
     */
    public static function notify_new_reply($reply_id, $comment_id, $reply_text, $author_id = 0, $guest_name = '', $guest_email = '') {
        global $wpdb;
        $table_comments = $wpdb->prefix . 'pp_comments';
        $comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_comments WHERE id = %d", $comment_id), ARRAY_A);
        if (!$comment) return false;

        $layout_id = (int)$comment['layout_id'];
        $context = self::resolve_layout_context($layout_id);
        if (!$context) return false;

        $project_id = $context['project_id'];

        $notifications_enabled = get_post_meta($project_id, '_proto_enable_notifications', true);
        if ($notifications_enabled === '0') return false;

        $author = $author_id ? get_user_by('id', $author_id) : null;
        $author_name = $author ? $author->display_name : ($guest_name ?: 'Reviewer');
        $author_email = $author ? $author->user_email : ($guest_email ?: '');
        $author_role = ($author && user_can($author->ID, 'manage_options')) ? 'Lead Designer' : 'Client Reviewer';
        $author_avatar = $author ? get_avatar_url($author->ID) : 'https://ui-avatars.com/api/?name=' . urlencode(substr($author_name, 0, 1)) . '&background=b02b2b&color=ffffff&bold=true';

        $recipients = self::get_project_recipients($project_id, $author_email);

        // Also ensure the original comment creator gets notified if not already in list
        $orig_author = get_user_by('id', (int)$comment['user_id']);
        if ($orig_author && is_email($orig_author->user_email) && $orig_author->user_email !== $author_email) {
            $recipients[] = trim($orig_author->user_email);
        }

        $recipients = array_unique(array_filter($recipients, 'is_email'));
        if (empty($recipients)) return false;

        $project_name = $context['project_name'];
        $screen_name  = $context['screen_name'];

        $player_url = add_query_arg([
            'proto_preview' => '1',
            'project'       => $project_id,
            'page'          => $context['screen_id'],
            'layout'        => $layout_id,
            'mode'          => 'comment'
        ], home_url('/'));

        $subject = sprintf('[%s] New reply on "%s" by %s', $project_name, $screen_name, $author_name);

        $body = self::get_email_template([
            'badge_title'     => 'New Reply in Thread',
            'project_name'    => $project_name,
            'screen_name'     => $screen_name,
            'layout_name'     => $context['layout_name'],
            'author_name'     => $author_name,
            'author_role'     => $author_role,
            'author_avatar'   => get_avatar_url($author_id ?: 1),
            'content_heading' => 'Thread Response',
            'original_text'   => $comment['text'],
            'message_text'    => $reply_text,
            'cta_url'         => $player_url,
            'cta_label'       => 'Open Thread on Canvas ➔'
        ]);

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: Bowden Works Prototype Reviewer <' . get_option('admin_email') . '>'
        ];

        return wp_mail($recipients, $subject, $body, $headers);
    }

    /**
     * Generates a modern, responsive HTML email template
     */
    private static function get_email_template($data) {
        $badge_title     = esc_html($data['badge_title'] ?? 'Prototype Review');
        $project_name    = esc_html($data['project_name'] ?? 'Project');
        $screen_name     = esc_html($data['screen_name'] ?? 'Screen');
        $layout_name     = esc_html($data['layout_name'] ?? 'Option');
        $author_name     = esc_html($data['author_name'] ?? 'Reviewer');
        $author_role     = esc_html($data['author_role'] ?? 'Member');
        $author_avatar   = esc_url($data['author_avatar'] ?? '');
        $message_text    = nl2br(esc_html($data['message_text'] ?? ''));
        $original_text   = !empty($data['original_text']) ? nl2br(esc_html($data['original_text'])) : '';
        $cta_url         = esc_url($data['cta_url'] ?? home_url());
        $cta_label       = esc_html($data['cta_label'] ?? 'Open in Reviewer ➔');

        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title><?php echo $badge_title; ?></title>
        </head>
        <body style="margin: 0; padding: 0; background-color: #f1f5f9; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b;">
          
          <table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #f1f5f9; padding: 30px 15px;">
            <tr>
              <td align="center">
                
                <!-- Main Email Card -->
                <table width="100%" border="0" cellspacing="0" cellpadding="0" style="max-width: 580px; background-color: #ffffff; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.06); border: 1px solid #e2e8f0;">
                  
                  <!-- Top Brand Header -->
                  <tr>
                    <td style="background-color: #1e293b; padding: 20px 28px; border-bottom: 3px solid #b02b2b;">
                      <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td>
                            <span style="display: inline-block; font-size: 13px; font-weight: 800; color: #ffffff; letter-spacing: 0.5px; text-transform: uppercase;">
                              Bowden Works <span style="color: #f87171;">•</span> Prototype Reviewer
                            </span>
                          </td>
                          <td align="right">
                            <span style="display: inline-block; background-color: rgba(176, 43, 43, 0.35); color: #fecaca; font-size: 11px; font-weight: 700; padding: 3px 10px; border-radius: 20px; border: 1px solid rgba(248, 113, 113, 0.4);">
                              <?php echo $badge_title; ?>
                            </span>
                          </td>
                        </tr>
                      </table>
                    </td>
                  </tr>

                  <!-- Breadcrumb / Context Bar -->
                  <tr>
                    <td style="background-color: #f8fafc; padding: 12px 28px; border-bottom: 1px solid #e2e8f0; font-size: 12px; color: #64748b;">
                      <strong>Project:</strong> <span style="color: #0f172a; font-weight: 700;"><?php echo $project_name; ?></span>
                      <span style="color: #cbd5e1; margin: 0 4px;">/</span>
                      <strong>Screen:</strong> <span style="color: #0f172a; font-weight: 600;"><?php echo $screen_name; ?></span>
                      <span style="color: #cbd5e1; margin: 0 4px;">/</span>
                      <span style="color: #b02b2b; font-weight: 600;"><?php echo $layout_name; ?></span>
                    </td>
                  </tr>

                  <!-- Email Body -->
                  <tr>
                    <td style="padding: 28px 28px 20px 28px;">
                      
                      <!-- Author Profile Pill -->
                      <table border="0" cellspacing="0" cellpadding="0" style="margin-bottom: 16px;">
                        <tr>
                          <?php if (!empty($author_avatar)): ?>
                          <td style="padding-right: 10px;">
                            <img src="<?php echo $author_avatar; ?>" alt="<?php echo $author_name; ?>" width="34" height="34" style="border-radius: 50%; display: block; border: 2px solid #ffffff; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                          </td>
                          <?php endif; ?>
                          <td>
                            <div style="font-size: 14px; font-weight: 800; color: #0f172a; line-height: 1.2;">
                              <?php echo $author_name; ?>
                            </div>
                            <div style="font-size: 11px; font-weight: 600; color: #b02b2b; text-transform: uppercase; letter-spacing: 0.3px;">
                              <?php echo $author_role; ?>
                            </div>
                          </td>
                        </tr>
                      </table>

                      <?php if (!empty($original_text)): ?>
                      <!-- Original Pin Quote (for replies) -->
                      <div style="background-color: #f1f5f9; border-left: 3px solid #94a3b8; border-radius: 4px 8px 8px 4px; padding: 10px 14px; margin-bottom: 14px; font-size: 12px; color: #475569; font-style: italic;">
                        <div style="font-size: 10px; font-weight: 700; color: #64748b; text-transform: uppercase; margin-bottom: 3px; font-style: normal;">Original Comment:</div>
                        <?php echo $original_text; ?>
                      </div>
                      <?php endif; ?>

                      <!-- New Feedback Message Bubble -->
                      <div style="background-color: #fff1f2; border: 1px solid #fecdd3; border-radius: 12px; padding: 16px 18px; margin-bottom: 24px;">
                        <div style="font-size: 14px; line-height: 1.6; color: #1e293b; font-weight: 500;">
                          <?php echo $message_text; ?>
                        </div>
                      </div>

                      <!-- Call to Action Button -->
                      <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td align="center" style="padding: 10px 0 20px 0;">
                            <a href="<?php echo $cta_url; ?>" target="_blank" style="display: inline-block; background-color: #b02b2b; color: #ffffff; font-size: 13px; font-weight: 800; text-decoration: none; padding: 12px 28px; border-radius: 10px; box-shadow: 0 3px 10px rgba(176,43,43,0.35);">
                              <?php echo $cta_label; ?>
                            </a>
                          </td>
                        </tr>
                      </table>

                    </td>
                  </tr>

                  <!-- Footer Notes -->
                  <tr>
                    <td style="background-color: #f8fafc; padding: 16px 28px; border-top: 1px solid #e2e8f0; font-size: 11px; color: #94a3b8; text-align: center; line-height: 1.5;">
                      You received this email because you are an assigned stakeholder on the <strong><?php echo $project_name; ?></strong> prototype project.
                      <br>To manage notification preferences, visit your WordPress Project dashboard.
                    </td>
                  </tr>

                </table>
                
              </td>
            </tr>
          </table>

        </body>
        </html>
        <?php
        return ob_get_clean();
    }
}
