<?php
/**
 * Orders admin page
 *
 * @package    Subscription_System
 * @subpackage Subscription_System/admin/partials
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Get orders with pagination
$page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

global $wpdb;
$orders_table = $wpdb->prefix . 'subscription_orders';
$subscriptions_table = $wpdb->prefix . 'subscriptions';
$plans_table = $wpdb->prefix . 'subscription_plans';

// Get total orders count
$total_orders = $wpdb->get_var("SELECT COUNT(*) FROM $orders_table");
$total_pages = ceil($total_orders / $per_page);

// Get orders with subscription and plan details
$orders = $wpdb->get_results(
    "SELECT o.*, s.plan_id, p.plan_name 
     FROM $orders_table o
     LEFT JOIN $subscriptions_table s ON o.subscription_id = s.id
     LEFT JOIN $plans_table p ON s.plan_id = p.id
     ORDER BY o.created_at DESC
     LIMIT $offset, $per_page"
);

// Get revenue statistics
$total_revenue = Subs_Sys_Order::get_total_revenue();
$monthly_revenue = Subs_Sys_Order::get_total_revenue('this_month');
$today_revenue = Subs_Sys_Order::get_total_revenue('today');

// Get order counts by status
$completed_orders = Subs_Sys_Order::get_order_count_by_status('completed');
$pending_orders = Subs_Sys_Order::get_order_count_by_status('pending');
$failed_orders = Subs_Sys_Order::get_order_count_by_status('failed');
?>

<div class="wrap">
    <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
    
    <div class="ss-admin-dashboard">
        <div class="ss-stats-cards">
            <div class="ss-stats-card">
                <h3><?php esc_html_e('Total Revenue', 'subscription-system'); ?></h3>
                <div class="ss-stats-value">$<?php echo esc_html(number_format($total_revenue, 2)); ?></div>
            </div>
            
            <div class="ss-stats-card">
                <h3><?php esc_html_e('Monthly Revenue', 'subscription-system'); ?></h3>
                <div class="ss-stats-value">$<?php echo esc_html(number_format($monthly_revenue, 2)); ?></div>
            </div>
            
            <div class="ss-stats-card">
                <h3><?php esc_html_e('Today\'s Revenue', 'subscription-system'); ?></h3>
                <div class="ss-stats-value">$<?php echo esc_html(number_format($today_revenue, 2)); ?></div>
            </div>
            
            <div class="ss-stats-card">
                <h3><?php esc_html_e('Total Orders', 'subscription-system'); ?></h3>
                <div class="ss-stats-value"><?php echo esc_html($total_orders); ?></div>
            </div>
        </div>
        
        <div class="ss-orders-table-container">
            <h2><?php esc_html_e('Recent Orders', 'subscription-system'); ?></h2>
            
            <?php if (empty($orders)) : ?>
                <p><?php esc_html_e('No orders found.', 'subscription-system'); ?></p>
            <?php else : ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Order #', 'subscription-system'); ?></th>
                            <th><?php esc_html_e('Date', 'subscription-system'); ?></th>
                            <th><?php esc_html_e('Customer', 'subscription-system'); ?></th>
                            <th><?php esc_html_e('Plan', 'subscription-system'); ?></th>
                            <th><?php esc_html_e('Amount', 'subscription-system'); ?></th>
                            <th><?php esc_html_e('Status', 'subscription-system'); ?></th>
                            <th><?php esc_html_e('Actions', 'subscription-system'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orders as $order) : ?>
                            <tr>
                                <td><?php echo esc_html($order->order_number); ?></td>
                                <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($order->transaction_date))); ?></td>
                                <td>
                                    <?php echo esc_html($order->billing_name); ?><br>
                                    <small><?php echo esc_html($order->billing_email); ?></small>
                                </td>
                                <td><?php echo esc_html($order->plan_name); ?></td>
                                <td>$<?php echo esc_html(number_format($order->amount, 2)); ?></td>
                                <td>
                                    <span class="order-status <?php echo esc_attr($order->status); ?>">
                                        <?php echo esc_html(ucfirst($order->status)); ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="button view-order" data-order-id="<?php echo esc_attr($order->id); ?>">
                                        <?php esc_html_e('View', 'subscription-system'); ?>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <?php if ($total_pages > 1) : ?>
                    <div class="tablenav">
                        <div class="tablenav-pages">
                            <span class="displaying-num">
                                <?php 
                                // translators: %s is the number of order items
                                printf(esc_html(_n('%s item', '%s items', $total_orders, 'subscription-system')), esc_html(number_format_i18n($total_orders))); 
                                ?>
                            </span>
                            
                            <span class="pagination-links">
                                <?php
                                echo wp_kses_post(paginate_links(array(
                                    'base' => add_query_arg('paged', '%#%'),
                                    'format' => '',
                                    'prev_text' => '&laquo;',
                                    'next_text' => '&raquo;',
                                    'total' => $total_pages,
                                    'current' => $page,
                                )));
                                ?>
                            </span>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Order Details Modal -->
    <div id="order-details-modal" class="ss-modal">
        <div class="ss-modal-content">
            <span class="ss-modal-close">&times;</span>
            <div id="order-details-content"></div>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // View order details
    $('.view-order').on('click', function() {
        var orderId = $(this).data('order-id');
        
        // Show loading state
        $('#order-details-content').html('<p>Loading order details...</p>');
        $('#order-details-modal').show();
        
        // Get order details via AJAX
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'get_admin_order_details',
                order_id: orderId,
                nonce: '<?php echo esc_js(wp_create_nonce('subs_sys_admin_nonce')); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $('#order-details-content').html(response.data.html);
                } else {
                    $('#order-details-content').html('<p class="error">' + response.data.message + '</p>');
                }
            },
            error: function() {
                $('#order-details-content').html('<p class="error">Error loading order details. Please try again.</p>');
            }
        });
    });
    
    // Close modal
    $('.ss-modal-close').on('click', function() {
        $('#order-details-modal').hide();
    });
    
    // Close modal when clicking outside
    $(window).on('click', function(event) {
        if ($(event.target).is('#order-details-modal')) {
            $('#order-details-modal').hide();
        }
    });
});
</script>

<style>
.ss-stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.ss-stats-card {
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 15px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.ss-stats-card h3 {
    margin-top: 0;
    margin-bottom: 10px;
    font-size: 14px;
    color: #666;
}

.ss-stats-value {
    font-size: 24px;
    font-weight: 600;
    color: #333;
}

.order-status {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 3px;
    font-size: 12px;
    font-weight: 600;
}

.order-status.completed {
    background-color: #e6f7e6;
    color: #2e7d32;
}

.order-status.pending {
    background-color: #fff8e1;
    color: #ff8f00;
}

.order-status.failed {
    background-color: #ffebee;
    color: #c62828;
}

.ss-modal {
    display: none;
    position: fixed;
    z-index: 100000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.4);
}

.ss-modal-content {
    background-color: #fefefe;
    margin: 10% auto;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 4px;
    width: 80%;
    max-width: 600px;
    position: relative;
}

.ss-modal-close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.ss-modal-close:hover {
    color: black;
}
</style> 