<?php
/**
 * Login Failed History & CSV Export
 *
 * Handles the display of the failed login attempts table (rendered inside
 * the "Login History" tab on the settings page) and the CSV download handler.
 *
 * @package AdminLoginGuardBranding
 */

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

/**
 * Render the failed login history table.
 *
 * Fetches the last 2 000 records from the custom login-history table
 * and outputs them in a DataTables-powered HTML table. A "Download CSV"
 * link is appended after the table.
 *
 * @since 1.0.0
 *
 * @return void
 */
function admilogu_history_page($type = 'failed')
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'admilogu_login_history';
    
    if ($type === 'failed') {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE status != 'success' ORDER BY time DESC LIMIT %d", 2000));
        $title = __('Failed Login Attempts', 'admin-login-guard-branding');
        $status_color = '#d63638';
        $status_text = __('Failed', 'admin-login-guard-branding');
    } else {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE status = 'success' ORDER BY time DESC LIMIT %d", 2000));
        $title = __('Successful Logins', 'admin-login-guard-branding');
        $status_color = '#00a32a';
        $status_text = __('Success', 'admin-login-guard-branding');
    }

    ?>
    <div class="adminlgb-history-container">
        <table class="display adminlgb_history-table" style="width:100%">
            <thead>
                <tr>
                    <th><?php esc_html_e('ID', 'admin-login-guard-branding'); ?></th>
                    <th><?php esc_html_e('IP Address', 'admin-login-guard-branding'); ?></th>
                    <th><?php esc_html_e('Username', 'admin-login-guard-branding'); ?></th>
                    <th><?php esc_html_e('Status', 'admin-login-guard-branding'); ?></th>
                    <th><?php esc_html_e('Time', 'admin-login-guard-branding'); ?></th>
                    <th><?php esc_html_e('User Agent', 'admin-login-guard-branding'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($results as $row): ?>
                    <tr>
                        <td><?php echo esc_html($row->id); ?></td>
                        <td><?php echo esc_html($row->ip_address); ?></td>
                        <td><?php echo esc_html($row->username); ?></td>
                        <td>
                            <span style="color: <?php echo esc_attr($status_color); ?>; font-weight: bold;"><?php echo esc_html($status_text); ?></span>
                        </td>
                        <td><?php echo esc_html($row->time); ?></td>
                        <td><?php echo esc_html($row->user_agent); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <p style="margin-top: 20px;">
            <a href="<?php echo esc_url(admin_url('admin-post.php?action=admilogu_download_history')); ?>"
                class="button button-secondary">
                <?php esc_html_e('Download CSV (All Records)', 'admin-login-guard-branding'); ?>
            </a>
        </p>
    </div>
    <?php
}

/**
 * Process the CSV export of failed login history.
 *
 * Verifies the current user has the `manage_options` capability, fetches
 * every record from the history table, and streams it as a downloadable
 * CSV file. Execution is terminated after output to prevent WordPress
 * from appending any additional content.
 *
 * Hooked to: `admin_post_admilogu_download_history`
 *
 * @since 1.0.0
 *
 * @return void
 */
function admilogu_process_csv_export()
{
    if (!current_user_can('manage_options')) {
        return;
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'admilogu_login_history';
    $results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY time DESC", ARRAY_A); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter

    if (empty($results)) {
        wp_die(esc_html__('No records found.', 'admin-login-guard-branding'));
    }

    $filename = 'login_history_' . gmdate('Y-m-d_H-i-s') . '.csv';

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $output = fopen('php://output', 'w');

    // Header row
    fputcsv($output, array(
        __('ID', 'admin-login-guard-branding'),
        __('IP Address', 'admin-login-guard-branding'),
        __('Username', 'admin-login-guard-branding'),
        __('Status', 'admin-login-guard-branding'),
        __('Time', 'admin-login-guard-branding'),
        __('User Agent', 'admin-login-guard-branding')
    ));

    foreach ($results as $row) {
        // Ensure status column exists in older records
        if (!isset($row['status'])) {
            $row['status'] = 'failed';
        }
        
        // Reorder array to match headers
        $csv_row = array(
            $row['id'],
            $row['ip_address'],
            $row['username'],
            $row['status'],
            $row['time'],
            $row['user_agent']
        );
        fputcsv($output, $csv_row);
    }

    @fclose($output); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
    exit;
}
add_action('admin_post_admilogu_download_history', 'admilogu_process_csv_export');
