<?php
/**
 * Service Model
 *
 * @package Booktics/Models
 */

namespace Booktics\Models;

use Booktics\Abstracts\Post_Model;
use BookticsPro\Models\Extra_Service_Model;

/**
 * Service_Model class
 */
class Service_Model extends Post_Model {
    /**
     * Store service data
     *
     * @var array<string, mixed>
     */
    protected $fillable = [
        'id'                                 => '',
        'title'                              => '',
        'description'                        => '',
        'content'                            => '',
        'link'                               => '',
        'image'                              => '',
        'image_id'                           => '',
        'categories'                         => [],
        'status'                             => '',
        'enable_custom_holiday'              => false,
        'enable_custom_schedule'             => false,
        'enable_additional_service_duration' => false,
        'interval_time'                      => 0,
        'before_buffer_time'                 => 0,
        'after_buffer_time'                  => 0,
        'team_member'                        => [],
        'show_end_time'                      => false,
        'additional_durations'               => [],
        'schedule'                           => [],
        'custom'                             => [],
        'holiday'                            => [],
    ];

    /**
     * Get post type
     *
     * @return  string Post type name
     */
    public function get_post_type() {
        return 'booktics-service';
    }

    /**
     * Delete a record and cleanup connected extra services
     * 
     *
     * @return  WP_Post|false|null Post data on success, false or null on failure.
     */
    public function delete() {
        if ( ! $this->post ) {
            return false;
        }

        // Get the service ID before deletion
        $service_id = $this->post->ID;

        // Cleanup connected extra services before deleting the service
        $this->cleanup_connected_extra_services( $service_id );

        // Call parent delete method to delete the service post
        return parent::delete();
    }

    /**
     * Cleanup connected extra services by removing this service ID from their connected_services array
     *
     * @param int $service_id The ID of the service being deleted
     *
     * @return void
     */
    private function cleanup_connected_extra_services( $service_id ) {
        try {
            // Get all extra services that have this service in their connected_services array
            $args = array(
                'post_type'      => 'booktics-ex-service',
                'post_status'    => array( 'publish', 'active', 'pending' ),
                'posts_per_page' => -1,
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Meta query is necessary for filtering services by meta fields
                'meta_query'     => array(
                    array(
                        'key'     => 'connected_services',
                        'value'   => "i:{$service_id}",
                        'compare' => 'LIKE',
                    ),
                ),
                'fields'         => 'ids',
            );

            $extra_service_post_ids = get_posts( $args );

            foreach ( $extra_service_post_ids as $post_id ) {
                try {
                    $extra_service_model = new Extra_Service_Model( $post_id );
                    if ( ! $extra_service_model ) {
                        if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
                            error_log( "Failed to instantiate Extra_Service_Model for post_id: $post_id" ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                        }
                        continue;
                    }

                    $extra_service_array = $extra_service_model->to_array();
                    $connected_services = isset( $extra_service_array['connected_services'] ) ? $extra_service_array['connected_services'] : array();

                    // Remove this service ID from the connected_services array
                    if ( is_array( $connected_services ) && in_array( $service_id, $connected_services, true ) ) {
                        $connected_services = array_values(
                            array_filter(
                                $connected_services, function ( $id ) use ( $service_id ) {
                                    return $id != $service_id;
                                }
                            )
                        );

                        $extra_service_array['connected_services'] = $connected_services;
                        $result = $extra_service_model->update( $extra_service_array );
                        if ( is_wp_error( $result ) ) {
                            if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
                                error_log( 'Failed to update Extra_Service_Model during cleanup: ' . $result->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                            }
                        }
                    }
                } catch ( \Throwable $e ) {
                    if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
                        error_log( 'Exception in cleanup_connected_extra_services: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                    }
                }
            }
        } catch ( \Throwable $e ) {
            if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
                error_log( 'Exception in cleanup_connected_extra_services: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            }
        }
    }
}
