<?php
/**
 * Credit Alert Endpoint for BoostBot REST API.
 *
 * Called by the backend when a site's BoostCoin balance drops below key
 * thresholds (20%, 10%, 0%). Sends a branded HTML email to the site
 * admin via wp_mail().
 *
 * @package BoostBot
 * @since 1.3.0
 */

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

class BoostBot_Alerts_Endpoint extends BoostBot_Base_Endpoint {

    protected $rest_base = 'send-alert';

    public function register() {
        $this->register_route(
            '',
            'POST',
            [ $this, 'send_credit_alert' ],
            [ $this, 'admin_access' ]
        );
    }

    /**
     * Send a low-credit alert email to the site administrator.
     */
    public function send_credit_alert( $request ) {
        $level      = sanitize_text_field( $request->get_param( 'level' ) );
        $subject_en = sanitize_text_field( $request->get_param( 'subject_en' ) );
        $subject_he = sanitize_text_field( $request->get_param( 'subject_he' ) );
        $remaining  = floatval( $request->get_param( 'remaining' ) );
        $total      = floatval( $request->get_param( 'total' ) );
        $percent    = floatval( $request->get_param( 'percent' ) );

        if ( ! in_array( $level, [ 'warning', 'urgent', 'critical' ], true ) ) {
            return $this->error( 'invalid_level', 'Level must be warning, urgent, or critical', 400 );
        }

        $admin_email = get_option( 'admin_email' );
        if ( empty( $admin_email ) ) {
            return $this->error( 'no_admin_email', 'No admin email configured', 400 );
        }

        $locale  = get_locale();
        $is_rtl  = ( strpos( $locale, 'he' ) === 0 );
        $subject = $is_rtl ? $subject_he : $subject_en;

        $html = $this->build_alert_email( $level, $remaining, $total, $percent, $is_rtl );

        $headers = [ 'Content-Type: text/html; charset=UTF-8' ];
        $sent    = wp_mail( $admin_email, $subject, $html, $headers );

        if ( $sent ) {
            BoostBot_Logger::info( "Credit alert sent: level={$level} to={$admin_email} remaining={$remaining}" );
        } else {
            BoostBot_Logger::error( "Credit alert FAILED: level={$level} to={$admin_email}" );
        }

        return $this->success( [ 'sent' => $sent, 'to' => $admin_email ] );
    }

    /**
     * Build a branded HTML email for credit alerts.
     */
    private function build_alert_email( $level, $remaining, $total, $percent, $is_rtl ) {
        $site_name = get_bloginfo( 'name' );
        $site_url  = home_url();
        $admin_url = admin_url( 'admin.php?page=boostbot#/usage' );
        $dir       = $is_rtl ? 'rtl' : 'ltr';
        $align     = $is_rtl ? 'right' : 'left';

        $level_colors = [
            'warning'  => [ 'bg' => '#fef9e7', 'border' => '#f39c12', 'text' => '#856404', 'badge' => '#f39c12' ],
            'urgent'   => [ 'bg' => '#fdf2e9', 'border' => '#e67e22', 'text' => '#984d11', 'badge' => '#e67e22' ],
            'critical' => [ 'bg' => '#fdedec', 'border' => '#e74c3c', 'text' => '#922b21', 'badge' => '#e74c3c' ],
        ];
        $colors = $level_colors[ $level ] ?? $level_colors['warning'];

        if ( $is_rtl ) {
            $remaining_fmt = number_format( $remaining, 0 );
            $total_fmt     = number_format( $total, 0 );
            $percent_fmt   = number_format( $percent, 1 );

            $heading = $level === 'critical'
                ? 'הקרדיטים נגמרו — הצ\'אטבוט לא פעיל'
                : ( $level === 'urgent'
                    ? 'הקרדיטים כמעט נגמרו'
                    : 'הקרדיטים אוזלים' );

            $message = $level === 'critical'
                ? 'יתרת ה-BoostCoin שלך הגיעה לאפס. הצ\'אטבוט לא עונה יותר למבקרים באתר. רכוש קרדיטים כעת כדי לחדש את השירות.'
                : ( $level === 'urgent'
                    ? 'יתרת ה-BoostCoin שלך ירדה מתחת ל-10%. הצ\'אטבוט יפסיק לענות בקרוב. רכוש קרדיטים נוספים כדי להמשיך בפעילות.'
                    : 'יתרת ה-BoostCoin שלך ירדה מתחת ל-20%. מומלץ לרכוש קרדיטים נוספים כדי להבטיח שירות רציף.' );

            $balance_label  = 'יתרה נוכחית';
            $total_label    = 'סה"כ';
            $status_label   = 'סטטוס';
            $status_text    = $level === 'critical' ? 'לא פעיל' : ( $level === 'urgent' ? 'כמעט ריק' : 'נמוך' );
            $cta_text       = 'רכישת BoostCoin';
            $footer_text    = "הודעה זו נשלחה על ידי תוסף BoostBot באתר {$site_name}.";
            $footer_reason  = 'אתה מקבל הודעה זו כי אתה מנהל האתר.';
        } else {
            $remaining_fmt = number_format( $remaining, 0 );
            $total_fmt     = number_format( $total, 0 );
            $percent_fmt   = number_format( $percent, 1 );

            $heading = $level === 'critical'
                ? 'Credits Exhausted — Chatbot is Offline'
                : ( $level === 'urgent'
                    ? 'Credits Almost Depleted'
                    : 'Credits Running Low' );

            $message = $level === 'critical'
                ? 'Your BoostCoin balance has reached zero. Your chatbot is no longer responding to visitors. Purchase credits immediately to restore service.'
                : ( $level === 'urgent'
                    ? 'Your BoostCoin balance is below 10%. Your chatbot will stop responding very soon. Purchase additional credits now to keep your chatbot online.'
                    : 'Your BoostCoin balance has dropped below 20%. Top up now to ensure uninterrupted service.' );

            $balance_label  = 'Current Balance';
            $total_label    = 'Total';
            $status_label   = 'Status';
            $status_text    = $level === 'critical' ? 'Offline' : ( $level === 'urgent' ? 'Almost Empty' : 'Low' );
            $cta_text       = 'Purchase BoostCoin';
            $footer_text    = "This alert was sent by the BoostBot plugin on {$site_name}.";
            $footer_reason  = "You're receiving this because you're the site administrator.";
        }

        $badge_bg    = esc_attr( $colors['badge'] );
        $text_color  = esc_attr( $colors['text'] );
        $bg_color    = esc_attr( $colors['bg'] );
        $border_clr  = esc_attr( $colors['border'] );
        $safe_dir    = esc_attr( $dir );
        $safe_align  = esc_attr( $align );
        $safe_url    = esc_url( $admin_url );
        $safe_level  = esc_html( $level );

        return '<!DOCTYPE html>'
            . '<html dir="' . $safe_dir . '" lang="' . $safe_dir . '">'
            . '<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>'
            . '<body style="margin:0; padding:0; background-color:#f4f5f7; font-family:Arial,Helvetica,sans-serif;">'
            . '<table width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f5f7; padding:24px 0;">'
            . '<tr><td align="center">'
            . '<table width="600" cellpadding="0" cellspacing="0" style="max-width:600px; width:100%;">'
            . '<tr><td style="background:#1a365d; padding:24px 32px; border-radius:12px 12px 0 0; text-align:center;">'
            . '<span style="color:#ffffff; font-size:22px; font-weight:bold; letter-spacing:0.5px;">BoostBot</span>'
            . '</td></tr>'
            . '<tr><td style="background:#ffffff; padding:32px; text-align:' . $safe_align . ';">'
            . '<table cellpadding="0" cellspacing="0" style="margin-bottom:20px;">'
            . '<tr><td style="background:' . $badge_bg . '; color:#ffffff; font-size:12px; font-weight:bold; padding:4px 12px; border-radius:12px; text-transform:uppercase;">'
            . $safe_level
            . '</td></tr>'
            . '</table>'
            . '<h2 style="margin:0 0 16px; color:' . $text_color . '; font-size:20px;">' . esc_html( $heading ) . '</h2>'
            . '<p style="margin:0 0 24px; color:#4a5568; font-size:15px; line-height:1.6;">' . esc_html( $message ) . '</p>'
            . '<table width="100%" cellpadding="0" cellspacing="0" style="background:' . $bg_color . '; border:1px solid ' . $border_clr . '; border-radius:8px; margin-bottom:24px;">'
            . '<tr><td style="padding:16px;">'
            . '<table width="100%" cellpadding="0" cellspacing="0">'
            . '<tr>'
            . '<td style="color:#4a5568; font-size:14px; padding:4px 0;"><strong>' . esc_html( $balance_label ) . ':</strong></td>'
            . '<td style="color:#1a202c; font-size:14px; padding:4px 0; text-align:' . $safe_align . '; font-weight:bold;">' . esc_html( $remaining_fmt ) . ' BoostCoin (' . esc_html( $percent_fmt ) . '%)</td>'
            . '</tr>'
            . '<tr>'
            . '<td style="color:#4a5568; font-size:14px; padding:4px 0;"><strong>' . esc_html( $total_label ) . ':</strong></td>'
            . '<td style="color:#1a202c; font-size:14px; padding:4px 0; text-align:' . $safe_align . ';">' . esc_html( $total_fmt ) . ' BoostCoin</td>'
            . '</tr>'
            . '<tr>'
            . '<td style="color:#4a5568; font-size:14px; padding:4px 0;"><strong>' . esc_html( $status_label ) . ':</strong></td>'
            . '<td style="color:' . $text_color . '; font-size:14px; padding:4px 0; text-align:' . $safe_align . '; font-weight:bold;">' . esc_html( $status_text ) . '</td>'
            . '</tr>'
            . '</table>'
            . '</td></tr>'
            . '</table>'
            . '<table cellpadding="0" cellspacing="0" style="margin:0 auto;">'
            . '<tr><td style="background:#1a365d; border-radius:8px;">'
            . '<a href="' . $safe_url . '" target="_blank" style="display:inline-block; padding:14px 32px; color:#ffffff; text-decoration:none; font-size:15px; font-weight:bold;">'
            . esc_html( $cta_text )
            . '</a>'
            . '</td></tr>'
            . '</table>'
            . '</td></tr>'
            . '<tr><td style="background:#f7fafc; padding:20px 32px; border-radius:0 0 12px 12px; text-align:center;">'
            . '<p style="margin:0 0 4px; color:#a0aec0; font-size:12px;">' . esc_html( $footer_text ) . '</p>'
            . '<p style="margin:0; color:#a0aec0; font-size:12px;">' . esc_html( $footer_reason ) . '</p>'
            . '</td></tr>'
            . '</table>'
            . '</td></tr>'
            . '</table>'
            . '</body>'
            . '</html>';
    }
}
