<?php

namespace Bookingor\Backend\Controller\Starter;

use Bookingor\Backend\Controller\Settings\SettingsControl;


class StarterController
{
    public static $dp_prefix = 'bookingor_';
    public static $bookingorDb;

    /**
     * Creates a WordPress page for bookings with the selected shortcode.
     */
    public static function create_booking_page()
    {
        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                wp_send_json_error(['message' => 'Nonce verification failed.']);
            }
        }

        $shortcode = sanitize_text_field(wp_unslash($_POST['shortcode'] ?? ''));

        if (empty($shortcode)) {
            wp_send_json_error(['message' => 'Shortcode is required.']);
        }

        $page_title = 'booking appointment';
        $page_content = $shortcode;

        // Check if page already exists to prevent duplicates
        $existing_page = self::get_page_by_title_safe($page_title);

        if ($existing_page && $existing_page->post_status !== 'trash') {
            // Update existing page content
            $updated_post = array(
                'ID' => $existing_page->ID,
                'post_content' => $page_content,
            );
            wp_update_post($updated_post);
            wp_send_json_success(['message' => 'Booking page updated successfully.', 'page_id' => $existing_page->ID, 'url' => get_permalink($existing_page->ID)]);
        } else {
            // Create new page
            $new_page = array(
                'post_title' => $page_title,
                'post_excerpt' => "Bookingor is WordPress Booking Plugin for Appointment, Booking system, Scheduling, Meeting Scheulder, event calender, WooCommerece Booking",
                'post_content' => $page_content,
                'post_status' => 'publish',
                'post_type' => 'page',
            );

            $page_id = wp_insert_post($new_page);

            if (is_wp_error($page_id)) {
                wp_send_json_error(['message' => 'Failed to create booking page.']);
            }

            wp_send_json_success(['message' => 'Booking page created successfully.', 'page_id' => $page_id, 'url' => get_permalink($page_id)]);
        }
    }


 

    /**
     * Imports demo data based on business type.
     *
     * @param string $type The business category (spa, barber, salon, medical)
     */
    public static function import_demo_seeder($type = 'spa')
    {
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $full_prefix = $wpdb->prefix . self::$dp_prefix;

        $categories = [];
        $services = [];
        $staff = [];
        $locations = [];

        switch ($type) {
            case 'barber':
                $categories = [
                    ['icon' => '', 'category_name' => 'Haircut', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Shave & Grooming', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Beard Trim', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Classic Haircut', 'service_cost' => 30, 'service_duration' => 30, 'category_get_id' => 1],
                    ['service_name' => 'Hot Towel Shave', 'service_cost' => 25, 'service_duration' => 20, 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'James', 'staff_last_name' => 'Barber', 'staff_email' => 'james@barber.com', 'staff_about' => 'Master Barber with 10 years experience'],
                ];
                $locations = [
                    ['location_title' => 'Downtown Barber Shop', 'location_address' => '456 Main St, Central City'],
                ];
                break;

            case 'salon':
                $categories = [
                    ['icon' => '', 'category_name' => 'Hair Styling', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Coloring', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Nail Art', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Cut & Blow Dry', 'service_cost' => 50, 'service_duration' => 60, 'category_get_id' => 1],
                    ['service_name' => 'Full Head Highlights', 'service_cost' => 120, 'service_duration' => 120, 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Sarah', 'staff_last_name' => 'Stylist', 'staff_email' => 'sarah@salon.com', 'staff_about' => 'Specialist in creative coloring'],
                ];
                $locations = [
                    ['location_title' => 'Elite Beauty Salon', 'location_address' => '789 Fashion Ave, Style Town'],
                ];
                break;

            case 'medical':
                $categories = [
                    ['icon' => '', 'category_name' => 'General Consultation', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Specialized Checkup', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Diagnostic Testing', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Primary Care Visit', 'service_cost' => 100, 'service_duration' => 30, 'category_get_id' => 1],
                    ['service_name' => 'Cardiology Consult', 'service_cost' => 200, 'service_duration' => 45, 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Dr.', 'staff_last_name' => 'Smith', 'staff_email' => 'smith@medical.com', 'staff_about' => 'Board-certified General Physician'],
                ];
                $locations = [
                    ['location_title' => 'Central Medical Clinic', 'location_address' => '101 Health Blvd, Wellness District'],
                ];
                break;

            case 'lawyer':
                $categories = [
                    ['icon' => '', 'category_name' => 'Legal Services', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Consultation', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Representation', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Initial Consultation', 'service_cost' => 200, 'service_duration' => 60, 'category_get_id' => 2],
                    ['service_name' => 'Contract Review', 'service_cost' => 300, 'service_duration' => 90, 'category_get_id' => 1],
                ];
                $staff = [
                    ['staff_first_name' => 'Robert', 'staff_last_name' => 'Lawyer', 'staff_email' => 'robert@lawfirm.com', 'staff_about' => 'Senior Attorney'],
                ];
                $locations = [
                    ['location_title' => 'City Law Office', 'location_address' => '123 Legal Row'],
                ];
                break;

            case 'counseling':
                $categories = [
                    ['icon' => '', 'category_name' => 'Therapy', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Support Group', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Assessment', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Individual Session', 'service_cost' => 100, 'service_duration' => 50, 'category_get_id' => 1],
                    ['service_name' => 'Couples Therapy', 'service_cost' => 150, 'service_duration' => 60, 'category_get_id' => 1],
                ];
                $staff = [
                    ['staff_first_name' => 'Alice', 'staff_last_name' => 'Counselor', 'staff_email' => 'alice@counseling.com', 'staff_about' => 'Licensed Therapist'],
                ];
                $locations = [
                    ['location_title' => 'Peaceful Mind Center', 'location_address' => '456 Serenity Lane'],
                ];
                break;

            case 'tour':
                $categories = [
                    ['icon' => '', 'category_name' => 'City Tours', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Adventure Tours', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Cultural Tours', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Full Day City Tour', 'service_cost' => 150, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 1],
                    ['service_name' => 'Mountain Hiking', 'service_cost' => 100, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Marco', 'staff_last_name' => 'Guide', 'staff_email' => 'marco@tourguide.com', 'staff_about' => 'Expert local tour guide'],
                ];
                $locations = [
                    ['location_title' => 'Visitor Center', 'location_address' => '500 Tourism Way'],
                ];
                break;

            case 'gym':
                $categories = [
                    ['icon' => '', 'category_name' => 'Yoga', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Crossfit', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Personal Training', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Morning Yoga Class', 'service_cost' => 20, 'service_duration' => 60, 'category_get_id' => 1],
                    ['service_name' => 'Personal Training Session', 'service_cost' => 50, 'service_duration' => 60, 'category_get_id' => 3],
                ];
                $staff = [
                    ['staff_first_name' => 'Alex', 'staff_last_name' => 'Trainer', 'staff_email' => 'alex@gym.com', 'staff_about' => 'Certified Fitness Instructor'],
                ];
                $locations = [
                    ['location_title' => 'City Gym', 'location_address' => '789 Fitness St'],
                ];
                break;

            case 'cleaning':
                $categories = [
                    ['icon' => '', 'category_name' => 'Residential Cleaning', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Commercial Cleaning', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Deep Cleaning', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Standard House Cleaning', 'service_cost' => 80, 'service_duration' => 120, 'category_get_id' => 1],
                    ['service_name' => 'Office Maintenance', 'service_cost' => 150, 'service_duration' => 180, 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Maria', 'staff_last_name' => 'Cleaner', 'staff_email' => 'maria@cleaning.com', 'staff_about' => 'Professional cleaner with 5 years experience'],
                ];
                $locations = [
                    ['location_title' => 'Cleaning HQ', 'location_address' => '123 Service Road'],
                ];
                break;

            case 'yoga':
                $categories = [
                    ['icon' => '', 'category_name' => 'Hatha Yoga', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Vinyasa Flow', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Meditation', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Morning Yoga Session', 'service_cost' => 25, 'service_duration' => 60, 'category_get_id' => 1],
                    ['service_name' => 'Private Meditation', 'service_cost' => 40, 'service_duration' => 45, 'category_get_id' => 3],
                ];
                $staff = [
                    ['staff_first_name' => 'Emma', 'staff_last_name' => 'Zen', 'staff_email' => 'emma@yoga.com', 'staff_about' => 'Certified Yoga & Meditation Instructor'],
                ];
                $locations = [
                    ['location_title' => 'Zen Yoga Studio', 'location_address' => '456 Tranquil Way'],
                ];
                break;

            case 'pet':
                $categories = [
                    ['icon' => '', 'category_name' => 'Dog Grooming', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Cat Grooming', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Special Treatments', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Full Grooming', 'service_cost' => 60, 'service_duration' => 90, 'category_get_id' => 1],
                    ['service_name' => 'Bath & Brush', 'service_cost' => 35, 'service_duration' => 45, 'category_get_id' => 1],
                ];
                $staff = [
                    ['staff_first_name' => 'Bella', 'staff_last_name' => 'Groomer', 'staff_email' => 'bella@petgrooming.com', 'staff_about' => 'Certified pet stylist'],
                ];
                $locations = [
                    ['location_title' => 'Happy Paws Grooming', 'location_address' => '789 Pet Lane'],
                ];
                break;

            case 'photography':
                $categories = [
                    ['icon' => '', 'category_name' => 'Portrait', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Event', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Studio', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Family Portrait', 'service_cost' => 150, 'service_duration' => 60, 'category_get_id' => 1],
                    ['service_name' => 'Commercial Shoot', 'service_cost' => 300, 'service_duration' => 120, 'category_get_id' => 3],
                ];
                $staff = [
                    ['staff_first_name' => 'David', 'staff_last_name' => 'Lens', 'staff_email' => 'david@photo.com', 'staff_about' => 'Professional Photographer'],
                ];
                $locations = [
                    ['location_title' => 'City Photo Studio', 'location_address' => '101 Camera St'],
                ];
                break;

            case 'auto':
                $categories = [
                    ['icon' => '', 'category_name' => 'Maintenance', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Repair', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Detailing', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Oil Change', 'service_cost' => 50, 'service_duration' => 45, 'category_get_id' => 1],
                    ['service_name' => 'Full Detailing', 'service_cost' => 200, 'service_duration' => 180, 'category_get_id' => 3],
                ];
                $staff = [
                    ['staff_first_name' => 'Mike', 'staff_last_name' => 'Mechanic', 'staff_email' => 'mike@auto.com', 'staff_about' => 'Expert Auto Technician'],
                ];
                $locations = [
                    ['location_title' => 'Elite Auto Care', 'location_address' => '555 Garage Rd'],
                ];
                break;

            case 'education':
                $categories = [
                    ['icon' => '', 'category_name' => 'Mathematics', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Languages', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Arts', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Private Tutoring', 'service_cost' => 40, 'service_duration' => 60, 'category_get_id' => 1],
                    ['service_name' => 'Group Workshop', 'service_cost' => 25, 'service_duration' => 90, 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Sophie', 'staff_last_name' => 'Tutor', 'staff_email' => 'sophie@edu.com', 'staff_about' => 'Professional Educator'],
                ];
                $locations = [
                    ['location_title' => 'Learning Center', 'location_address' => '222 Study Ave'],
                ];
                break;

            case 'consulting':
                $categories = [
                    ['icon' => '', 'category_name' => 'Business', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Financial', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Technical', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Strategy Session', 'service_cost' => 100, 'service_duration' => 60, 'category_get_id' => 1],
                    ['service_name' => 'Project Review', 'service_cost' => 150, 'service_duration' => 90, 'category_get_id' => 3],
                ];
                $staff = [
                    ['staff_first_name' => 'James', 'staff_last_name' => 'Consultant', 'staff_email' => 'james@consult.com', 'staff_about' => 'Senior Business Advisor'],
                ];
                $locations = [
                    ['location_title' => 'Corporate Hub', 'location_address' => '999 Executive Plaza'],
                ];
                break;

            case 'meeting':
                $categories = [
                    ['icon' => '', 'category_name' => '1:1 Meeting', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Consultation', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Introductory Call', 'service_cost' => 0, 'service_duration' => 30, 'category_get_id' => 1],
                    ['service_name' => 'Strategy Session', 'service_cost' => 100, 'service_duration' => 60, 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'John', 'staff_last_name' => 'Advisor', 'staff_email' => 'john.advisor@example.com', 'staff_about' => 'Specialist in strategic consulting and personal sessions.'],
                ];
                $locations = [
                    ['location_title' => 'Online Meeting', 'location_address' => 'Zoom or Google Meet'],
                ];
                break;

            case 'product_meeting':
                $categories = [
                    ['icon' => '', 'category_name' => 'Product Demo', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Onboarding', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Product Walkthrough', 'service_cost' => 0, 'service_duration' => 45, 'category_get_id' => 1],
                    ['service_name' => 'Onboarding & Setup', 'service_cost' => 50, 'service_duration' => 60, 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Sarah', 'staff_last_name' => 'Success', 'staff_email' => 'sarah.success@example.com', 'staff_about' => 'Customer success manager helping you get the best value.'],
                ];
                $locations = [
                    ['location_title' => 'Online Video Call', 'location_address' => 'Zoom or Microsoft Teams'],
                ];
                break;

            case 'car_rental':
                $categories = [
                    ['icon' => '', 'category_name' => 'Sedan', 'status' => 1],
                    ['icon' => '', 'category_name' => 'SUV', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Convertible', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Tesla Model 3', 'service_cost' => 80, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 1],
                    ['service_name' => 'Jeep Wrangler SUV', 'service_cost' => 120, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Robert', 'staff_last_name' => 'Agent', 'staff_email' => 'robert@carrental.com', 'staff_about' => 'Rental Fleet Specialist'],
                ];
                $locations = [
                    ['location_title' => 'Airport Pickup Station', 'location_address' => 'Terminal 1 Arrivals, Airport Blvd'],
                ];
                break;

            case 'hotel':
                $categories = [
                    ['icon' => '', 'category_name' => 'Suites', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Rooms', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Campsites', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Deluxe Queen Suite', 'service_cost' => 150, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 1],
                    ['service_name' => 'Standard Twin Room', 'service_cost' => 90, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Alice', 'staff_last_name' => 'Host', 'staff_email' => 'alice@hotelstays.com', 'staff_about' => 'Resort Guest Coordinator'],
                ];
                $locations = [
                    ['location_title' => 'Grand Hotel & Resort', 'location_address' => '777 Shoreline Dr, Oceanview City'],
                ];
                break;

            case 'home_rental':
                $categories = [
                    ['icon' => '', 'category_name' => 'Apartments', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Villas', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Guest Houses', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'City Center Apartment', 'service_cost' => 110, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 1],
                    ['service_name' => 'Luxury Beachfront Villa', 'service_cost' => 320, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'Emma', 'staff_last_name' => 'Host', 'staff_email' => 'emma@homerentals.com', 'staff_about' => 'Vacation Property Manager'],
                ];
                $locations = [
                    ['location_title' => 'Vacation Rental Office', 'location_address' => '100 Beachfront Blvd, Palm City'],
                ];
                break;

            case 'equipment_rental':
                $categories = [
                    ['icon' => '', 'category_name' => 'Camera Gear', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Power Tools', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Party Supplies', 'status' => 1],
                ];
                $services = [
                    ['service_name' => '4K Camera Rig', 'service_cost' => 75, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 1],
                    ['service_name' => 'Heavy Duty Jackhammer', 'service_cost' => 50, 'service_duration' => 1440, 'service_duration_type' => 'day', 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'David', 'staff_last_name' => 'Manager', 'staff_email' => 'david@equipmentrental.com', 'staff_about' => 'Equipment Inventory Coordinator'],
                ];
                $locations = [
                    ['location_title' => 'Main Distribution Center', 'location_address' => '250 Industrial Way, Factory Zone'],
                ];
                break;

            case 'spa':
            default:
                $categories = [
                    ['icon' => '', 'category_name' => 'Massage', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Makeup', 'status' => 1],
                    ['icon' => '', 'category_name' => 'Skincare Consultation', 'status' => 1],
                ];
                $services = [
                    ['service_name' => 'Swedish Massage', 'service_cost' => 80, 'service_duration' => 60, 'category_get_id' => 1],
                    ['service_name' => 'Bridal Makeup', 'service_cost' => 150, 'service_duration' => 90, 'category_get_id' => 2],
                ];
                $staff = [
                    ['staff_first_name' => 'John', 'staff_last_name' => 'Doe', 'staff_email' => 'contact@bookingo.com', 'staff_about' => 'Experienced massage therapist'],
                ];
                $locations = [
                    ['location_title' => 'Main Spa Location', 'location_address' => '123 Spa Street, Wellness City'],
                ];
                break;
                
        }

        // Insert Categories
        $cat_ids = [];
        foreach ($categories as $index => $cat) {
            $wpdb->insert($full_prefix . 'categories', $cat);
            $cat_ids[$index + 1] = $wpdb->insert_id;
        }

        // Insert Services
        $svc_ids = [];
        foreach ($services as $svc) {
            $cat_index = $svc['category_get_id'] ?? 1;
            $actual_cat_id = $cat_ids[$cat_index] ?? 0;
            $svc['category_get_id'] = $actual_cat_id;

            $default_svc = [
                'service_icon' => '',
                'service_description' => '',
                'service_deposit' => 0,
                'service_deposit_type' => '',
                'service_tax' => 0,
                'service_duration_type' => 'minute',
                'service_duration_count' => 1,
                'timeslot_length' => $svc['service_duration'],
                'service_slot_increment' => 0,
                'padding_before' => 0,
                'padding_after' => 0,
                'service_capacity_min' => 1,
                'service_capacity_max' => 1,
                'recurring_status' => 0,
                'recurring_type' => '',
                'recurring_payment' => 0,
                'service_cancel_booking_time' => 24,
                'service_allow_booking_time' => 24,
                'service_allow_zoom_meeting' => 0,
                'single_booking_only_slot' => 0,
                'service_time_sheet' => '',
                'wc_id' => 0,
                'status' => 1
            ];
            $wpdb->insert($full_prefix . 'services', array_merge($default_svc, $svc));
            $svc_ids[] = $wpdb->insert_id;
        }

        // Insert Staff
        $stf_ids = [];
        foreach ($staff as $stf) {
            $default_stf = [
                'staff_phone' => '1234567890',
                'staff_location' => '',
                'staff_icon' => '',
                'staff_tag_line' => '',
                'staff_about' => '',
                'staff_sheet_weekly' => '',
                'staff_holiday' => '',
                'google_calendar_id' => '',
                'google_access_token' => '',
                'zoom_user_id' => '',
                'google_time_zone' => '',
                'status' => 1
            ];
            $wpdb->insert($full_prefix . 'staff_add', array_merge($default_stf, $stf));
            $stf_ids[] = $wpdb->insert_id;
        }

        // Insert Locations
        $loc_ids = [];
        foreach ($locations as $loc) {
            $default_loc = [
                'location_icon' => '',
                'location_country' => '',
                'location_city' => '',
                'location_address' => '',
                'location_phone' => '1234567890',
                'location_latitude' => '',
                'location_longitude' => '',
                'location_time_sheet' => '',
                'status' => 1
            ];
            $wpdb->insert($full_prefix . 'location', array_merge($default_loc, $loc));
            $loc_ids[] = $wpdb->insert_id;
        }

        // Populate Assignment Tables
        foreach ($svc_ids as $svc_id) {
            // Assign each service to all staff
            foreach ($stf_ids as $stf_id) {
                $wpdb->insert($full_prefix . 'staff_assign_service', [
                    'staff_get_id' => $stf_id,
                    'service_get_id' => $svc_id,
                    'staff_price' => 0,
                ]);
            }
            // Assign each service to all locations
            foreach ($loc_ids as $loc_id) {
                $wpdb->insert($full_prefix . 'location_assign_service', [
                    'location_get_id' => $loc_id,
                    'service_get_id' => $svc_id,
                ]);
            }
        }

        // Assign each staff to all locations
        foreach ($loc_ids as $loc_id) {
            foreach ($stf_ids as $stf_id) {
                $wpdb->insert($full_prefix . 'location_assign_staff', [
                    'location_get_id' => $loc_id,
                    'staff_get_id' => $stf_id,
                ]);
            }
        }

        return [
            'service_ids' => $svc_ids,
            'staff_ids' => $stf_ids,
            'location_ids' => $loc_ids
        ];
    }
    /**
     * Handles the AJAX request for importing demo data.
     *
     * @since 1.0.0
     * @access public
     *
     * @return void
     */
    public static function import_demo()
    {
        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                wp_send_json_error(['message' => 'Nonce verification failed.']);
            }
        }

        $type = sanitize_text_field(wp_unslash($_POST['demo_type'] ?? 'spa'));

        // Ensure seeder class is loaded


        // Call the seeder's import method
        $result = self::import_demo_seeder($type);

        $response_data = [
            'message' => 'Demo data imported successfully for ' . ucfirst($type),
            'service_id' => !empty($result['service_ids']) ? $result['service_ids'][0] : null,
            'staff_id' => !empty($result['staff_ids']) ? $result['staff_ids'][0] : null,
            'location_id' => !empty($result['location_ids']) ? $result['location_ids'][0] : null
        ];

        wp_send_json_success($response_data);
    }

    /**
     * Marks the initial setup as complete.
     *
     * @since 1.0.0
     * @access public
     *
     * @return void
     */
    public static function mark_setup_complete()
    {
        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                wp_send_json_error(['message' => 'Nonce verification failed.']);
            }
        }

        update_option('bookingor_starter_setup_completed', 'yes');
        wp_send_json_success(['message' => 'Setup marked as complete.']);
    }

    /**
     * Saves a manual service and category from the wizard.
     */
    public static function save_wizard_service()
    {
        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                wp_send_json_error(['message' => 'Nonce verification failed.']);
            }
        }

        global $wpdb;
        $full_prefix = $wpdb->prefix . self::$dp_prefix;

        $cat_name = sanitize_text_field(wp_unslash($_POST['category_name'] ?? ''));
        $svc_name = sanitize_text_field(wp_unslash($_POST['service_name'] ?? ''));
        $svc_cost = floatval(wp_unslash($_POST['service_cost'] ?? 0));
        $svc_dur = intval(wp_unslash($_POST['service_duration'] ?? 60));
        $svc_dur_type = sanitize_text_field(wp_unslash($_POST['service_duration_type'] ?? 'minute'));
        $loc_title = sanitize_text_field(wp_unslash($_POST['location_title'] ?? ''));
        $loc_address = sanitize_text_field(wp_unslash($_POST['location_address'] ?? ''));

        if (empty($cat_name) || empty($svc_name)) {
            wp_send_json_error(['message' => 'Category and Service names are required.']);
        }

        if (empty($loc_title)) {
            wp_send_json_error(['message' => 'Location title is required.']);
        }

        // 1. Create Category
        update_option("bookingor_settings_category_active", "on");
        $wpdb->insert($full_prefix . 'categories', [
            'category_name' => $cat_name,
            'icon' => '',
            'status' => 1
        ]);
        $cat_id = $wpdb->insert_id;

        // 2. Create Service
        $wpdb->insert($full_prefix . 'services', [
            'service_name' => $svc_name,
            'service_cost' => $svc_cost,
            'service_duration' => $svc_dur,
            'category_get_id' => $cat_id,
            'service_icon' => '',
            'service_description' => '',
            'service_deposit' => 0,
            'service_deposit_type' => '',
            'service_tax' => 0,
            'service_duration_type' => $svc_dur_type,
            'service_duration_count' => 1,
            'timeslot_length' => $svc_dur,
            'service_slot_increment' => 0,
            'padding_before' => 0,
            'padding_after' => 0,
            'service_capacity_min' => 1,
            'service_capacity_max' => 1,
            'recurring_status' => 0,
            'recurring_type' => '',
            'recurring_payment' => 0,
            'service_cancel_booking_time' => 24,
            'service_allow_booking_time' => 24,
            'service_allow_zoom_meeting' => 0,
            'single_booking_only_slot' => 0,
            'service_time_sheet' => '',
            'wc_id' => 0,
            'status' => 1
        ]);
        $svc_id = $wpdb->insert_id;

        // 3. Create Location
        $wpdb->insert($full_prefix . 'location', [
            'location_title' => $loc_title,
            'location_icon' => '',
            'location_country' => '',
            'location_city' => '',
            'location_address' => $loc_address,
            'location_phone' => '1234567890',
            'location_latitude' => '',
            'location_longitude' => '',
            'location_time_sheet' => '',
            'status' => 1
        ]);
        $loc_id = $wpdb->insert_id;

        // 4. Assign Service to Location
        $wpdb->insert($full_prefix . 'location_assign_service', [
            'location_get_id' => $loc_id,
            'service_get_id' => $svc_id,
        ]);

        if ($wpdb->last_error) {
            error_log('Bookingor Wizard Save Service Error: ' . $wpdb->last_error);
            wp_send_json_error(['message' => 'Database error: ' . $wpdb->last_error]);
        }

        wp_send_json_success(['message' => 'Service and Location saved successfully.', 'svc_id' => $svc_id, 'location_id' => $loc_id]);
    }

    /**
     * Saves a manual staff member from the wizard.
     */
    public static function save_wizard_staff()
    {
        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                wp_send_json_error(['message' => 'Nonce verification failed.']);
            }
        }

        global $wpdb;
        $full_prefix = $wpdb->prefix . self::$dp_prefix;

        $fname = sanitize_text_field(wp_unslash($_POST['staff_fname'] ?? ''));
        $lname = sanitize_text_field(wp_unslash($_POST['staff_lname'] ?? ''));
        $email = sanitize_email(wp_unslash($_POST['staff_email'] ?? ''));
        $phone = sanitize_text_field(wp_unslash($_POST['staff_phone'] ?? ''));

        if (empty($fname)) {
            wp_send_json_error(['message' => 'Staff first name is required.']);
        }

        if (empty($email) || empty($phone)) {
            wp_send_json_error(['message' => 'Staff email and phone are required.']);
        }

        $wpdb->insert($full_prefix . 'staff_add', [
            'staff_first_name' => $fname,
            'staff_last_name' => $lname,
            'staff_email' => $email,
            'staff_phone' => $phone,
            'staff_location' => '',
            'staff_icon' => '',
            'staff_tag_line' => '',
            'staff_about' => 'Staff member created via wizard.',
            'staff_sheet_weekly' => '',
            'staff_holiday' => '',
            'google_calendar_id' => '',
            'google_access_token' => '',
            'zoom_user_id' => '',
            'google_time_zone' => '',
            'status' => 1
        ]);
        $staff_id = $wpdb->insert_id;

        // Auto-assign all services to this staff member
        $services = $wpdb->get_results("SELECT service_id FROM {$full_prefix}services");
        foreach ($services as $svc) {
            $wpdb->insert($full_prefix . 'staff_assign_service', [
                'staff_get_id' => $staff_id,
                'service_get_id' => $svc->service_id,
                'staff_price' => 0,
            ]);
        }

        // Auto-assign this staff member to all locations
        $locations = $wpdb->get_results("SELECT location_id FROM {$full_prefix}location");
        foreach ($locations as $loc) {
            $wpdb->insert($full_prefix . 'location_assign_staff', [
                'location_get_id' => $loc->location_id,
                'staff_get_id' => $staff_id,
            ]);
        }

        if ($wpdb->last_error) {
            error_log('Bookingor Wizard Save Staff Error: ' . $wpdb->last_error);
            wp_send_json_error(['message' => 'Database error: ' . $wpdb->last_error]);
        }

        wp_send_json_success(['message' => 'Staff member saved and assigned to all services and locations.', 'staff_id' => $staff_id]);
    }

    /**
     * Saves a manual location from the wizard.
     */


    /**
     * Helper to get page by title safely using WP_Query (replacing deprecated get_page_by_title)
     */
    private static function get_page_by_title_safe($title, $post_type = 'page')
    {
        $query = new \WP_Query([
            'post_type' => $post_type,
            'title' => $title,
            'posts_per_page' => 1,
            'no_found_rows' => true,
            'ignore_sticky_posts' => true,
            'update_post_term_cache' => false,
            'update_post_meta_cache' => false,
            'orderby' => 'post_date',
            'order' => 'ASC',
            'post_status' => 'all',
        ]);

        return $query->have_posts() ? $query->posts[0] : null;
    }
}
