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

/**
 * VMO Membership & User Dashboard System
 * 
 * Provides the infrastructure for:
 * 1. User Registration & Login
 * 2. Protected Content Areas
 * 3. Client/Member Dashboards
 * 4. Role-based Access Control
 */

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

class VMO_Membership_System {

    public function __construct() {
        // Shortcodes for AI to use
        add_shortcode('vmo_login_form', array($this, 'render_login_form'));
        add_shortcode('vmo_register_form', array($this, 'render_register_form'));
        add_shortcode('vmo_user_dashboard', array($this, 'render_dashboard'));
        add_shortcode('vmo_protected', array($this, 'render_protected_content'));
        
        // Admin/Staff Tools
        add_shortcode('vmo_member_list', array($this, 'render_member_list'));
        add_action('wp_ajax_vmo_export_members', array($this, 'handle_member_export'));
        
        // AJAX Handlers
        add_action('wp_ajax_nopriv_vmo_member_register', array($this, 'handle_registration'));
        add_action('wp_ajax_vmo_member_login', array($this, 'handle_login')); // Usually handled by WP, but custom flow supported
    }

    /**
     * [vmo_login_form]
     */
    public function render_login_form($atts) {
        if (is_user_logged_in()) {
            return '<div class="vmo-alert info">You are already logged in. <a href="' . wp_logout_url(home_url()) . '">Logout</a></div>';
        }
        
        $args = array(
            'echo' => false,
            'redirect' => home_url('/dashboard'), 
            'form_id' => 'vmo-login-form',
            'label_username' => 'Email or Username',
            'label_password' => 'Password',
            'label_remember' => 'Remember Me',
            'label_log_in' => 'Access Dashboard',
            'value_remember' => true
        );
        
        return wp_login_form($args);
    }

    /**
     * [vmo_register_form]
     */
    public function render_register_form($atts) {
        if (is_user_logged_in()) {
            return '<div class="vmo-alert info">You are already registered.</div>';
        }

        ob_start();
        ?>
        <div class="vmo-register-container">
            <form id="vmo-register-form" class="vmo-form">
                <div class="form-group">
                    <label>Full Name</label>
                    <input type="text" name="fullname" required>
                </div>
                <div class="form-group">
                    <label>Email Address</label>
                    <input type="email" name="email" required>
                </div>
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="username" required>
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" name="password" required>
                </div>
                <button type="submit" id="vmo-reg-btn">Create Account</button>
                <div id="vmo-reg-msg"></div>
            </form>
        </div>
        <?php wp_nonce_field('vmo_member_register', 'vmo_register_nonce'); ?>
        <script>
        jQuery('#vmo-register-form').on('submit', function(e) {
            e.preventDefault();
            var btn = jQuery('#vmo-reg-btn');
            btn.prop('disabled', true).text('Creating Account...');
            
            jQuery.post(ajaxurl, {
                action: 'vmo_member_register',
                security: jQuery('#vmo_register_nonce').val(),
                data: jQuery(this).serialize()
            }, function(res) {
                if(res.success) {
                    jQuery('#vmo-reg-msg').html('<p class="success">'+res.data.message+'</p>');
                    setTimeout(function(){ window.location.href = '/login'; }, 2000);
                } else {
                    jQuery('#vmo-reg-msg').html('<p class="error">'+res.data.message+'</p>');
                    btn.prop('disabled', false).text('Create Account');
                }
            });
        });
        </script>
        <style>
            .vmo-form .form-group { margin-bottom: 15px; }
            .vmo-form label { display: block; margin-bottom: 5px; font-weight: 600; }
            .vmo-form input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
            .vmo-form button { width: 100%; padding: 10px; background: #333; color: #fff; border: none; cursor: pointer; }
            .success { color: green; } .error { color: red; }
        </style>
        <?php
        return ob_get_clean();
    }

    /**
     * Handle Registration AJAX
     */
    public function handle_registration() {
        check_ajax_referer('vmo_member_register', 'security');

        parse_str(wp_unslash($_POST['data']), $form_data);
        
        $username = sanitize_user($form_data['username']);
        $email = sanitize_email($form_data['email']);
        $password = $form_data['password'];
        
        if (username_exists($username) || email_exists($email)) {
            wp_send_json_error(['message' => 'Username or Email already exists.']);
        }
        
        $user_id = wp_create_user($username, $password, $email);
        
        if (is_wp_error($user_id)) {
            wp_send_json_error(['message' => $user_id->get_error_message()]);
        }
        
        // Update Full Name
        wp_update_user([
            'ID' => $user_id, 
            'display_name' => sanitize_text_field($form_data['fullname'])
        ]);
        
        wp_send_json_success(['message' => 'Account created successfully! Redirecting...']);
    }

    /**
     * [vmo_user_dashboard]
     * The central hub for logged-in users.
     * Integrates with Ticketing and Projects if available.
     */
    public function render_dashboard($atts) {
        if (!is_user_logged_in()) {
            return '<p>Please <a href="/login">login</a> to view your dashboard.</p>';
        }
        
        $user = wp_get_current_user();
        
        ob_start();
        ?>
        <div class="vmo-dashboard-wrapper">
            <div class="vmo-dash-header">
                <h2>Welcome, <?php echo esc_html($user->display_name); ?></h2>
                <div class="vmo-dash-nav">
                    <button onclick="showTab('overview')" class="active">Overview</button>
                    <button onclick="showTab('tickets')">Support Tickets</button>
                    <button onclick="showTab('profile')">Profile</button>
                </div>
            </div>
            
            <div id="tab-overview" class="vmo-dash-tab" style="display:block;">
                <div class="vmo-card-grid">
                    <div class="vmo-card">
                        <h3>Account Status</h3>
                        <p>Active Member</p>
                    </div>
                    <!-- Hooks for other modules to inject content -->
                    <?php do_action('vmo_dashboard_overview_cards', $user->ID); ?>
                </div>
            </div>
            
            <div id="tab-tickets" class="vmo-dash-tab" style="display:none;">
                <?php echo do_shortcode('[vmo_ticket_list]'); ?>
                <hr>
                <h3>Open New Ticket</h3>
                <?php echo do_shortcode('[vmo_support_ticket_form]'); ?>
            </div>
            
            <div id="tab-profile" class="vmo-dash-tab" style="display:none;">
                <p><strong>Email:</strong> <?php echo esc_html($user->user_email); ?></p>
                <p><strong>Joined:</strong> <?php echo date('F j, Y', strtotime($user->user_registered)); ?></p>
            </div>
        </div>
        
        <script>
        function showTab(tabName) {
            jQuery('.vmo-dash-tab').hide();
            jQuery('#tab-' + tabName).show();
            jQuery('.vmo-dash-nav button').removeClass('active');
            // Simple active state toggle logic would go here
        }
        </script>
        <style>
            .vmo-dashboard-wrapper { background: #f9f9f9; padding: 20px; border-radius: 8px; }
            .vmo-dash-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 2px solid #eee; padding-bottom: 10px; }
            .vmo-dash-nav button { background: none; border: none; padding: 10px 15px; cursor: pointer; font-weight: 600; color: #666; }
            .vmo-dash-nav button.active { color: #007bff; border-bottom: 2px solid #007bff; }
            .vmo-card-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; }
            .vmo-card { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        </style>
        <?php
        return ob_get_clean();
    }

    /**
     * [vmo_protected]Content[/vmo_protected]
     */
    public function render_protected_content($atts, $content = null) {
        if (is_user_logged_in()) {
            return do_shortcode($content);
        }
        return '<div class="vmo-protected-notice">This content is for members only. Please <a href="/login">login</a> to view.</div>';
    }

    /**
     * [vmo_member_list]
     * Admin tool to view all members
     */
    public function render_member_list($atts) {
        if (!current_user_can('list_users')) return 'Access Denied';

        $users = get_users();
        
        ob_start();
        ?>
        <div class="vmo-admin-panel">
            <div class="vmo-panel-header">
                <h3>Member Database</h3>
                <button onclick="window.location.href='<?php echo admin_url('admin-ajax.php?action=vmo_export_members'); ?>'" class="vmo-btn-export">Export CSV</button>
            </div>
            <table class="vmo-data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Joined</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td>#<?php echo esc_html( $user->ID ); ?></td>
                        <td><?php echo esc_html($user->display_name); ?></td>
                        <td><?php echo esc_html($user->user_email); ?></td>
                        <td><?php echo date('Y-m-d', strtotime($user->user_registered)); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <style>
            .vmo-admin-panel { background: #fff; padding: 20px; border: 1px solid #ddd; }
            .vmo-panel-header { display: flex; justify-content: space-between; margin-bottom: 15px; }
            .vmo-data-table { width: 100%; border-collapse: collapse; }
            .vmo-data-table th, .vmo-data-table td { padding: 10px; border-bottom: 1px solid #eee; text-align: left; }
            .vmo-btn-export { background: #28a745; color: white; border: none; padding: 8px 15px; cursor: pointer; }
        </style>
        <?php
        return ob_get_clean();
    }

    /**
     * Handle CSV Export
     */
    public function handle_member_export() {
        if (!current_user_can('list_users')) wp_die('Access Denied');

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="members_export_' . date('Y-m-d') . '.csv"');

        $output = fopen('php://output', 'w');
        fputcsv($output, array('ID', 'Username', 'Email', 'Name', 'Registered Date'));

        $users = get_users();
        foreach ($users as $user) {
            fputcsv($output, array(
                $user->ID,
                $user->user_login,
                $user->user_email,
                $user->display_name,
                $user->user_registered
            ));
        }
        fclose($output);
        exit;
    }
}
