<?php
if (!defined('ABSPATH')) {
    exit;
}

class Manfiet_Email_Reports {
    private $table;

    public function __construct() {
        global $wpdb;
        $this->table = $wpdb->prefix . 'manfiet_expenses';
        add_action('manfiet_send_monthly_report', [$this, 'send_monthly_report']);
    }

    public function send_monthly_report() {
        global $wpdb;
        $current_month = gmdate('Y-m');
        $table = $this->table;
        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reporting queries run on plugin-owned table.

        $admins = get_users(['role' => 'administrator', 'fields' => ['user_email']]);
        $email_list = wp_list_pluck($admins, 'user_email');

        $total_spent = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT SUM(amount) FROM %i WHERE DATE_FORMAT(date, '%%Y-%%m') = %s",
                $table,
                $current_month
            )
        );

        $expenses = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT category, SUM(amount) as total FROM %i WHERE DATE_FORMAT(date, '%%Y-%%m') = %s GROUP BY category",
                $table,
                $current_month
            ),
            ARRAY_A
        );
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

        $symbol = class_exists('Manfiet_Expense_Tracker_Settings') ? Manfiet_Expense_Tracker_Settings::get_current_currency_symbol() : '$';

        $message = '<h2>' . __('Monthly Expense Report', 'manfi-expense-tracker') . '</h2>';
        $message .= '<p>' . sprintf(
            /* translators: 1: currency symbol, 2: total spent for the current month. */
            __('Total Spent: %1$s%2$s', 'manfi-expense-tracker'),
            $symbol,
            $total_spent
        ) . '</p>';
        $message .= '<table border="1" cellpadding="5">';
        $message .= '<tr><th>' . __('Category', 'manfi-expense-tracker') . '</th><th>' . __('Total', 'manfi-expense-tracker') . '</th></tr>';

        foreach ($expenses as $expense) {
            $message .= sprintf('<tr><td>%s</td><td>%s%s</td></tr>', esc_html($expense['category']), esc_html($symbol), esc_html($expense['total']));
        }

        $message .= '</table>';

        $sender_name = get_option('manfiet_email_sender_name', 'Manfi Expense Tracker');
        $domain = wp_parse_url(get_site_url(), PHP_URL_HOST);
        $default_email = 'no-reply@' . ($domain ? $domain : 'manfietracker.com');
        $sender_email = get_option('manfiet_email_sender_address', $default_email);

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            sprintf('From: %s <%s>', $sender_name, $sender_email)
        ];
        wp_mail($email_list, __('Manfi Expense Tracker: Monthly Report', 'manfi-expense-tracker'), $message, $headers);
    }
}
