<?php
/**
 * Event Types Service
 *
 * Manages event type definitions, presets, and templates
 *
 * @package NemtlyBooking
 * @since   PBOOKING_SINCE
 */

namespace NemtlyBooking\Services;

/**
 * Event Types Service class
 *
 * Handles event type presets, custom templates, and configuration
 *
 * @since PBOOKING_SINCE
 */
class Event_Types_Service {

    /**
     * Default event types with their preset configurations
     *
     * @since PBOOKING_SINCE
     *
     * @var array
     */
    private $default_types = [
        'one-on-one' => [
            'label'          => 'One-on-One',
            'description'    => 'Private appointments with a single attendee per time slot. Each booking fills the slot completely.',
            'help'           => 'Best for: doctor visits, barber appointments, consulting calls, tutoring sessions, therapy, personal training.',
            'icon'           => '👤',
            'duration'       => 30,
            'max_attendees'  => 1,
            'buffer_before'  => 0,
            'buffer_after'   => 15,
            'booking_cutoff' => 2,
            'slot_based'     => true,
            'allow_waitlist' => false,
        ],
        'group'      => [
            'label'          => 'Group',
            'description'    => 'Sessions with a fixed number of spots. Multiple people book into the same time slot until capacity is reached.',
            'help'           => 'Best for: yoga classes, workshops, cooking classes, group training, seminars, study groups.',
            'icon'           => '👥',
            'duration'       => 60,
            'max_attendees'  => 20,
            'buffer_before'  => 0,
            'buffer_after'   => 15,
            'booking_cutoff' => 24,
            'slot_based'     => true,
            'allow_waitlist' => true,
        ],
        'event'      => [
            'label'          => 'Event',
            'description'    => 'Large-scale gatherings with high or unlimited capacity. Attendees purchase tickets or RSVP.',
            'help'           => 'Best for: concerts, conferences, meetups, festivals, galas, webinars, product launches.',
            'icon'           => '🎪',
            'duration'       => 180,
            'max_attendees'  => 0, // unlimited
            'buffer_before'  => 0,
            'buffer_after'   => 0,
            'booking_cutoff' => 48,
            'slot_based'     => false,
            'allow_waitlist' => true,
        ],
    ];

    /**
     * Get all available event types (default + custom templates)
     *
     * @since PBOOKING_SINCE
     *
     * @return array Array of event types with configurations
     */
    public function get_all_event_types() {
        $default_types    = $this->get_default_event_types();
        $custom_templates = $this->get_custom_templates();

        return array_merge( $default_types, $custom_templates );
    }

    /**
     * Get default event types
     *
     * @since PBOOKING_SINCE
     *
     * @return array Array of default event types
     */
    public function get_default_event_types() {
        return apply_filters( 'nemtly_booking_default_event_types', $this->default_types );
    }

    /**
     * Get custom event templates
     *
     * @since PBOOKING_SINCE
     *
     * @return array Array of custom templates
     */
    public function get_custom_templates() {
        $templates = get_option( 'nemtly_booking_event_templates', [] );

        // Format templates to match event type structure
        $formatted_templates = [];
        foreach ( $templates as $template_id => $template ) {
            $formatted_templates[ 'template_' . $template_id ] = array_merge(
                $template,
                [
                    'is_template' => true,
                    'template_id' => $template_id,
                ]
            );
        }

        return $formatted_templates;
    }

    /**
     * Get event type configuration by key
     *
     * @since PBOOKING_SINCE
     *
     * @param string $type_key Event type key
     *
     * @return array|null Event type configuration or null if not found
     */
    public function get_event_type( $type_key ) {
        $all_types = $this->get_all_event_types();

        return isset( $all_types[ $type_key ] ) ? $all_types[ $type_key ] : null;
    }

    /**
     * Save custom event template
     *
     * @since PBOOKING_SINCE
     *
     * @param array $template_data Template configuration
     *
     * @return string|WP_Error Template ID on success, WP_Error on failure
     */
    public function save_custom_template( $template_data ) {
        // Validate template data
        $validation_result = $this->validate_template_data( $template_data );
        if ( is_wp_error( $validation_result ) ) {
            return $validation_result;
        }

        // Get existing templates
        $templates = get_option( 'nemtly_booking_event_templates', [] );

        // Generate template ID
        $template_id = isset( $template_data['template_id'] ) ?
            $template_data['template_id'] :
            'custom_' . time() . '_' . wp_rand( 1000, 9999 );

        // Prepare template data
        $template = [
            'label'          => sanitize_text_field( $template_data['label'] ),
            'description'    => sanitize_textarea_field( $template_data['description'] ?? '' ),
            'icon'           => sanitize_text_field( $template_data['icon'] ?? '⚙️' ),
            'duration'       => intval( $template_data['duration'] ),
            'max_attendees'  => intval( $template_data['max_attendees'] ),
            'buffer_before'  => intval( $template_data['buffer_before'] ?? 0 ),
            'buffer_after'   => intval( $template_data['buffer_after'] ?? 0 ),
            'booking_cutoff' => intval( $template_data['booking_cutoff'] ?? 2 ),
            'slot_based'     => (bool) ( $template_data['slot_based'] ?? true ),
            'allow_waitlist' => (bool) ( $template_data['allow_waitlist'] ?? false ),
            'created_at'     => current_time( 'mysql' ),
            'updated_at'     => current_time( 'mysql' ),
        ];

        // Save template
        $templates[ $template_id ] = $template;
        $saved                     = update_option( 'nemtly_booking_event_templates', $templates );

        if ( ! $saved ) {
            return new \WP_Error(
                'template_save_failed',
                __( 'Failed to save event template', 'nemtly-booking' )
            );
        }

        // Dispatch event for template creation
        do_action( 'nemtly_booking_template_saved', $template_id, $template );

        return $template_id;
    }

    /**
     * Delete custom event template
     *
     * @since PBOOKING_SINCE
     *
     * @param string $template_id Template ID
     *
     * @return bool|WP_Error True on success, WP_Error on failure
     */
    public function delete_custom_template( $template_id ) {
        $templates = get_option( 'nemtly_booking_event_templates', [] );

        if ( ! isset( $templates[ $template_id ] ) ) {
            return new \WP_Error(
                'template_not_found',
                __( 'Template not found', 'nemtly-booking' )
            );
        }

        // Check if template is in use
        $template_in_use = $this->is_template_in_use( $template_id );
        if ( $template_in_use ) {
            return new \WP_Error(
                'template_in_use',
                __( 'Cannot delete template that is currently in use by events', 'nemtly-booking' )
            );
        }

        unset( $templates[ $template_id ] );
        $saved = update_option( 'nemtly_booking_event_templates', $templates );

        if ( ! $saved ) {
            return new \WP_Error(
                'template_delete_failed',
                __( 'Failed to delete event template', 'nemtly-booking' )
            );
        }

        // Dispatch event for template deletion
        do_action( 'nemtly_booking_template_deleted', $template_id );

        return true;
    }

    /**
     * Check if template is in use by any events
     *
     * @since PBOOKING_SINCE
     *
     * @param string $template_id Template ID
     *
     * @return bool True if template is in use, false otherwise
     */
    private function is_template_in_use( $template_id ) {
        global $wpdb;

        $count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->postmeta}
                 WHERE meta_key = 'nemtly_event_type'
                 AND meta_value = %s",
                'template_' . $template_id
            )
        );

        return $count > 0;
    }

    /**
     * Validate template data
     *
     * @since PBOOKING_SINCE
     *
     * @param array $template_data Template data to validate
     *
     * @return true|WP_Error True on success, WP_Error on validation failure
     */
    private function validate_template_data( $template_data ) {
        $errors = [];

        // Required fields
        if ( empty( $template_data['label'] ) ) {
            $errors[] = __( 'Template name is required', 'nemtly-booking' );
        }

        if ( empty( $template_data['duration'] ) || intval( $template_data['duration'] ) <= 0 ) {
            $errors[] = __( 'Duration must be greater than 0', 'nemtly-booking' );
        }

        if ( isset( $template_data['max_attendees'] ) && intval( $template_data['max_attendees'] ) < 0 ) {
            $errors[] = __( 'Max attendees cannot be negative', 'nemtly-booking' );
        }

        if ( isset( $template_data['buffer_before'] ) && intval( $template_data['buffer_before'] ) < 0 ) {
            $errors[] = __( 'Buffer before time cannot be negative', 'nemtly-booking' );
        }

        if ( isset( $template_data['buffer_after'] ) && intval( $template_data['buffer_after'] ) < 0 ) {
            $errors[] = __( 'Buffer after time cannot be negative', 'nemtly-booking' );
        }

        if ( isset( $template_data['booking_cutoff'] ) && intval( $template_data['booking_cutoff'] ) < 0 ) {
            $errors[] = __( 'Booking cutoff cannot be negative', 'nemtly-booking' );
        }

        if ( ! empty( $errors ) ) {
            return new \WP_Error( 'validation_failed', implode( '. ', $errors ) );
        }

        return true;
    }

    /**
     * Apply event type configuration to event data
     *
     * @since PBOOKING_SINCE
     *
     * @param array  $event_data Event data array
     * @param string $event_type Event type key
     *
     * @return array Modified event data with type configuration applied
     */
    public function apply_event_type_config( $event_data, $event_type ) {
        $type_config = $this->get_event_type( $event_type );

        if ( ! $type_config ) {
            return $event_data;
        }

        // Apply defaults only if values are not already set
        $defaults = [
            'duration'       => $type_config['duration'],
            'max_attendees'  => $type_config['max_attendees'],
            'buffer_before'  => $type_config['buffer_before'] ?? 0,
            'buffer_after'   => $type_config['buffer_after'] ?? 0,
            'booking_cutoff' => $type_config['booking_cutoff'] ?? 2,
            'allow_waitlist' => $type_config['allow_waitlist'] ?? false,
        ];

        foreach ( $defaults as $key => $default_value ) {
            if ( ! isset( $event_data[ $key ] ) || '' === $event_data[ $key ] ) {
                $event_data[ $key ] = $default_value;
            }
        }

        // Always set the event type
        $event_data['event_type'] = $event_type;

        return $event_data;
    }
}
