<?php
// lucydream-transaction-history.php

// Add "Credits" section to WordPress admin dashboard with transaction history
add_action('admin_menu', 'lucydream_add_credits_menu');
function lucydream_add_credits_menu() {
    add_menu_page(
        'LucyDream Credits',
        'LucyDream Credits',
        'read',
        'lucydream-credits',
        'lucydream_credits_page',
        'dashicons-money'
    );
}

// Handle AJAX request to refresh transactions
add_action('wp_ajax_lucydream_refresh_transactions', 'lucydream_refresh_transactions');
function lucydream_refresh_transactions() {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'Permission denied'));
        wp_die();
    }

    global $wpdb;

    // Fetch purchases from payments table
    $payments_table = $wpdb->prefix . 'lucydream_payments';
    $purchases = $wpdb->get_results("SELECT * FROM $payments_table WHERE status = 'completed' ORDER BY created_at DESC");

    // Fetch manual gifts from user meta
    $gifts = $wpdb->get_results("SELECT user_id, meta_key, meta_value FROM {$wpdb->usermeta} WHERE meta_key LIKE 'credit_transactions_%'");

    // Fetch expenditures from user meta
    $expenditures = $wpdb->get_results("SELECT user_id, meta_key, meta_value FROM {$wpdb->usermeta} WHERE meta_key LIKE 'credit_expenditures_%'");

    // Collect all transactions in an array
    $all_tx = [];

    // Process purchases
    foreach ($purchases as $tx) {
        $user = get_userdata($tx->user_id);
        $email = $user ? esc_html($user->user_email) : 'Unknown';
        $all_tx[] = [
            'date' => $tx->created_at,
            'user_id' => $tx->user_id,
            'email' => $email,
            'credits' => $tx->credits,
            'tx_id' => $tx->transaction_id,
            'psp' => esc_html(strtoupper($tx->psp)),
            'type' => 'Purchase',
            'referred' => '', // Empty for now
            'source' => 'purchase',
            'delete_id' => $tx->transaction_id,
        ];
    }

    // Process manual gifts
    foreach ($gifts as $gift) {
        $data = maybe_unserialize($gift->meta_value);
        if (is_array($data) && isset($data['payment_type']) && $data['payment_type'] === 'manual_gift') {
            $user = get_userdata($gift->user_id);
            $email = $user ? esc_html($user->user_email) : 'Unknown';
            $all_tx[] = [
                'date' => $data['date'],
                'user_id' => $gift->user_id,
                'email' => $email,
                'credits' => $data['credits'],
                'tx_id' => $data['transaction_id'],
                'psp' => 'Manual',
                'type' => 'Gift',
                'referred' => '',
                'source' => 'meta',
                'delete_id' => $gift->meta_key,
            ];
        }
    }

    // Process expenditures (credits shown as positive, but type indicates spend)
    foreach ($expenditures as $exp) {
        $data = maybe_unserialize($exp->meta_value);
        if (is_array($data)) {
            $user = get_userdata($exp->user_id);
            $email = $user ? esc_html($user->user_email) : 'Unknown';
            $all_tx[] = [
                'date' => $data['date'],
                'user_id' => $exp->user_id,
                'email' => $email,
                'credits' => $data['credits'], // Positive value, type shows it's a spend
                'tx_id' => $data['transaction_id'],
                'psp' => 'Internal',
                'type' => 'Expenditure',
                'referred' => esc_html($data['reason'] ?? ''), // Use reason here if available (adjust column usage as needed)
                'source' => 'meta',
                'delete_id' => $exp->meta_key,
            ];
        }
    }

    // Get sort parameters
    $sort_column = isset($_POST['sort_column']) ? sanitize_text_field($_POST['sort_column']) : 'date';
    $sort_dir = isset($_POST['sort_dir']) && in_array($_POST['sort_dir'], ['asc', 'desc']) ? $_POST['sort_dir'] : 'desc';

    // Check if filters should be applied
    $apply_filters = isset($_POST['apply_filters']) && $_POST['apply_filters'] === 'true';

    if ($apply_filters && isset($_POST['filter_columns']) && is_array($_POST['filter_columns']) && isset($_POST['filter_values']) && is_array($_POST['filter_values'])) {
        $filter_columns = array_map('sanitize_text_field', $_POST['filter_columns']);
        $filter_values = array_map('sanitize_text_field', $_POST['filter_values']);
        if (count($filter_columns) === count($filter_values)) {
            for ($i = 0; $i < count($filter_columns); $i++) {
                $col = $filter_columns[$i];
                $val = $filter_values[$i];
                if ($col !== '' && $val !== '') {
                    $all_tx = array_filter($all_tx, function($tx) use ($col, $val) {
                        return stripos((string)$tx[$col], $val) !== false;
                    });
                }
            }
        }
    }

    // Sort all transactions
    usort($all_tx, function($a, $b) use ($sort_column, $sort_dir) {
        $valA = $a[$sort_column];
        $valB = $b[$sort_column];

        if ($sort_column === 'date') {
            $valA = strtotime($valA);
            $valB = strtotime($valB);
        } elseif (in_array($sort_column, ['user_id', 'credits'])) {
            $valA = (int)$valA;
            $valB = (int)$valB;
        } else {
            $valA = strtolower((string)$valA);
            $valB = strtolower((string)$valB);
            return ($sort_dir === 'asc') ? strcmp($valA, $valB) : strcmp($valB, $valA);
        }

        if ($valA === $valB) return 0;
        return ($sort_dir === 'asc') ? ($valA > $valB ? 1 : -1) : ($valA > $valB ? -1 : 1);
    });

    // Build HTML
    $html = '';
    if (empty($all_tx)) {
        $html = '<tr><td colspan="9">No transactions available.</td></tr>';
    } else {
        foreach ($all_tx as $tx) {
            $html .= '<tr>';
            $html .= '<td><input type="checkbox" class="select-transaction" data-source="' . esc_attr($tx['source']) . '" data-user-id="' . esc_attr($tx['user_id']) . '" data-delete-id="' . esc_attr($tx['delete_id']) . '"></td>';
            $html .= '<td>' . esc_html($tx['user_id']) . '</td>';
            $html .= '<td>' . $tx['email'] . '</td>';
            $html .= '<td>' . esc_html($tx['credits']) . '</td>';
            $html .= '<td>' . esc_html($tx['date']) . '</td>';
            $html .= '<td>' . esc_html($tx['tx_id']) . '</td>';
            $html .= '<td>' . $tx['psp'] . '</td>';
            $html .= '<td>' . esc_html($tx['type']) . '</td>';
            $html .= '<td>' . $tx['referred'] . '</td>';
            $html .= '</tr>';
        }
    }

    wp_send_json_success(array('html' => $html));
    wp_die();
}

// Handle AJAX request to delete transactions
add_action('wp_ajax_lucydream_delete_transactions', 'lucydream_delete_transactions');
function lucydream_delete_transactions() {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'Permission denied'));
        wp_die();
    }

    global $wpdb;

    $selected = isset($_POST['selected']) ? $_POST['selected'] : [];
    if (!is_array($selected) || empty($selected)) {
        wp_send_json_error(array('message' => 'No transactions selected'));
        wp_die();
    }

    $payments_table = $wpdb->prefix . 'lucydream_payments';

    foreach ($selected as $item) {
        $source = isset($item['source']) ? sanitize_text_field($item['source']) : '';
        $user_id = isset($item['user_id']) ? intval($item['user_id']) : 0;
        $delete_id = isset($item['delete_id']) ? sanitize_text_field($item['delete_id']) : '';

        if ($source === 'purchase' && $delete_id) {
            $wpdb->delete($payments_table, ['transaction_id' => $delete_id]);
        } elseif ($source === 'meta' && $user_id && $delete_id) {
            delete_user_meta($user_id, $delete_id);
        }
    }

    wp_send_json_success();
    wp_die();
}

function lucydream_credits_page() {
    settings_errors('lucydream_credits');

    echo '<div class="wrap"><h1>Credits</h1>';

    echo '<h2>Credit Transaction History <button id="lucydream-refresh-transactions" class="button">Refresh All</button> <button id="lucydream-delete-transactions" class="button" style="color: red;">Delete</button></h2>';
    
    echo '<div id="filter-container">';
    echo '<div class="filter-row">Filter by: <select class="filter-column">';
    echo '<option value="">-- Select Column --</option>';
    echo '<option value="user_id">User ID</option>';
    echo '<option value="email">Email</option>';
    echo '<option value="credits">Credits</option>';
    echo '<option value="date">Date</option>';
    echo '<option value="tx_id">Transaction ID</option>';
    echo '<option value="psp">PSP</option>';
    echo '<option value="type">Type</option>';
    echo '<option value="referred">Reason</option>';
    echo '</select>';
    echo ' <input type="text" class="filter-value" placeholder="Enter value">';
    echo ' <button class="remove-filter button">Remove</button></div>';
    echo '</div>';
    echo '<button id="add-filter" class="button" style="margin-top: 10px; margin-bottom: 10px;">Add filter</button>';
    echo '<button id="apply-filters" class="button" style="font-weight: bold; margin-top: 10px; margin-bottom: 10px; margin-left: 5px;">Apply Filters</button>';

    echo '<table class="wp-list-table widefat fixed striped" id="lucydream-transaction-table">';
    echo '<thead><tr>';
    echo '<th><input type="checkbox" id="select-all"></th>';
    echo '<th data-column="user_id">User ID</th>';
    echo '<th data-column="email">Email</th>';
    echo '<th data-column="credits">Credits</th>';
    echo '<th data-column="date" class="desc">Date</th>';
    echo '<th data-column="tx_id">Transaction ID</th>';
    echo '<th data-column="psp">PSP</th>';
    echo '<th data-column="type">Type</th>';
    echo '<th data-column="referred">Reason</th>';
    echo '</tr></thead>';
    echo '<tbody id="lucydream-transaction-body">';

    // Initial placeholder until AJAX loads
    echo '<tr><td colspan="9">Click Refresh to load all transactions or use filters.</td></tr>';

    echo '</tbody></table>';
    echo '</div>';

    echo '<style>
    thead th.asc::after { content: " \25b2"; }
    thead th.desc::after { content: " \25bc"; }
    thead th { cursor: pointer; }
    thead th:first-child, tbody td:first-child { width: 60px; text-align: center; padding: 0; }
    </style>';

    echo '<script>
    jQuery(document).ready(function($) {
        var filtersApplied = false;
        var currentSortColumn = "date";
        var currentSortDir = "desc";

        $("#add-filter").click(function() {
            var newFilter = \'<div class="filter-row">Filter by: <select class="filter-column"><option value="">-- Select Column --</option><option value="user_id">User ID</option><option value="email">Email</option><option value="credits">Credits</option><option value="date">Date</option><option value="tx_id">Transaction ID</option><option value="psp">PSP</option><option value="type">Type</option><option value="referred">Reason</option></select> <input type="text" class="filter-value" placeholder="Enter value"> <button class="remove-filter button">Remove</button></div>\';
            $("#filter-container").append(newFilter);
        });

        $(document).on("click", ".remove-filter", function() {
            $(this).closest(".filter-row").remove();
        });

        $(document).on("change", "#select-all", function() {
            $("#lucydream-transaction-body .select-transaction").prop("checked", this.checked);
        });

        $("thead th").click(function() {
            var column = $(this).data("column");
            if (!column) return;

            if (column === currentSortColumn) {
                currentSortDir = (currentSortDir === "asc") ? "desc" : "asc";
            } else {
                currentSortColumn = column;
                currentSortDir = "desc";
            }

            $("thead th").removeClass("asc desc");
            $(this).addClass(currentSortDir);

            loadTransactions(filtersApplied);
        });

        $("#lucydream-delete-transactions").click(function() {
            var selected = [];
            $(".select-transaction:checked").each(function() {
                selected.push({
                    source: $(this).data("source"),
                    user_id: $(this).data("user-id"),
                    delete_id: $(this).data("delete-id")
                });
            });

            if (selected.length === 0) {
                alert("No transactions selected");
                return;
            }

            if (!confirm("Are you sure you want to delete " + selected.length + " transactions?")) {
                return;
            }

            $.ajax({
                url: ajaxurl,
                type: "POST",
                data: {
                    action: "lucydream_delete_transactions",
                    selected: selected
                },
                success: function(response) {
                    if (response.success) {
                        alert("Transactions deleted successfully.");
                        loadTransactions(filtersApplied);
                    } else {
                        alert(response.data.message || "Error deleting transactions");
                    }
                }
            });
        });

        function loadTransactions(applyFilters) {
            var data = {
                action: "lucydream_refresh_transactions",
                apply_filters: applyFilters ? "true" : "false",
                sort_column: currentSortColumn,
                sort_dir: currentSortDir
            };

            if (applyFilters) {
                var filter_columns = [];
                var filter_values = [];
                $(".filter-column").each(function() {
                    filter_columns.push($(this).val());
                });
                $(".filter-value").each(function() {
                    filter_values.push($(this).val());
                });
                data.filter_columns = filter_columns;
                data.filter_values = filter_values;
            }

            $.ajax({
                url: ajaxurl,
                type: "POST",
                data: data,
                success: function(response) {
                    if (response.success) {
                        $("#lucydream-transaction-body").html(response.data.html);
                        $("#select-all").prop("checked", false);
                    } else {
                        alert(response.data.message);
                    }
                }
            });
        }

        $("#lucydream-refresh-transactions").click(function() {
            filtersApplied = false;
            loadTransactions(false);
        });

        $("#apply-filters").click(function() {
            filtersApplied = true;
            loadTransactions(true);
        });
    });
    </script>';
}
?>