<?php

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

class WPDD_Customer {
    
    public static function init() {
        add_action('wp_dashboard_setup', array(__CLASS__, 'add_dashboard_widgets'));
        add_filter('login_redirect', array(__CLASS__, 'login_redirect'), 10, 3);
        add_action('show_user_profile', array(__CLASS__, 'add_customer_fields'));
        add_action('edit_user_profile', array(__CLASS__, 'add_customer_fields'));
        
        // Block wp-admin access for customers
        add_action('admin_init', array(__CLASS__, 'restrict_admin_access'));
        
        // Add frontend logout and account management
        add_action('wp_footer', array(__CLASS__, 'add_customer_scripts'));
    }
    
    public static function add_dashboard_widgets() {
        if (current_user_can('wpdd_view_purchases')) {
            wp_add_dashboard_widget(
                'wpdd_customer_recent_purchases',
                __('Recent Purchases', 'wp-digital-download'),
                array(__CLASS__, 'recent_purchases_widget')
            );
        }
        
        if (current_user_can('wpdd_view_own_sales')) {
            wp_add_dashboard_widget(
                'wpdd_creator_sales_summary',
                __('Sales Summary', 'wp-digital-download'),
                array(__CLASS__, 'sales_summary_widget')
            );
        }
    }
    
    public static function recent_purchases_widget() {
        global $wpdb;
        $current_user = wp_get_current_user();
        
        $recent_orders = $wpdb->get_results($wpdb->prepare(
            "SELECT o.*, p.post_title as product_name 
             FROM {$wpdb->prefix}wpdd_orders o
             LEFT JOIN {$wpdb->posts} p ON o.product_id = p.ID
             WHERE o.customer_id = %d 
             AND o.status = 'completed'
             ORDER BY o.purchase_date DESC
             LIMIT 5",
            $current_user->ID
        ));
        
        if ($recent_orders) {
            echo '<ul>';
            foreach ($recent_orders as $order) {
                printf(
                    '<li>%s - <a href="%s">%s</a> ($%s)</li>',
                    date_i18n(get_option('date_format'), strtotime($order->purchase_date)),
                    get_permalink($order->product_id),
                    esc_html($order->product_name),
                    number_format($order->amount, 2)
                );
            }
            echo '</ul>';
            
            printf(
                '<p><a href="%s" class="button">%s</a></p>',
                get_permalink(get_option('wpdd_purchases_page_id')),
                __('View All Purchases', 'wp-digital-download')
            );
        } else {
            echo '<p>' . __('No purchases yet.', 'wp-digital-download') . '</p>';
            printf(
                '<p><a href="%s" class="button button-primary">%s</a></p>',
                get_permalink(get_option('wpdd_shop_page_id')),
                __('Browse Products', 'wp-digital-download')
            );
        }
    }
    
    public static function sales_summary_widget() {
        global $wpdb;
        $current_user = wp_get_current_user();
        
        $stats = $wpdb->get_row($wpdb->prepare(
            "SELECT 
                COUNT(*) as total_sales,
                SUM(amount) as total_revenue,
                COUNT(DISTINCT product_id) as products_sold
             FROM {$wpdb->prefix}wpdd_orders
             WHERE creator_id = %d 
             AND status = 'completed'
             AND purchase_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)",
            $current_user->ID
        ));
        
        $recent_sales = $wpdb->get_results($wpdb->prepare(
            "SELECT o.*, p.post_title as product_name 
             FROM {$wpdb->prefix}wpdd_orders o
             LEFT JOIN {$wpdb->posts} p ON o.product_id = p.ID
             WHERE o.creator_id = %d 
             AND o.status = 'completed'
             ORDER BY o.purchase_date DESC
             LIMIT 5",
            $current_user->ID
        ));
        ?>
        <div class="wpdd-sales-summary">
            <div class="wpdd-stats-grid">
                <div class="wpdd-stat">
                    <span class="wpdd-stat-value"><?php echo intval($stats->total_sales); ?></span>
                    <span class="wpdd-stat-label"><?php _e('Sales (30 days)', 'wp-digital-download'); ?></span>
                </div>
                <div class="wpdd-stat">
                    <span class="wpdd-stat-value">$<?php echo number_format($stats->total_revenue ?: 0, 2); ?></span>
                    <span class="wpdd-stat-label"><?php _e('Revenue (30 days)', 'wp-digital-download'); ?></span>
                </div>
            </div>
            
            <?php if ($recent_sales) : ?>
                <h4><?php _e('Recent Sales', 'wp-digital-download'); ?></h4>
                <ul>
                    <?php foreach ($recent_sales as $sale) : ?>
                        <li>
                            <?php echo date_i18n(get_option('date_format'), strtotime($sale->purchase_date)); ?> - 
                            <?php echo esc_html($sale->product_name); ?> 
                            ($<?php echo number_format($sale->amount, 2); ?>)
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
            
            <p>
                <a href="<?php echo admin_url('edit.php?post_type=wpdd_product'); ?>" class="button">
                    <?php _e('Manage Products', 'wp-digital-download'); ?>
                </a>
            </p>
        </div>
        
        <style>
            .wpdd-stats-grid {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 15px;
                margin-bottom: 20px;
            }
            .wpdd-stat {
                text-align: center;
                padding: 10px;
                background: #f0f0f1;
                border-radius: 4px;
            }
            .wpdd-stat-value {
                display: block;
                font-size: 24px;
                font-weight: 600;
                color: #2271b1;
            }
            .wpdd-stat-label {
                display: block;
                font-size: 12px;
                color: #646970;
                margin-top: 5px;
            }
        </style>
        <?php
    }
    
    public static function login_redirect($redirect_to, $requested_redirect_to, $user) {
        if (!is_wp_error($user) && in_array('wpdd_customer', $user->roles)) {
            $purchases_page = get_option('wpdd_purchases_page_id');
            if ($purchases_page) {
                return get_permalink($purchases_page);
            }
        }
        
        return $redirect_to;
    }
    
    public static function add_customer_fields($user) {
        if (!in_array('wpdd_customer', $user->roles)) {
            return;
        }
        
        global $wpdb;
        
        $total_purchases = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}wpdd_orders 
             WHERE customer_id = %d AND status = 'completed'",
            $user->ID
        ));
        
        $total_spent = $wpdb->get_var($wpdb->prepare(
            "SELECT SUM(amount) FROM {$wpdb->prefix}wpdd_orders 
             WHERE customer_id = %d AND status = 'completed'",
            $user->ID
        ));
        ?>
        <h3><?php _e('Customer Information', 'wp-digital-download'); ?></h3>
        <table class="form-table">
            <tr>
                <th><?php _e('Total Purchases', 'wp-digital-download'); ?></th>
                <td><?php echo intval($total_purchases); ?></td>
            </tr>
            <tr>
                <th><?php _e('Total Spent', 'wp-digital-download'); ?></th>
                <td>$<?php echo number_format($total_spent ?: 0, 2); ?></td>
            </tr>
        </table>
        <?php
    }
    
    public static function get_customer_purchases($customer_id) {
        global $wpdb;
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT o.*, p.post_title as product_name 
             FROM {$wpdb->prefix}wpdd_orders o
             LEFT JOIN {$wpdb->posts} p ON o.product_id = p.ID
             WHERE o.customer_id = %d 
             AND o.status = 'completed'
             ORDER BY o.purchase_date DESC",
            $customer_id
        ));
    }
    
    public static function can_download_product($customer_id, $product_id) {
        global $wpdb;
        
        $order = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}wpdd_orders 
             WHERE customer_id = %d 
             AND product_id = %d 
             AND status = 'completed'
             ORDER BY purchase_date DESC
             LIMIT 1",
            $customer_id,
            $product_id
        ));
        
        if (!$order) {
            return false;
        }
        
        $download_limit = get_post_meta($product_id, '_wpdd_download_limit', true);
        $download_expiry = get_post_meta($product_id, '_wpdd_download_expiry', true);
        
        if ($download_expiry > 0) {
            $expiry_date = date('Y-m-d H:i:s', strtotime($order->purchase_date . ' + ' . $download_expiry . ' days'));
            if (current_time('mysql') > $expiry_date) {
                return false;
            }
        }
        
        if ($download_limit > 0 && $order->download_count >= $download_limit) {
            return false;
        }
        
        return true;
    }
    
    /**
     * Block wp-admin access for customers
     */
    public static function restrict_admin_access() {
        $current_user = wp_get_current_user();
        
        // Only block for wpdd_customer role, allow creators and admins
        if (in_array('wpdd_customer', $current_user->roles) && !current_user_can('manage_options')) {
            // Allow AJAX requests
            if (defined('DOING_AJAX') && DOING_AJAX) {
                return;
            }
            
            // Redirect to purchases page
            $purchases_page = get_option('wpdd_purchases_page_id');
            $redirect_url = $purchases_page ? get_permalink($purchases_page) : home_url();
            wp_redirect($redirect_url);
            exit;
        }
    }
    
    /**
     * Add frontend customer scripts and functionality
     */
    public static function add_customer_scripts() {
        if (is_user_logged_in()) {
            $current_user = wp_get_current_user();
            
            // Only for customers
            if (in_array('wpdd_customer', $current_user->roles)) {
                ?>
                <script>
                // Add logout functionality to customer pages
                document.addEventListener('DOMContentLoaded', function() {
                    // Add logout link to customer navigation if it exists
                    var customerNav = document.querySelector('.wpdd-customer-nav, .wpdd-shop-filters, .wpdd-customer-purchases');
                    if (customerNav && !document.querySelector('.wpdd-customer-logout')) {
                        var logoutLink = document.createElement('div');
                        logoutLink.className = 'wpdd-customer-logout';
                        logoutLink.style.cssText = 'margin-top: 10px; padding: 10px; background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px;';
                        logoutLink.innerHTML = '<strong>Welcome, <?php echo esc_js($current_user->display_name); ?>!</strong> | ' +
                            '<a href="<?php echo wp_logout_url(get_permalink()); ?>" style="color: #dc3545;">Logout</a> | ' +
                            '<a href="#" onclick="wpdd_show_password_form()" style="color: #007cba;">Change Password</a>';
                        customerNav.appendChild(logoutLink);
                    }
                });
                
                // Password change functionality
                function wpdd_show_password_form() {
                    var passwordForm = document.getElementById('wpdd-password-form');
                    if (passwordForm) {
                        passwordForm.style.display = passwordForm.style.display === 'none' ? 'block' : 'none';
                        return;
                    }
                    
                    var formHtml = '<div id="wpdd-password-form" style="margin-top: 15px; padding: 15px; background: white; border: 2px solid #007cba; border-radius: 4px;">' +
                        '<h4>Change Password</h4>' +
                        '<form id="wpdd-change-password" onsubmit="wpdd_change_password(event)">' +
                        '<p><input type="password" name="current_password" placeholder="Current Password" required style="width: 100%; margin-bottom: 10px; padding: 8px;"></p>' +
                        '<p><input type="password" name="new_password" placeholder="New Password" required style="width: 100%; margin-bottom: 10px; padding: 8px;"></p>' +
                        '<p><input type="password" name="confirm_password" placeholder="Confirm New Password" required style="width: 100%; margin-bottom: 10px; padding: 8px;"></p>' +
                        '<p><button type="submit" style="background: #007cba; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer;">Update Password</button> ' +
                        '<button type="button" onclick="wpdd_hide_password_form()" style="background: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer;">Cancel</button></p>' +
                        '</form></div>';
                    
                    var logoutDiv = document.querySelector('.wpdd-customer-logout');
                    if (logoutDiv) {
                        logoutDiv.insertAdjacentHTML('afterend', formHtml);
                    }
                }
                
                function wpdd_hide_password_form() {
                    var passwordForm = document.getElementById('wpdd-password-form');
                    if (passwordForm) {
                        passwordForm.remove();
                    }
                }
                
                function wpdd_change_password(event) {
                    event.preventDefault();
                    var form = event.target;
                    var formData = new FormData(form);
                    
                    if (formData.get('new_password') !== formData.get('confirm_password')) {
                        alert('New passwords do not match!');
                        return;
                    }
                    
                    formData.append('action', 'wpdd_change_password');
                    formData.append('nonce', '<?php echo wp_create_nonce('wpdd_change_password'); ?>');
                    
                    fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('Password changed successfully!');
                            wpdd_hide_password_form();
                        } else {
                            alert('Error: ' + (data.data || 'Failed to change password'));
                        }
                    })
                    .catch(error => {
                        alert('Error: ' + error.message);
                    });
                }
                </script>
                <?php
            }
        }
    }
}