<?php

namespace DaftPlug\Generatify\Features\HelpdeskAgent;

use DaftPlug\Generatify\Features\Chatbot\Prompt;
use DaftPlug\Generatify\Features\Chatbot\Response;
use DaftPlug\Generatify\Features\Connectors\Models;
use DaftPlug\Generatify\Helpers\Utils;
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class Handlers {
    public function __construct() {
        add_action( 'rest_api_init', [$this, 'registerRoutes'] );
    }

    public function registerRoutes() {
        register_rest_route( 'generatify/v1', '/helpdesk-agent/contact', [
            'methods'             => 'POST',
            'callback'            => [$this, 'handleContactForm'],
            'permission_callback' => '__return_true',
        ] );
    }

    public function handleContactForm( $request ) {
        if ( !wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) {
            return new \WP_Error('invalid_nonce', 'Invalid nonce', [
                'status' => 403,
            ]);
        }
        $name = sanitize_text_field( $request->get_param( 'name' ) );
        $email = sanitize_email( $request->get_param( 'email' ) );
        $message = sanitize_textarea_field( $request->get_param( 'message' ) );
        $page = sanitize_text_field( $request->get_param( 'page' ) );
        if ( empty( $name ) || empty( $email ) || empty( $message ) ) {
            return new \WP_REST_Response([
                'status'  => 'fail',
                'message' => __( 'Missing required fields.', 'generatify' ),
            ], 400);
        }
        if ( !is_email( $email ) ) {
            return new \WP_REST_Response([
                'status'  => 'fail',
                'message' => __( 'Please enter a valid email address.', 'generatify' ),
            ], 400);
        }
        // Determine recipient: plugin setting fallback to admin email
        $recipient = Utils::getSetting( 'helpdeskAgent[helpdeskAgent][message][contactEmail]' );
        $recipient = sanitize_email( ( $recipient ?: get_option( 'admin_email' ) ) );
        if ( !is_email( $recipient ) ) {
            // As a last resort, fail clearly to avoid sending to an invalid address
            return new \WP_REST_Response([
                'status'  => 'fail',
                'message' => __( 'No valid recipient email is configured.', 'generatify' ),
            ], 500);
        }
        // Build email
        $site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
        // translators: %s: sender name
        $subject = sprintf( __( 'New helpdesk message from %s', 'generatify' ), $name );
        // Prepare email content (avoid sprintf with % in HTML; use placeholders)
        $template = '
      <!doctype html>
      <html>
        <head>
        <meta name="viewport" content="width=device-width">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f9fafb; margin: 0; padding: 0;">
          <table role="presentation" width="100%" bgcolor="#f9fafb">
            <tr>
            <td>&nbsp;</td>
            <td width="700" style="padding:40px 0;">
              <table role="presentation" width="100%">
              <tr>
                <td align="center"><img src="{{logo_url}}" height="60" alt="{{logo_alt}}" style="border:none;max-width:100%;"></td>
              </tr>
              </table>
              <table role="presentation" width="100%" style="margin-top: 15px; background-color: #ffffff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
              <tr>
                <td style="padding:20px;">
                <table role="presentation" width="100%">
                  <tr>
                  <td>
                    <h3 style="font-family:sans-serif;font-size:17px;font-weight:bold;margin:0 0 10px 0;">👋 {{hello_title}}</h3>
                    <div style="margin:0;font-size: 14px;line-height: 20px;color: #333;">{{intro_text}}</div>
                    <blockquote style="margin: 18px 0;border-left: 4px solid #2563eb;color:#000;font-size:14px;line-height:20px;background: #f9fafb;border-radius: 8px;padding: 8px 16px;">{{message}}</blockquote>
                    <div style="margin:0;font-size: 14px;line-height: 20px;color: #333;">{{reply_hint}}</div>
                  </td>
                  </tr>
                </table>
                </td>
              </tr>
              </table>
              <table role="presentation" width="100%" style="margin-top: 25px;text-align:center;width:100%;">
              <tr>
                <td align="center" style="color:#99a1af;font-size:12px;line-height: 16px;">{{footer_text}}</td>
              </tr>
              </table>
            </td>
            <td>&nbsp;</td>
            </tr>
          </table>
        </body>
      </html>
    ';
        // Localized strings and sentences
        $hello_title = esc_html__( 'Hello,', 'generatify' );
        $sent_at = esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ) );
        $page_text = esc_html( ( $page ?: Utils::getCurrentUrl( true ) ) );
        $intro_text = sprintf(
            // translators: %1$s: sender name, %2$s: sender email, %3$s: page URL, %4$s: sent at date/time
            __( 'You have received a new message from <strong>%1$s (%2$s)</strong> via the Generatify helpdesk form on <strong>%3$s</strong>, sent on <strong>%4$s</strong>.', 'generatify' ),
            esc_html( $name ),
            esc_html( $email ),
            $page_text,
            $sent_at
        );
        $intro_text = wp_kses_post( $intro_text );
        $reply_hint = esc_html__( 'To respond, simply reply to this email.', 'generatify' );
        // translators: %s: settings URL
        $footer_text = sprintf( __( 'This message was sent by the <strong>Generatify</strong> plugin, developed by <a href="https://daftplug.com/">DaftPlug</a>.<br> To stop receiving these emails, you can update your helpdesk settings <a href="%s">here</a>.', 'generatify' ), esc_url( admin_url( '/admin.php?page=generatify-settings#/helpdesk-agent/' ) ) );
        $footer_text = wp_kses_post( $footer_text );
        $body = strtr( $template, [
            '{{logo_url}}'    => esc_url( plugins_url( 'assets/media/icons/logo.png', GENERATIFY_FILE ) ),
            '{{logo_alt}}'    => esc_attr__( 'Generatify Logo', 'generatify' ),
            '{{hello_title}}' => $hello_title,
            '{{intro_text}}'  => $intro_text,
            '{{message}}'     => nl2br( esc_html( $message ) ),
            '{{reply_hint}}'  => $reply_hint,
            '{{footer_text}}' => $footer_text,
        ] );
        // Headers: use site/admin as From to avoid SPF issues; add Reply-To for the user
        $from_email = get_option( 'admin_email' );
        $headers = ['Content-Type: text/html; charset=UTF-8', 'From: ' . $site_name . ' <' . $from_email . '>', 'Reply-To: ' . $name . ' <' . $email . '>'];
        // Allow customization via filters
        $subject = apply_filters(
            'generatify_helpdesk_contact_subject',
            $subject,
            $name,
            $email,
            $message
        );
        $body = apply_filters(
            'generatify_helpdesk_contact_body',
            $body,
            $name,
            $email,
            $message
        );
        $headers = apply_filters(
            'generatify_helpdesk_contact_headers',
            $headers,
            $name,
            $email,
            $message
        );
        $recipient = apply_filters(
            'generatify_helpdesk_contact_recipient',
            $recipient,
            $name,
            $email,
            $message
        );
        $sent = wp_mail(
            $recipient,
            $subject,
            $body,
            $headers
        );
        if ( !$sent ) {
            return new \WP_REST_Response([
                'status'  => 'fail',
                'message' => __( 'Failed to send your message. Please try again later.', 'generatify' ),
            ], 500);
        }
        return new \WP_REST_Response([
            'status'  => 'success',
            'message' => __( 'Your message has been sent successfully.', 'generatify' ),
        ], 200);
    }

}
