<?php
/**
 * Système de Notifications Automatisées AVI
 * 
 * - Rapport Hebdomadaire (lundi 9h) : completedActions de la semaine
 * - Rapport Mensuel (30j après inscription) : score_at_day_1 vs current_score, Sprint débloqué
 * - Alerte Crisis Mode : avis ≤2★ en mode manual → email urgence ; en mode auto → confirmation
 */

namespace Avision;

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

class Avision_Notifications {
    
    private $database;
    
    const SPRINT_THRESHOLDS = [55, 70, 85, 100];
    
    public function __construct() {
        $this->database = new Avision_Database();
        $this->database->init();
    }
    
    /**
     * Envoie un email avec priorité haute (pour crise) - réception instantanée via SMTP
     */
    public static function send_mail_high_priority($to, $subject, $message_html, $headers = []) {
        $default_headers = [
            'Content-Type: text/html; charset=UTF-8',
            'X-Priority: 1',
            'Importance: high'
        ];
        $all_headers = array_merge($default_headers, $headers);
        return wp_mail($to, $subject, $message_html, $all_headers);
    }
    
    /**
     * Alerte Crisis Mode - Avis ≤2★ en mode MANUAL → Email urgence immédiat (priorité haute SMTP)
     * @param string|null $proposed_response Proposition AVI pour validation (optionnel)
     */
    public function send_crisis_alert_email($audit, $review, $dashboard_url, $proposed_response = null) {
        $subject = "🚨 URGENT AVI - Avis négatif nécessite ton action";
        $stars = (int) ($review['rating'] ?? 0);
        $stars_visual = str_repeat('⭐', $stars) . str_repeat('☆', 5 - $stars);
        $review_text = $review['text'] ?? '(Pas de commentaire)';
        $reviewer = $review['reviewer_name'] ?? 'Anonyme';
        $to_email = isset($audit['email']) ? sanitize_email(trim((string) $audit['email'])) : '';
        if (!is_email($to_email)) {
            return false;
        }
        $wp_uid = 0;
        $wp_lookup = get_user_by('email', $to_email);
        if ($wp_lookup instanceof \WP_User) {
            $wp_uid = (int) $wp_lookup->ID;
        }
        $business_name = $audit['business_name'] ?? '';
        $message = $this->get_crisis_alert_html($audit, $reviewer, $stars_visual, $review_text, $dashboard_url, $proposed_response);

        $sent = false;
        if (class_exists('\Avision\Avision_Email_Manager')) {
            $data = [
                'recipient_email' => $to_email,
                'user_name' => $business_name !== '' ? $business_name : $reviewer,
                'business_name' => $business_name,
                'reviewer_name' => $reviewer,
                'stars_display' => $stars_visual,
                'review_text' => (string) $review_text,
                'dashboard_url' => $dashboard_url,
            ];
            if (!empty($proposed_response)) {
                $data['suggested_reply'] = (string) $proposed_response;
            }
            $sent = \Avision\Avision_Email_Manager::send_avi_email(
                $wp_uid,
                \Avision\Avision_Email_Manager::TYPE_CRISIS_URGENT,
                $data
            );
        }
        if (!$sent) {
            return self::send_mail_high_priority($to_email, $subject, $message);
        }
        return true;
    }
    
    /**
     * Confirmation "J'ai neutralisé une attaque" - Avis ≤2★ en mode AUTO
     */
    public function send_crisis_neutralized_email($audit, $review, $response_text, $dashboard_url) {
        $subject = "🛡️ AVI - J'ai neutralisé une attaque pour vous";
        $stars = (int) ($review['rating'] ?? 0);
        $stars_visual = str_repeat('⭐', $stars) . str_repeat('☆', 5 - $stars);
        $review_text = $review['text'] ?? '(Pas de commentaire)';
        $reviewer = $review['reviewer_name'] ?? 'Anonyme';
        $to_email = isset($audit['email']) ? sanitize_email(trim((string) $audit['email'])) : '';
        if (!is_email($to_email)) {
            return false;
        }
        $wp_uid = 0;
        $wp_lookup = get_user_by('email', $to_email);
        if ($wp_lookup instanceof \WP_User) {
            $wp_uid = (int) $wp_lookup->ID;
        }
        $business_name = $audit['business_name'] ?? '';
        $message = $this->get_crisis_neutralized_html($audit, $reviewer, $stars_visual, $review_text, $response_text, $dashboard_url);

        $sent = false;
        if (class_exists('\Avision\Avision_Email_Manager')) {
            $sent = \Avision\Avision_Email_Manager::send_avi_email(
                $wp_uid,
                \Avision\Avision_Email_Manager::TYPE_CRISIS_NEUTRALIZED,
                [
                    'recipient_email' => $to_email,
                    'user_name' => $business_name !== '' ? $business_name : $reviewer,
                    'business_name' => $business_name,
                    'reviewer_name' => $reviewer,
                    'stars_display' => $stars_visual,
                    'review_text' => (string) $review_text,
                    'reply_text' => (string) $response_text,
                    'dashboard_url' => $dashboard_url,
                ]
            );
        }
        if (!$sent) {
            $headers = ['Content-Type: text/html; charset=UTF-8'];
            return wp_mail($to_email, $subject, $message, $headers);
        }
        return true;
    }
    
    /**
     * Rapport hebdomadaire - completedActions (avis + posts)
     */
    public function send_weekly_report($audit, $actions) {
        $dashboard_url = $this->get_dashboard_url($audit);
        // Brevo template #34 — envoi transactionnel (plus de doublon wp_mail) ; voir avi-email-s11.php / options avi_brevo_tpl_weekly_report.
        $to_email = isset($audit['email']) ? sanitize_email(trim((string) $audit['email'])) : '';
        if (!is_email($to_email)) {
            return false;
        }
        $wp_uid = 0;
        $wp_lookup = get_user_by('email', $to_email);
        if ($wp_lookup instanceof \WP_User) {
            $wp_uid = (int) $wp_lookup->ID;
        }
        $reviews = (int) ($actions['reviews'] ?? 0);
        $posts = (int) ($actions['posts'] ?? 0);
        $total = $reviews + $posts;
        $company = $audit['business_name'] ?? 'Votre entreprise';

        $sent = false;
        if (class_exists('\Avision\Avision_Email_Manager')) {
            $sent = \Avision\Avision_Email_Manager::send_avi_email(
                $wp_uid,
                \Avision\Avision_Email_Manager::TYPE_WEEKLY_REPORT,
                [
                    'recipient_email' => $to_email,
                    'user_name' => $company,
                    'business_name' => $company,
                    'dashboard_url' => $dashboard_url,
                    'period' => '7 days',
                    'reviews_week' => (string) $reviews,
                    'posts_week' => (string) $posts,
                    'actions_total' => (string) $total,
                ]
            );
        }
        if ($sent) {
            $this->database->update_last_weekly_report_sent($audit['id']);
        }
        return $sent;
    }
    
    /**
     * Rapport mensuel - score progress + Félicitations si nouveau Sprint
     */
    public function send_monthly_report($audit, $new_sprint_unlocked = false, $sprint_label = '') {
        $dashboard_url = $this->get_dashboard_url($audit);
        // Brevo template #35 — envoi transactionnel (plus de doublon wp_mail) ; voir avi-email-s11.php / options avi_brevo_tpl_monthly_report.
        $to = isset($audit['email']) ? sanitize_email(trim((string) $audit['email'])) : '';
        $to = apply_filters('avision_monthly_report_recipient_email', $to, $audit);
        if (!is_email($to)) {
            return false;
        }
        $wp_uid = 0;
        $wp_lookup = get_user_by('email', $to);
        if ($wp_lookup instanceof \WP_User) {
            $wp_uid = (int) $wp_lookup->ID;
        }
        $company = $audit['business_name'] ?? 'Votre entreprise';
        $score = (int) ($audit['score'] ?? 0);
        $score_day1 = (int) ($audit['score_at_day_1'] ?? 0);

        $sent = false;
        if (class_exists('\Avision\Avision_Email_Manager')) {
            $sent = \Avision\Avision_Email_Manager::send_avi_email(
                $wp_uid,
                \Avision\Avision_Email_Manager::TYPE_MONTHLY_REPORT,
                [
                    'recipient_email' => $to,
                    'user_name' => $company,
                    'business_name' => $company,
                    'dashboard_url' => $dashboard_url,
                    'period' => '30 days',
                    'score_current' => (string) $score,
                    'score_day1' => (string) $score_day1,
                    'score' => (string) $score,
                    'sprint_unlocked' => $new_sprint_unlocked ? '1' : '0',
                    'sprint_label' => (string) $sprint_label,
                ]
            );
        }
        if ($sent) {
            $this->database->update_last_monthly_report_sent($audit['id']);
        }
        return $sent;
    }
    
    /**
     * Vérifie si un nouveau Sprint a été débloqué (score_at_day_1 vs current_score)
     */
    public function has_new_sprint_unlocked($score_at_day_1, $current_score) {
        $score_at_day_1 = (int) $score_at_day_1;
        $current_score = (int) $current_score;
        if ($current_score <= $score_at_day_1) return [false, ''];
        
        $unlocked = '';
        foreach (self::SPRINT_THRESHOLDS as $t) {
            if ($current_score >= $t && $score_at_day_1 < $t) {
                $labels = [55 => 'Sprint 1', 70 => 'Sprint 2', 85 => 'Sprint 3', 100 => 'Sprint 4'];
                $unlocked = $labels[$t] ?? "Seuil {$t}";
            }
        }
        return [$unlocked !== '', $unlocked];
    }
    
    private function get_dashboard_url($audit) {
        return add_query_arg(['audit_id' => $audit['id']], home_url('/premium-dashboard'));
    }
    
    private function get_crisis_alert_html($audit, $reviewer, $stars_visual, $review_text, $url, $proposed_response = null) {
        $response_block = '';
        if (!empty($proposed_response)) {
            $response_block = "
                <div style='background:#fef3c7;padding:15px;border-radius:8px;margin:15px 0;border-left:4px solid #d97706;'>
                    <p style='margin:0 0 8px 0;font-weight:bold;color:#92400e;'>💬 Proposition AVI à valider :</p>
                    <p style='margin:0;color:#78350f;white-space:pre-line;'>" . htmlspecialchars($proposed_response) . "</p>
                </div>";
        }
        return "
        <html><body style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;'>
            <div style='background:#fef2f2;border:2px solid #ef4444;border-radius:10px;padding:20px;'>
                <h2 style='color:#dc2626;margin:0;'>🚨 ALERTE - Avis négatif reçu</h2>
                <p style='color:#991b1b;margin:10px 0 0 0;'>Chef, un client mécontent vient de laisser un avis. Sans AVI, tu aurais pu le rater.</p>
            </div>
            <div style='background:#fff;padding:25px;border:1px solid #e5e7eb;margin-top:15px;'>
                <p><strong>{$stars_visual}</strong> | {$reviewer}</p>
                <p style='font-style:italic;color:#4b5563;'>\"{$review_text}\"</p>
                {$response_block}
                <p style='margin-top:20px;'><strong>Action requise :</strong> Valide ou modifie la réponse depuis ton Notification Hub.</p>
                <a href='{$url}' style='display:inline-block;background:#ef4444;color:white;padding:12px 24px;text-decoration:none;border-radius:6px;margin-top:15px;'>Accéder au Dashboard</a>
            </div>
            <p style='color:#6b7280;font-size:12px;margin-top:15px;'>AVI te protège 24/7. Réagis vite pour préserver ta réputation.</p>
        </body></html>";
    }
    
    private function get_crisis_neutralized_html($audit, $reviewer, $stars_visual, $review_text, $response_text, $url) {
        $response_preview = mb_substr($response_text, 0, 150) . (mb_strlen($response_text) > 150 ? '...' : '');
        return "
        <html><body style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;'>
            <div style='background:#ecfdf5;border:2px solid #10b981;border-radius:10px;padding:20px;'>
                <h2 style='color:#065f46;margin:0;'>🛡️ J'ai neutralisé une attaque pour vous</h2>
                <p style='color:#047857;margin:10px 0 0 0;'>Un avis négatif est arrivé. J'ai répondu automatiquement en ton nom.</p>
            </div>
            <div style='background:#fff;padding:25px;border:1px solid #e5e7eb;margin-top:15px;'>
                <p><strong>{$stars_visual}</strong> | {$reviewer}</p>
                <p style='font-style:italic;color:#4b5563;'>\"{$review_text}\"</p>
                <div style='background:#f0fdf4;padding:15px;border-radius:8px;margin:15px 0;'>
                    <p style='margin:0 0 8px 0;font-weight:bold;'>Ma réponse :</p>
                    <p style='margin:0;'>{$response_preview}</p>
                </div>
                <a href='{$url}' style='display:inline-block;background:#10b981;color:white;padding:12px 24px;text-decoration:none;border-radius:6px;'>Voir sur le Dashboard</a>
            </div>
        </body></html>";
    }
    
    private function get_weekly_report_html($audit, $actions, $url) {
        $reviews = $actions['reviews'] ?? 0;
        $posts = $actions['posts'] ?? 0;
        $total = $reviews + $posts;
        $company = $audit['business_name'] ?? 'Votre entreprise';
        
        return "
        <html><body style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;'>
            <div style='background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);padding:20px;border-radius:10px 10px 0 0;'>
                <h1 style='color:white;margin:0;'>📊 Rapport Hebdomadaire</h1>
                <p style='color:rgba(255,255,255,0.9);margin:5px 0 0 0;'>{$company}</p>
            </div>
            <div style='background:#fff;padding:25px;border:1px solid #e5e7eb;'>
                <p>Voici ton bilan de la semaine écoulée :</p>
                <ul>
                    <li><strong>{$reviews}</strong> avis auxquels j'ai répondu</li>
                    <li><strong>{$posts}</strong> posts publiés</li>
                </ul>
                <p><strong>Total : {$total}</strong> actions complétées par le Mode Gardien.</p>
                <a href='{$url}' style='display:inline-block;background:#667eea;color:white;padding:12px 24px;text-decoration:none;border-radius:6px;margin-top:15px;'>Ouvrir le Dashboard</a>
            </div>
        </body></html>";
    }
    
    private function get_monthly_report_html($audit, $new_sprint, $sprint_label, $url) {
        $company = $audit['business_name'] ?? 'Votre entreprise';
        $score = $audit['score'] ?? 0;
        $score_day1 = $audit['score_at_day_1'] ?? 0;
        $diff = max(0, $score - $score_day1);
        
        $felicitations_block = '';
        if ($new_sprint && $sprint_label) {
            $felicitations_block = "
            <div style='background:linear-gradient(135deg,#fef3c7,#fde68a);padding:20px;border-radius:10px;margin:20px 0;border:2px solid #f59e0b;'>
                <h3 style='margin:0 0 10px 0;color:#92400e;'>🎉 Félicitations !</h3>
                <p style='margin:0;color:#78350f;'>Tu as débloqué le <strong>{$sprint_label}</strong>. Ta progression est remarquable.</p>
            </div>";
        }
        
        return "
        <html><body style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;'>
            <div style='background:linear-gradient(135deg,#10b981 0%,#059669 100%);padding:20px;border-radius:10px 10px 0 0;'>
                <h1 style='color:white;margin:0;'>📈 Rapport Mensuel</h1>
                <p style='color:rgba(255,255,255,0.9);margin:5px 0 0 0;'>{$company}</p>
            </div>
            <div style='background:#fff;padding:25px;border:1px solid #e5e7eb;'>
                <p>Comparaison sur les 30 derniers jours :</p>
                <ul>
                    <li>Score au jour 1 : <strong>{$score_day1}/100</strong></li>
                    <li>Score actuel : <strong>{$score}/100</strong></li>
                    <li>Progression : <strong>+{$diff} points</strong></li>
                </ul>
                {$felicitations_block}
                <a href='{$url}' style='display:inline-block;background:#10b981;color:white;padding:12px 24px;text-decoration:none;border-radius:6px;margin-top:15px;'>Ouvrir le Dashboard</a>
            </div>
        </body></html>";
    }

    /**
     * Envoie l'email avertissement Smart Gallery (une seule fois).
     * ANTI-RÉGRESSION #65 #91 #92 #99 #100 #169 [Sprint 32]
     *
     * @param int    $profile_id ID profil avi_saas_profiles.
     * @param string $context    guardian|level3|level20 — texte étape 1 email.
     * @return bool
     */
    public static function send_gallery_warning_email( $profile_id, $context = 'guardian' ) {
        global $wpdb;

        $profiles_table = $wpdb->prefix . 'avi_saas_profiles';
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $profile = $wpdb->get_row( $wpdb->prepare(
            "SELECT p.id, p.user_id, p.business_name, p.city,
                    p.email_prefs, p.account_deleted_at
             FROM `{$profiles_table}` p
             WHERE p.id = %d
               AND p.account_deleted_at IS NULL
             LIMIT 1",
            (int) $profile_id
        ) );

        if ( ! $profile ) {
            return false;
        }

        $wp_user_id = (int) $profile->user_id;

        // Garde #169 — envoi unique.
        $meta_key = 'avi_gallery_warning_email_sent_' . (int) $profile_id;
        if ( get_user_meta( $wp_user_id, $meta_key, true ) ) {
            return false;
        }

        // Garde #91 — vérifier guardian_alerts dans email_prefs.
        $prefs = array();
        if ( ! empty( $profile->email_prefs ) ) {
            $decoded = json_decode( $profile->email_prefs, true );
            if ( is_array( $decoded ) ) {
                $prefs = $decoded;
            }
        }
        $guardian_alerts = isset( $prefs['guardian_alerts'] )
            ? (bool) $prefs['guardian_alerts']
            : true;

        if ( ! $guardian_alerts ) {
            return false;
        }

        $wp_user = get_userdata( $wp_user_id );
        if ( ! $wp_user ) {
            return false;
        }

        $user_email    = $wp_user->user_email;
        $user_name     = $wp_user->display_name ? $wp_user->display_name : $wp_user->user_login;
        $business_name = $profile->business_name ? $profile->business_name : $user_name;
        $dashboard_url = home_url( '/premium-dashboard/' );
        $gallery_url   = $dashboard_url . '#mediaDropZone';

        $context = sanitize_key( (string) $context );
        switch ( $context ) {
            case 'level3':
                $step1 = 'Open Level 3 (Photos Pack 1) in your dashboard → use the drop zone to upload your photos.';
                break;
            case 'level20':
                $step1 = 'Open Level 20 (Photos Pack 2) in your dashboard → use the drop zone to upload your photos.';
                break;
            case 'guardian':
            default:
                $step1 = 'Open your Guardian cockpit → scroll to the Smart Gallery section → use the drop zone.';
                break;
        }

        // ANTI-RÉGRESSION #100 — params double casse UPPER + lower.
        $data = array(
            'recipient_email' => $user_email,
            'USER_NAME'       => $user_name,
            'BUSINESS_NAME'   => $business_name,
            'DASHBOARD_URL'   => $dashboard_url,
            'GALLERY_URL'     => $gallery_url,
            'STEP1_CONTEXT'   => $step1,
            'user_name'       => $user_name,
            'business_name'   => $business_name,
            'dashboard_url'   => $dashboard_url,
            'gallery_url'     => $gallery_url,
            'step1_context'   => $step1,
        );

        $sent = \Avision\Avision_Email_Manager::send_avi_email(
            $wp_user_id,
            \Avision\Avision_Email_Manager::TYPE_GALLERY_WARNING,
            $data
        );

        if ( $sent ) {
            update_user_meta( $wp_user_id, $meta_key, 1 );
        }

        return $sent;
    }
}
