<?php
/**
 * Handles all AJAX requests for Event Monster (Free Version).
 *
 * @package    Event_Monster
 * @subpackage Event_Monster/includes
 */
class Event_Monster_Free_Ajax
{

    /**
     * The single instance of the class.
     */
    private static $_instance = null;

    /**
     * Ensures only one instance of the class is loaded.
     */
    public static function instance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }


    /**
     * Constructor - Hooks all AJAX actions into WordPress.
     * Free version: Only visitor management, shortcode, event listing, and free booking.
     */
    public function __construct()
    {
        // Free version AJAX actions — no tickets, coupons, payments, or payment gateways.
        $ajax_actions = array(
            // Visitor Actions
            'delete_visitor',
            'view_visitor',
            'update_visitor_status',
            'download_visitor_list',
            'delete_all_visitors',

            // Shortcode
            'get_shortcode_modal',

            // Event List
            'get_event_modal_content',
            'load_more_events',
        );

        foreach ($ajax_actions as $action) {
            if ($action === 'get_event_modal_content') {
                add_action('wp_ajax_em_' . $action, array($this, 'handle_get_event_modal_content'));
                add_action('wp_ajax_nopriv_em_' . $action, array($this, 'handle_get_event_modal_content'));
            } elseif ($action === 'load_more_events') {
                add_action('wp_ajax_em_' . $action, array($this, $action));
                add_action('wp_ajax_nopriv_em_' . $action, array($this, $action));
            } else {
                add_action('wp_ajax_em_' . $action, array($this, $action));
            }
        }

        // Free booking (no paid tickets, no payment gateways)
        add_action('wp_ajax_em_book_tickets', [$this, 'book_tickets']);
        add_action('wp_ajax_nopriv_em_book_tickets', [$this, 'book_tickets']);

        // Process booking (used by calendar modal — free only)
        add_action('wp_ajax_em_process_booking', [$this, 'process_booking']);
        add_action('wp_ajax_nopriv_em_process_booking', [$this, 'process_booking']);
    }

    // --- Ticket Methods removed (Pro-only feature) ---

    // --- Visitor Methods ---

    /**
     * Handles deleting a single visitor/attendee.
     */
    public function delete_visitor()
    {
        if (!check_ajax_referer('em_delete_visitor_nonce', 'nonce', false)) {
            wp_send_json_error(['message' => 'Security check failed.']);
        }
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }

        $attendee_id = isset($_POST['id']) ? absint($_POST['id']) : 0;
        if (!$attendee_id) {
            wp_send_json_error(['message' => 'Invalid Visitor ID.']);
        }

        global $wpdb;
        $attendees_table = $wpdb->prefix . 'em_attendees';
        $result = $wpdb->delete($attendees_table, array('id' => $attendee_id));

        if ($result) {
            wp_send_json_success(['message' => 'Visitor successfully deleted.']);
        } else {
            wp_send_json_error(['message' => 'Database error.']);
        }
    }

    /**
     * Handles deleting multiple visitors in bulk.
     */
    /**
     * Handles deleting multiple visitors in bulk.
     */
    public function delete_all_visitors()
    {
        if (!check_ajax_referer('em_delete_all_visitor_nonce', 'nonce', false)) {
            wp_send_json_error(['message' => 'Security check failed.']);
        }
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }

        $ids_to_delete = isset($_POST['ids']) && is_array($_POST['ids']) ? $_POST['ids'] : array();

        if (empty($ids_to_delete)) {
            wp_send_json_error(['message' => 'No visitor IDs provided.']);
        }

        // Sanitize all IDs to ensure they are integers
        $sanitized_ids = array_map('absint', $ids_to_delete);
        $ids_format = implode(',', array_fill(0, count($sanitized_ids), '%d'));

        global $wpdb;
        $attendees_table = $wpdb->prefix . 'em_attendees';

        $result = $wpdb->query($wpdb->prepare(
            "DELETE FROM $attendees_table WHERE id IN ( $ids_format )",
            $sanitized_ids
        ));

        if ($result !== false) {
            wp_send_json_success();
        } else {
            wp_send_json_error(['message' => 'Database error during bulk deletion.']);
        }
    }


    /**
     * Handles fetching visitor details and sending the modal HTML.
     * This is a self-contained version without a separate render helper.
     */
    public function view_visitor()
    {
        // 1. Security & Data Validation
        if (!check_ajax_referer('em_view_visitor_nonce', 'nonce', false)) {
            wp_send_json_error(['message' => 'Security check failed.']);
        }
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }

        $attendee_id = isset($_POST['id']) ? absint($_POST['id']) : 0;
        if (!$attendee_id) {
            wp_send_json_error(['message' => 'Invalid Visitor ID.']);
        }

        // 2. Fetch Data
        global $wpdb;
        $attendee = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}em_attendees` WHERE id = %d", $attendee_id));
        $booking = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}em_bookings` WHERE attendees_id = %d", $attendee_id));

        if (!$attendee || !$booking) {
            wp_send_json_error(['message' => 'Visitor data not found.']);
        }

        // 3. Prepare the different parts of the modal as variables

        // -- Prepare the Title
        $modal_title = __('View Visitor / Attendee', 'event-monster');

        // -- Prepare the Content
        ob_start();
        include EM_FREE_PLUGIN_DIR . 'templates/admin/modal-content/view-visitor-content.php';
        $modal_content = ob_get_clean();

        // -- Prepare the Footer
        ob_start();
        ?>
        <button type="button" class="btn btn-success" data-dismiss="modal">
            <i class="fa fa-times" aria-hidden="true"></i> <?php _e('Close', 'event-monster'); ?>
        </button>
        <?php
        $modal_footer = ob_get_clean();

        // 4. Load the main modal SHELL template, which uses the variables we just created
        ob_start();
        include EM_FREE_PLUGIN_DIR . 'templates/admin/modal-template.php';
        $html = ob_get_clean();

        // 5. Send the final, complete HTML back to the JavaScript
        wp_send_json_success(['html' => $html]);
    }
    /**
     * Handles updating the booking status of a visitor.
     */
    public function update_visitor_status()
    {
        if (!check_ajax_referer('em_update_status_nonce', 'nonce', false)) {
            wp_send_json_error(['message' => 'Security check failed.']);
        }
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }

        $attendee_id = isset($_POST['id']) ? absint($_POST['id']) : 0;
        $new_status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : '';

        global $wpdb;
        $bookings_table = $wpdb->prefix . 'em_bookings';
        $wpdb->update($bookings_table, ['status' => $new_status], ['attendees_id' => $attendee_id]);

        wp_send_json_success(['message' => 'Status updated.']);
    }

    /**
     * Creates and serves a CSV file of visitors for download.
     */
    public function download_visitor_list()
    {
        if (!check_ajax_referer('em-download-visitor-nonce', 'nonce', false)) {
            wp_send_json_error(['message' => 'Security check failed.']);
            return;
        }
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
            return;
        }

        global $wpdb;
        $attendees_table = $wpdb->prefix . 'em_attendees';
        $filter_event_id = isset($_POST['filter']) ? $_POST['filter'] : 'all';

        $query = "SELECT * FROM `$attendees_table`";
        if ('all' !== $filter_event_id) {
            $query .= $wpdb->prepare(" WHERE event_id = %d", absint($filter_event_id));
        }
        $attendees = $wpdb->get_results($query, ARRAY_A);

        if (empty($attendees)) {
            wp_send_json_error(['message' => 'No visitors to export.']);
            return;
        }

        $upload_dir = wp_upload_dir();
        $filename = 'visitors-list-' . uniqid() . '.csv';
        $filepath = $upload_dir['path'] . '/' . $filename;
        $fileurl = $upload_dir['url'] . '/' . $filename;

        $file = fopen($filepath, 'w');
        fputcsv($file, array('First Name', 'Last Name', 'Email', 'Phone', 'Event'));
        foreach ($attendees as $attendee) {
            fputcsv($file, array($attendee['first_name'], $attendee['last_name'], $attendee['email'], $attendee['phone'], get_the_title($attendee['event_id'])));
        }
        fclose($file);

        wp_send_json_success(['fileurl' => $fileurl]);
    }


    // --- Coupon Methods removed (Pro-only feature) ---

    // --- Payment Methods removed (Pro-only feature) ---

    /**
     * Gets the HTML for the "Get Shortcode" modal by loading the correct templates.
     */
    public function get_shortcode_modal()
    {
        // Security checks
        if (!check_ajax_referer('em_get_shortcode_nonce', 'nonce', false)) {
            wp_send_json_error();
        }
        if (!current_user_can('edit_posts')) {
            wp_send_json_error();
        }

        // --- Prepare variables for the modal templates ---
        $modal_title = __('Generate Event Shortcode', 'event-monster');
        $modal_footer = '<button type="button" class="btn btn-default close-modal">Close</button>';

        // --- Prepare the content by loading our new content-specific template ---
        ob_start();
        include EM_FREE_PLUGIN_DIR . 'templates/admin/modal-content/get-shortcode-content.php';
        $modal_content = ob_get_clean();

        // --- Load the main modal SHELL template ---
        ob_start();
        include EM_FREE_PLUGIN_DIR . 'templates/admin/modal-template.php';
        $html = ob_get_clean();

        // Send the final, complete HTML back to the JavaScript
        wp_send_json_success(['html' => $html]);
    }

    /**
     * Handle AJAX request for event modal content
     */
    public function handle_get_event_modal_content()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'em_ajax_nonce')) {
            wp_send_json_error('Invalid nonce');
        }

        $event_id = intval($_POST['event_id']);

        if (!$event_id) {
            wp_send_json_error('Invalid event ID');
        }

        if (get_post_type($event_id) !== 'awl_event_monster') {
            wp_send_json_error('Event not found');
        }

        // Get event data
        $event_post = get_post($event_id);
        $event_settings = get_post_meta($event_id, 'awl_em_settings_' . $event_id, true);
        if (!is_array($event_settings)) $event_settings = array();

        // Simple content generation
        $content = $this->generate_simple_modal_content($event_post, $event_settings);

        wp_send_json_success([
            'title' => $event_post->post_title,
            'content' => $content
        ]);
    }

    /**
     * Generate full single event content for modal
     */
    private function generate_simple_modal_content($event_post, $event_settings)
    {
        $event_id = $event_post->ID;

        // Set global variables for compatibility
        global $em_id;
        $em_id = $event_id;

        // Keep the original registration modal setting from event settings
        // Don't force inline mode - let the registration component decide

        // Start output buffering to capture the full single event template
        ob_start();

        // Include the full single event template
        include EM_FREE_PLUGIN_DIR . 'templates/frontend/single-event-template.php';

        $full_content = ob_get_clean();

        // Remove footer from modal content
        $full_content = preg_replace('/<footer[^>]*>.*?<\/footer>/is', '', $full_content);

        // Don't remove scripts - the registration component needs its JavaScript to work

        // Wrap in modal-specific styling
        $modal_content = '<div class="em-modal-single-event">';
        $modal_content .= $full_content;
        $modal_content .= '</div>';

        // Add modal-specific CSS
        $modal_content .= '<style>
        .em-modal-single-event {
            font-family: inherit;
            width: 100%;
            max-width: none;
        }
        .em-modal-single-event .em-bg-slate-50 {
            background: white !important;
            padding: 0 !important;
            min-height: auto !important;
        }
        .em-modal-single-event .em-event-container {
            opacity: 1 !important;
            max-width: none !important;
            margin: 0 !important;
            padding: 0 !important;
            width: 100% !important;
        }
        .em-modal-single-event .em-container {
            max-width: none !important;
            padding: 0 !important;
            width: 100% !important;
        }
      
        .em-modal-single-event .em-p-5 {
            padding: 1rem !important;
        }
        .em-modal-single-event .em-p-6 {
            padding: 1rem !important;
        }
        .em-modal-single-event .em-registration-section {
            border: 2px solid #10b981 !important;
            border-radius: 0.5rem !important;
            background: #f0fdf4 !important;
        }
        /* Hide footer in modal */
        .em-modal-single-event footer {
            display: none !important;
        }
        /* Prevent modal conflicts */
        .em-modal-single-event .em-modal-overlay {
            display: none;
        }
        /* Fix registration modal styles within event modal */
        .em-modal-single-event .em-modal-content {
            border-radius: 1rem !important;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
            max-width: 32rem !important;
            width: 100% !important;
            overflow-y: auto !important;
            position: relative !important;
        }
        </style>';

        return $modal_content;
    }

    /**
     * Handle AJAX load more events
     */
    public function load_more_events()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'em_ajax_nonce')) {
            wp_send_json_error('Invalid nonce');
        }

        // Debug logging
        error_log('Load more events called with data: ' . print_r($_POST, true));

        $page = intval($_POST['page'] ?? 1);
        $limit = intval($_POST['limit'] ?? 6);
        $category = sanitize_text_field($_POST['category'] ?? '');
        $view_mode = sanitize_text_field($_POST['view_mode'] ?? 'page');
        $columns = intval($_POST['columns'] ?? 3);
        $show_filters = sanitize_text_field($_POST['show_filters'] ?? 'yes');

        if (!$page || !$limit) {
            error_log('Load more events: Invalid parameters - page: ' . $page . ', limit: ' . $limit);
            wp_send_json_error('Invalid parameters');
        }

        // Calculate offset
        $offset = ($page - 1) * $limit;

        // Get events
        $args = array(
            'post_type' => 'awl_event_monster',
            'post_status' => 'publish',
            'posts_per_page' => $limit,
            'offset' => $offset,
            'orderby' => 'date',
            'order' => 'DESC'
        );

        if (!empty($category)) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'awplife-event-categories',
                    'field' => 'slug',
                    'terms' => $category
                )
            );
        }

        $events = get_posts($args);

        if (empty($events)) {
            wp_send_json_success(array(
                'html' => '',
                'has_more' => false
            ));
        }

        // Generate HTML for events
        ob_start();

        foreach ($events as $event_post) {
            $event_id = $event_post->ID;
            $event_settings = get_post_meta($event_id, 'awl_em_settings_' . $event_id, true);
            if (!is_array($event_settings)) $event_settings = array();

            // Set variables for template - MUST match main template variables
            $atts = array(
                'view_mode' => $view_mode,
                'columns' => $columns,
                'show_filters' => $show_filters
            );

            // Set all the same variables as main template
            $event_title = get_the_title($event_post);
            $event_description = get_the_excerpt($event_post);

            // Get event settings
            $start_date = isset($event_settings['em_start_date']) ? $event_settings['em_start_date'] : '';
            $end_date = isset($event_settings['em_end_date']) ? $event_settings['em_end_date'] : '';
            $start_time = isset($event_settings['em_start_time']) ? $event_settings['em_start_time'] : '';

            // Format dates - same logic as main template
            $formatted_date = '';
            if ($start_date) {
                $start_timestamp = strtotime($start_date);
                if ($end_date && $end_date !== $start_date) {
                    $end_timestamp = strtotime($end_date);
                    $formatted_date = date_i18n('F j', $start_timestamp) . ' - ' . date_i18n('F j, Y', $end_timestamp);
                } else {
                    $formatted_date = date_i18n('F j, Y', $start_timestamp);
                }
                if ($start_time) {
                    $formatted_date .= ' at ' . date_i18n('g:i A', strtotime($start_time));
                }
            }

            // Get location and category
            $location = isset($event_settings['em_event_location']) ? $event_settings['em_event_location'] : '';

            // Get category from WordPress taxonomy first, then fallback to meta field
            $category = '';
            $wp_categories = get_the_terms($event_id, 'awplife-event-categories');
            if (!is_wp_error($wp_categories) && !empty($wp_categories)) {
                $category = $wp_categories[0]->name; // Use first category
            } elseif (isset($event_settings['em_event_category']) && !empty($event_settings['em_event_category'])) {
                $category = $event_settings['em_event_category']; // Fallback to meta field
            }

            // Get featured image
            $featured_image = get_the_post_thumbnail_url($event_id, 'medium');
            if (!$featured_image) {
                $featured_image = EM_FREE_PLUGIN_URL . 'images/placeholder-840x630.png';
            }

            // Include the event card template
            include EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-card.php';
        }

        $html = ob_get_clean();

        // Check if there are more events
        $total_args = $args;
        $total_args['posts_per_page'] = -1;
        $total_args['fields'] = 'ids';
        unset($total_args['offset']);
        $total_events = get_posts($total_args);
        $has_more = count($total_events) > ($offset + $limit);

        wp_send_json_success(array(
            'html' => $html,
            'has_more' => $has_more
        ));
    }

    /**
     * Handle ticket booking from frontend
     */
    public function book_tickets()
    {
        // Verify nonce
        if (!check_ajax_referer('em_book_tickets', 'em_booking_nonce', false)) {
            wp_send_json_error(['message' => 'Security check failed.']);
        }

        $event_id = isset($_POST['event_id']) ? absint($_POST['event_id']) : 0;
        $first_name = isset($_POST['first_name']) ? sanitize_text_field($_POST['first_name']) : '';
        $last_name = isset($_POST['last_name']) ? sanitize_text_field($_POST['last_name']) : '';
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
        $phone = isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '';
        $ticket_qty = isset($_POST['ticket_qty']) ? $_POST['ticket_qty'] : [];

        // Validate required fields
        if (empty($event_id) || empty($first_name) || empty($last_name) || empty($email) || empty($ticket_qty)) {
            wp_send_json_error(['message' => 'Please fill in all required fields.']);
        }

        global $wpdb;
        $booking_table_name = $wpdb->prefix . 'em_bookings';
        $attendee_table_name = $wpdb->prefix . 'em_attendees';
        $ticket_table_name = $wpdb->prefix . 'em_tickets';

        // Calculate total amount
        $total_amount = 0;
        $ticket_data = [];

        foreach ($ticket_qty as $ticket_id => $quantity) {
            $ticket_id = absint($ticket_id);
            $quantity = absint($quantity);
            if ($quantity > 0) {
                $ticket = $wpdb->get_row($wpdb->prepare(
                    "SELECT * FROM `$ticket_table_name` WHERE `id` = %d AND `status` = 'available'",
                    $ticket_id
                ));

                if ($ticket) {
                    $total_amount += $ticket->price * $quantity;
                    $ticket_data[$ticket_id] = $quantity;
                }
            }
        }

        if (empty($ticket_data)) {
            wp_send_json_error(['message' => 'No valid tickets selected.']);
        }

        if ($total_amount > 0) {
            wp_send_json_error(['message' => 'Paid bookings are not supported in this version.']);
        }

        // Free version: No coupon support (Pro-only feature)

        // Insert attendee
        $attendee_result = $wpdb->insert($attendee_table_name, [
            'event_id' => $event_id,
            'ticket_id' => serialize($ticket_data),
            'first_name' => $first_name,
            'last_name' => $last_name,
            'email' => $email,
            'phone' => $phone,
            'extra' => '',
        ]);

        if ($attendee_result === false) {
            wp_send_json_error(['message' => 'Failed to save attendee information.']);
        }

        $attendee_id = $wpdb->insert_id;

        // Free version: All bookings are free
        $booking_type = 'free';
        $status = 'Completed';

        // Insert booking
        $booking_result = $wpdb->insert($booking_table_name, [
            'event_id' => $event_id,
            'ticket_id' => serialize($ticket_data),
            'amount' => 0,
            'coupon_id' => '',
            'attendees_id' => $attendee_id,
            'booking_type' => $booking_type,
            'payment_id' => '',
            'status' => $status,
            'extra' => '',
        ]);

        if ($booking_result === false) {
            wp_send_json_error(['message' => 'Failed to create booking.']);
        }

        $booking_id = $wpdb->insert_id;

        // Send confirmation email
        $email_handler = new Event_Monster_Free_Emails();
        $email_handler->send_booking_confirmation_email($booking_id);

        wp_send_json_success([
            'message' => 'Booking completed successfully!',
            'booking_id' => $booking_id,
            'booking_type' => 'free'
        ]);
    }

    /**
     * Handle booking process from calendar modal
     */
    public function process_booking()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'em_calendar_nonce')) {
            wp_send_json_error(['message' => 'Security check failed.']);
            return;
        }

        // Get event ID
        $event_id = isset($_POST['event_id']) ? absint($_POST['event_id']) : 0;
        if (!$event_id) {
            wp_send_json_error(['message' => 'Event ID is required.']);
            return;
        }

        // Get selected tickets
        $selected_tickets = isset($_POST['selected_tickets']) ? json_decode(stripslashes($_POST['selected_tickets']), true) : [];
        if (empty($selected_tickets)) {
            wp_send_json_error(['message' => 'No tickets selected.']);
            return;
        }

        // Get form data
        $first_name = sanitize_text_field($_POST['first_name'] ?? '');
        $last_name = sanitize_text_field($_POST['last_name'] ?? '');
        $email = sanitize_email($_POST['email'] ?? '');
        $phone = sanitize_text_field($_POST['phone'] ?? '');

        // Validate required fields
        if (empty($first_name) || empty($last_name) || empty($email)) {
            wp_send_json_error(['message' => 'Please fill in all required fields.']);
            return;
        }

        // Use the existing book_tickets logic
        // This ensures consistency with the existing booking system
        $_POST['em_booking_nonce'] = wp_create_nonce('em_book_tickets');
        $_POST['event_id'] = $event_id;

        // Convert selected tickets to the format expected by book_tickets
        foreach ($selected_tickets as $ticket_data) {
            $ticket_id = $ticket_data['ticket_id'];
            $quantity = $ticket_data['quantity'];
            $_POST['ticket_qty'][$ticket_id] = $quantity;
        }

        // Call the existing book_tickets method
        $this->book_tickets();
    }


    // --- Stripe Payment Methods removed (Pro-only feature) ---
    // --- Razorpay Payment Methods removed (Pro-only feature) ---
    // --- Square Payment Methods removed (Pro-only feature) ---

}

Event_Monster_Free_Ajax::instance();
