<?php
/**
 * Clinic Database Service
 *
 * Handles advanced clinic data operations and business logic
 *
 * @package Care_API
 * @subpackage Services\Database
 * @version    1.0.0
 * @author     Descomplicar® <dev@descomplicar.pt>
 * @link       https://descomplicar.pt
 * @since      1.0.0
 */

namespace Care_API\Services\Database;

use Care_API\Models\Clinic;
use Care_API\Services\Permission_Service;

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

/**
 * Class Clinic_Service
 *
 * Advanced database service for clinic management with business logic
 *
 * @since 1.0.0
 */
class Clinic_Service {

    /**
     * Initialize the service
     *
     * @since 1.0.0
     */
    public static function init() {
        // Hook into WordPress actions
        add_action( 'kivicare_clinic_created', array( self::class, 'on_clinic_created' ), 10, 2 );
        add_action( 'kivicare_clinic_updated', array( self::class, 'on_clinic_updated' ), 10, 2 );
        add_action( 'kivicare_clinic_deleted', array( self::class, 'on_clinic_deleted' ), 10, 1 );
    }

    /**
     * Create clinic with advanced business logic
     *
     * @param array $clinic_data Clinic data
     * @param int   $user_id     Creating user ID
     * @return array|WP_Error Clinic data or error
     * @since 1.0.0
     */
    public static function create_clinic( $clinic_data, $user_id = null ) {
        // Permission check
        if ( ! Permission_Service::current_user_can( 'manage_clinics' ) ) {
            return new \WP_Error(
                'insufficient_permissions',
                'You do not have permission to create clinics',
                array( 'status' => 403 )
            );
        }

        // Enhanced validation
        $validation = self::validate_clinic_business_rules( $clinic_data );
        if ( is_wp_error( $validation ) ) {
            return $validation;
        }

        // Add metadata
        $clinic_data['created_by'] = $user_id ?: get_current_user_id();
        $clinic_data['created_at'] = current_time( 'mysql' );

        // Create clinic
        $clinic_id = Clinic::create( $clinic_data );
        
        if ( is_wp_error( $clinic_id ) ) {
            return $clinic_id;
        }

        // Post-creation tasks
        self::setup_clinic_defaults( $clinic_id, $clinic_data );
        
        // Trigger action
        do_action( 'kivicare_clinic_created', $clinic_id, $clinic_data );

        // Return full clinic data
        return self::get_clinic_with_metadata( $clinic_id );
    }

    /**
     * Update clinic with business logic
     *
     * @param int   $clinic_id   Clinic ID
     * @param array $clinic_data Updated data
     * @return array|WP_Error Updated clinic data or error
     * @since 1.0.0
     */
    public static function update_clinic( $clinic_id, $clinic_data ) {
        // Permission check
        if ( ! Permission_Service::current_user_can( 'manage_clinics' ) ) {
            return new \WP_Error(
                'insufficient_permissions',
                'You do not have permission to update clinics',
                array( 'status' => 403 )
            );
        }

        // Check if clinic exists
        if ( ! Clinic::exists( $clinic_id ) ) {
            return new \WP_Error(
                'clinic_not_found',
                'Clinic not found',
                array( 'status' => 404 )
            );
        }

        // Get current data for comparison
        $current_data = Clinic::get_by_id( $clinic_id );
        
        // Enhanced validation
        $validation = self::validate_clinic_business_rules( $clinic_data, $clinic_id );
        if ( is_wp_error( $validation ) ) {
            return $validation;
        }

        // Add update metadata
        $clinic_data['updated_by'] = get_current_user_id();
        $clinic_data['updated_at'] = current_time( 'mysql' );

        // Update clinic
        $result = Clinic::update( $clinic_id, $clinic_data );
        
        if ( is_wp_error( $result ) ) {
            return $result;
        }

        // Handle specialty changes
        self::handle_specialty_changes( $clinic_id, $current_data, $clinic_data );

        // Trigger action
        do_action( 'kivicare_clinic_updated', $clinic_id, $clinic_data );

        // Return updated clinic data
        return self::get_clinic_with_metadata( $clinic_id );
    }

    /**
     * Get clinic with enhanced metadata
     *
     * @param int $clinic_id Clinic ID
     * @return array|WP_Error Clinic data with metadata or error
     * @since 1.0.0
     */
    public static function get_clinic_with_metadata( $clinic_id ) {
        // Permission check
        if ( ! Permission_Service::can_access_clinic( get_current_user_id(), $clinic_id ) ) {
            return new \WP_Error(
                'access_denied',
                'You do not have access to this clinic',
                array( 'status' => 403 )
            );
        }

        $clinic = Clinic::get_by_id( $clinic_id );
        
        if ( ! $clinic ) {
            return new \WP_Error(
                'clinic_not_found',
                'Clinic not found',
                array( 'status' => 404 )
            );
        }

        // Add enhanced metadata
        $clinic['statistics'] = self::get_clinic_statistics( $clinic_id );
        $clinic['doctors'] = self::get_clinic_doctors( $clinic_id );
        $clinic['services'] = self::get_clinic_services( $clinic_id );
        $clinic['working_hours'] = self::get_clinic_working_hours( $clinic_id );
        $clinic['contact_info'] = self::get_clinic_contact_info( $clinic_id );

        return $clinic;
    }

    /**
     * Get clinics accessible to user with filters
     *
     * @param array $args Query arguments
     * @return array Clinics with metadata
     * @since 1.0.0
     */
    public static function get_accessible_clinics( $args = array() ) {
        $user_id = get_current_user_id();
        $accessible_clinic_ids = Permission_Service::get_accessible_clinic_ids( $user_id );

        if ( empty( $accessible_clinic_ids ) ) {
            return array(
                'clinics' => array(),
                'total' => 0,
                'has_more' => false
            );
        }

        // Add clinic filter to args
        $args['clinic_ids'] = $accessible_clinic_ids;

        $defaults = array(
            'limit' => 20,
            'offset' => 0,
            'status' => 1,
            'include_statistics' => false,
            'include_doctors' => false,
            'include_services' => false
        );

        $args = wp_parse_args( $args, $defaults );

        // Get clinics with custom query for better performance
        $clinics = self::query_clinics_with_filters( $args );
        
        // Add metadata if requested
        if ( $args['include_statistics'] || $args['include_doctors'] || $args['include_services'] ) {
            foreach ( $clinics as &$clinic ) {
                if ( $args['include_statistics'] ) {
                    $clinic['statistics'] = self::get_clinic_statistics( $clinic['id'] );
                }
                if ( $args['include_doctors'] ) {
                    $clinic['doctors'] = self::get_clinic_doctors( $clinic['id'] );
                }
                if ( $args['include_services'] ) {
                    $clinic['services'] = self::get_clinic_services( $clinic['id'] );
                }
            }
        }

        // Get total count for pagination
        $total = self::count_clinics_with_filters( $args );

        return array(
            'clinics' => $clinics,
            'total' => $total,
            'has_more' => ( $args['offset'] + $args['limit'] ) < $total
        );
    }

    /**
     * Search clinics with advanced criteria
     *
     * @param string $search_term Search term
     * @param array  $filters     Additional filters
     * @return array Search results
     * @since 1.0.0
     */
    public static function search_clinics( $search_term, $filters = array() ) {
        global $wpdb;

        $user_id = get_current_user_id();
        $accessible_clinic_ids = Permission_Service::get_accessible_clinic_ids( $user_id );

        if ( empty( $accessible_clinic_ids ) ) {
            return array();
        }

        // Build search query
        $where_clauses = array( "c.id IN (" . implode( ',', $accessible_clinic_ids ) . ")" );
        $where_values = array();

        // Search term
        if ( ! empty( $search_term ) ) {
            $where_clauses[] = "(c.name LIKE %s OR c.address LIKE %s OR c.city LIKE %s OR c.specialties LIKE %s)";
            $search_term = '%' . $wpdb->esc_like( $search_term ) . '%';
            $where_values = array_merge( $where_values, array_fill( 0, 4, $search_term ) );
        }

        // Location filter
        if ( ! empty( $filters['city'] ) ) {
            $where_clauses[] = "c.city = %s";
            $where_values[] = $filters['city'];
        }

        if ( ! empty( $filters['state'] ) ) {
            $where_clauses[] = "c.state = %s";
            $where_values[] = $filters['state'];
        }

        // Specialty filter
        if ( ! empty( $filters['specialty'] ) ) {
            $where_clauses[] = "c.specialties LIKE %s";
            $where_values[] = '%' . $wpdb->esc_like( $filters['specialty'] ) . '%';
        }

        $where_sql = implode( ' AND ', $where_clauses );

        $query = "SELECT c.*, 
                         COUNT(DISTINCT dcm.doctor_id) as doctor_count,
                         COUNT(DISTINCT pcm.patient_id) as patient_count
                  FROM {$wpdb->prefix}kc_clinics c
                  LEFT JOIN {$wpdb->prefix}kc_doctor_clinic_mappings dcm ON c.id = dcm.clinic_id
                  LEFT JOIN {$wpdb->prefix}kc_patient_clinic_mappings pcm ON c.id = pcm.clinic_id
                  WHERE {$where_sql}
                  GROUP BY c.id
                  ORDER BY c.name ASC
                  LIMIT 20";

        if ( ! empty( $where_values ) ) {
            $results = $wpdb->get_results( $wpdb->prepare( $query, $where_values ), ARRAY_A );
        } else {
            $results = $wpdb->get_results( $query, ARRAY_A );
        }

        return array_map( function( $clinic ) {
            $clinic['id'] = (int) $clinic['id'];
            $clinic['doctor_count'] = (int) $clinic['doctor_count'];
            $clinic['patient_count'] = (int) $clinic['patient_count'];
            return $clinic;
        }, $results );
    }

    /**
     * Get clinic dashboard data
     *
     * @param int $clinic_id Clinic ID
     * @return array|WP_Error Dashboard data or error
     * @since 1.0.0
     */
    public static function get_clinic_dashboard( $clinic_id ) {
        // Permission check
        if ( ! Permission_Service::can_access_clinic( get_current_user_id(), $clinic_id ) ) {
            return new \WP_Error(
                'access_denied',
                'You do not have access to this clinic dashboard',
                array( 'status' => 403 )
            );
        }

        $dashboard = array();

        // Basic clinic info
        $dashboard['clinic'] = Clinic::get_by_id( $clinic_id );
        
        if ( ! $dashboard['clinic'] ) {
            return new \WP_Error(
                'clinic_not_found',
                'Clinic not found',
                array( 'status' => 404 )
            );
        }

        // Statistics
        $dashboard['statistics'] = self::get_comprehensive_statistics( $clinic_id );

        // Recent activity
        $dashboard['recent_appointments'] = self::get_recent_appointments( $clinic_id, 10 );
        $dashboard['recent_patients'] = self::get_recent_patients( $clinic_id, 10 );

        // Performance metrics
        $dashboard['performance'] = self::get_performance_metrics( $clinic_id );

        // Alerts and notifications
        $dashboard['alerts'] = self::get_clinic_alerts( $clinic_id );

        return $dashboard;
    }

    /**
     * Get clinic performance metrics
     *
     * @param int $clinic_id Clinic ID
     * @return array Performance metrics
     * @since 1.0.0
     */
    public static function get_performance_metrics( $clinic_id ) {
        global $wpdb;

        $metrics = array();

        // Appointment completion rate (last 30 days)
        $completion_data = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT 
                    COUNT(*) as total_appointments,
                    SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as completed_appointments,
                    SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as cancelled_appointments,
                    SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) as no_show_appointments
                 FROM {$wpdb->prefix}kc_appointments 
                 WHERE clinic_id = %d 
                 AND appointment_start_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)",
                $clinic_id
            ),
            ARRAY_A
        );

        if ( $completion_data && $completion_data['total_appointments'] > 0 ) {
            $total = (int) $completion_data['total_appointments'];
            $metrics['completion_rate'] = round( ( (int) $completion_data['completed_appointments'] / $total ) * 100, 1 );
            $metrics['cancellation_rate'] = round( ( (int) $completion_data['cancelled_appointments'] / $total ) * 100, 1 );
            $metrics['no_show_rate'] = round( ( (int) $completion_data['no_show_appointments'] / $total ) * 100, 1 );
        } else {
            $metrics['completion_rate'] = 0;
            $metrics['cancellation_rate'] = 0;
            $metrics['no_show_rate'] = 0;
        }

        // Average patient wait time (would require additional tracking)
        $metrics['avg_wait_time'] = 0; // Placeholder

        // Revenue trend (last 3 months)
        $metrics['revenue_trend'] = self::get_revenue_trend( $clinic_id, 3 );

        // Utilization rate (appointments vs. available slots)
        $metrics['utilization_rate'] = self::calculate_utilization_rate( $clinic_id );

        return $metrics;
    }

    /**
     * Validate clinic business rules
     *
     * @param array $clinic_data Clinic data
     * @param int   $clinic_id   Clinic ID (for updates)
     * @return bool|WP_Error True if valid, WP_Error otherwise
     * @since 1.0.0
     */
    private static function validate_clinic_business_rules( $clinic_data, $clinic_id = null ) {
        global $wpdb;

        $errors = array();

        // Check for duplicate clinic name in same city
        if ( ! empty( $clinic_data['name'] ) && ! empty( $clinic_data['city'] ) ) {
            $existing_query = "SELECT id FROM {$wpdb->prefix}kc_clinics WHERE name = %s AND city = %s";
            $query_params = array( $clinic_data['name'], $clinic_data['city'] );

            if ( $clinic_id ) {
                $existing_query .= " AND id != %d";
                $query_params[] = $clinic_id;
            }

            $existing_clinic = $wpdb->get_var( $wpdb->prepare( $existing_query, $query_params ) );
            
            if ( $existing_clinic ) {
                $errors[] = 'A clinic with this name already exists in the same city';
            }
        }

        // Validate contact information format
        if ( ! empty( $clinic_data['telephone_no'] ) ) {
            if ( ! preg_match( '/^[+]?[0-9\s\-\(\)]{7,20}$/', $clinic_data['telephone_no'] ) ) {
                $errors[] = 'Invalid telephone number format';
            }
        }

        // Validate specialties if provided
        if ( ! empty( $clinic_data['specialties'] ) ) {
            $specialties = is_array( $clinic_data['specialties'] ) ? 
                $clinic_data['specialties'] : 
                json_decode( $clinic_data['specialties'], true );

            if ( is_array( $specialties ) ) {
                $valid_specialties = self::get_valid_specialties();
                foreach ( $specialties as $specialty ) {
                    if ( ! in_array( $specialty, $valid_specialties ) ) {
                        $errors[] = "Invalid specialty: {$specialty}";
                    }
                }
            }
        }

        // Validate clinic admin if provided
        if ( ! empty( $clinic_data['clinic_admin_id'] ) ) {
            $admin_user = get_user_by( 'id', $clinic_data['clinic_admin_id'] );
            if ( ! $admin_user || ! in_array( 'kivicare_doctor', $admin_user->roles ) ) {
                $errors[] = 'Clinic admin must be a valid doctor user';
            }
        }

        if ( ! empty( $errors ) ) {
            return new \WP_Error(
                'clinic_business_validation_failed',
                'Clinic business validation failed',
                array( 
                    'status' => 400,
                    'errors' => $errors 
                )
            );
        }

        return true;
    }

    /**
     * Setup clinic defaults after creation
     *
     * @param int   $clinic_id   Clinic ID
     * @param array $clinic_data Clinic data
     * @since 1.0.0
     */
    private static function setup_clinic_defaults( $clinic_id, $clinic_data ) {
        // Create default services
        self::create_default_services( $clinic_id );

        // Setup default working hours
        self::setup_default_working_hours( $clinic_id );

        // Create default appointment slots
        self::setup_default_appointment_slots( $clinic_id );

        // Initialize clinic settings
        self::initialize_clinic_settings( $clinic_id );
    }

    /**
     * Create default services for new clinic
     *
     * @param int $clinic_id Clinic ID
     * @since 1.0.0
     */
    private static function create_default_services( $clinic_id ) {
        global $wpdb;

        $default_services = array(
            array( 'name' => 'General Consultation', 'type' => 'consultation', 'price' => 50.00, 'duration' => 30 ),
            array( 'name' => 'Follow-up Visit', 'type' => 'consultation', 'price' => 30.00, 'duration' => 15 ),
            array( 'name' => 'Health Checkup', 'type' => 'checkup', 'price' => 80.00, 'duration' => 45 )
        );

        foreach ( $default_services as $service ) {
            $wpdb->insert(
                $wpdb->prefix . 'kc_services',
                array_merge( $service, array(
                    'clinic_id' => $clinic_id,
                    'status' => 1,
                    'created_at' => current_time( 'mysql' )
                ) )
            );
        }
    }

    /**
     * Setup default working hours
     *
     * @param int $clinic_id Clinic ID
     * @since 1.0.0
     */
    private static function setup_default_working_hours( $clinic_id ) {
        $default_hours = array(
            'monday' => array( 'start_time' => '09:00', 'end_time' => '17:00' ),
            'tuesday' => array( 'start_time' => '09:00', 'end_time' => '17:00' ),
            'wednesday' => array( 'start_time' => '09:00', 'end_time' => '17:00' ),
            'thursday' => array( 'start_time' => '09:00', 'end_time' => '17:00' ),
            'friday' => array( 'start_time' => '09:00', 'end_time' => '17:00' ),
            'saturday' => array( 'start_time' => '09:00', 'end_time' => '13:00' ),
            'sunday' => array( 'closed' => true )
        );

        update_option( "kivicare_clinic_{$clinic_id}_working_hours", $default_hours );
    }

    /**
     * Get clinic statistics
     *
     * @param int $clinic_id Clinic ID
     * @return array Statistics
     * @since 1.0.0
     */
    private static function get_clinic_statistics( $clinic_id ) {
        return Clinic::get_statistics( $clinic_id );
    }

    /**
     * Get clinic doctors
     *
     * @param int $clinic_id Clinic ID
     * @return array Doctors
     * @since 1.0.0
     */
    private static function get_clinic_doctors( $clinic_id ) {
        global $wpdb;

        return $wpdb->get_results(
            $wpdb->prepare(
                "SELECT u.ID, u.display_name, u.user_email,
                        COUNT(a.id) as total_appointments
                 FROM {$wpdb->prefix}kc_doctor_clinic_mappings dcm
                 JOIN {$wpdb->prefix}users u ON dcm.doctor_id = u.ID
                 LEFT JOIN {$wpdb->prefix}kc_appointments a ON u.ID = a.doctor_id AND a.clinic_id = %d
                 WHERE dcm.clinic_id = %d
                 GROUP BY u.ID
                 ORDER BY u.display_name",
                $clinic_id, $clinic_id
            ),
            ARRAY_A
        );
    }

    /**
     * Get clinic services
     *
     * @param int $clinic_id Clinic ID
     * @return array Services
     * @since 1.0.0
     */
    private static function get_clinic_services( $clinic_id ) {
        global $wpdb;

        return $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}kc_services WHERE clinic_id = %d AND status = 1 ORDER BY name",
                $clinic_id
            ),
            ARRAY_A
        );
    }

    /**
     * Get clinic working hours
     *
     * @param int $clinic_id Clinic ID
     * @return array Working hours
     * @since 1.0.0
     */
    private static function get_clinic_working_hours( $clinic_id ) {
        return get_option( "kivicare_clinic_{$clinic_id}_working_hours", array() );
    }

    /**
     * Get clinic contact information
     *
     * @param int $clinic_id Clinic ID
     * @return array Contact info
     * @since 1.0.0
     */
    private static function get_clinic_contact_info( $clinic_id ) {
        $clinic = Clinic::get_by_id( $clinic_id );
        
        if ( ! $clinic ) {
            return array();
        }

        return array(
            'email' => $clinic['email'],
            'telephone' => $clinic['telephone_no'],
            'address' => $clinic['address'],
            'city' => $clinic['city'],
            'state' => $clinic['state'],
            'country' => $clinic['country'],
            'postal_code' => $clinic['postal_code']
        );
    }

    /**
     * Get valid medical specialties
     *
     * @return array Valid specialties
     * @since 1.0.0
     */
    private static function get_valid_specialties() {
        return array(
            'general_medicine', 'cardiology', 'dermatology', 'endocrinology',
            'gastroenterology', 'gynecology', 'neurology', 'oncology',
            'ophthalmology', 'orthopedics', 'otolaryngology', 'pediatrics',
            'psychiatry', 'pulmonology', 'radiology', 'urology'
        );
    }

    /**
     * Query clinics with custom filters
     *
     * @param array $args Query arguments
     * @return array Clinics
     * @since 1.0.0
     */
    private static function query_clinics_with_filters( $args ) {
        global $wpdb;

        $where_clauses = array( '1=1' );
        $where_values = array();

        if ( ! empty( $args['clinic_ids'] ) ) {
            $placeholders = implode( ',', array_fill( 0, count( $args['clinic_ids'] ), '%d' ) );
            $where_clauses[] = "id IN ({$placeholders})";
            $where_values = array_merge( $where_values, $args['clinic_ids'] );
        }

        if ( isset( $args['status'] ) ) {
            $where_clauses[] = 'status = %d';
            $where_values[] = $args['status'];
        }

        $where_sql = implode( ' AND ', $where_clauses );

        $query = "SELECT * FROM {$wpdb->prefix}kc_clinics WHERE {$where_sql} ORDER BY name ASC LIMIT %d OFFSET %d";
        $where_values[] = $args['limit'];
        $where_values[] = $args['offset'];

        return $wpdb->get_results( $wpdb->prepare( $query, $where_values ), ARRAY_A );
    }

    /**
     * Count clinics with filters
     *
     * @param array $args Query arguments
     * @return int Count
     * @since 1.0.0
     */
    private static function count_clinics_with_filters( $args ) {
        global $wpdb;

        $where_clauses = array( '1=1' );
        $where_values = array();

        if ( ! empty( $args['clinic_ids'] ) ) {
            $placeholders = implode( ',', array_fill( 0, count( $args['clinic_ids'] ), '%d' ) );
            $where_clauses[] = "id IN ({$placeholders})";
            $where_values = array_merge( $where_values, $args['clinic_ids'] );
        }

        if ( isset( $args['status'] ) ) {
            $where_clauses[] = 'status = %d';
            $where_values[] = $args['status'];
        }

        $where_sql = implode( ' AND ', $where_clauses );
        $query = "SELECT COUNT(*) FROM {$wpdb->prefix}kc_clinics WHERE {$where_sql}";

        if ( ! empty( $where_values ) ) {
            return (int) $wpdb->get_var( $wpdb->prepare( $query, $where_values ) );
        }

        return (int) $wpdb->get_var( $query );
    }

    /**
     * Handle clinic specialty changes
     *
     * @param int   $clinic_id    Clinic ID
     * @param array $current_data Current clinic data
     * @param array $new_data     New clinic data
     * @since 1.0.0
     */
    private static function handle_specialty_changes( $clinic_id, $current_data, $new_data ) {
        if ( ! isset( $new_data['specialties'] ) ) {
            return;
        }

        $old_specialties = is_array( $current_data['specialties'] ) ? 
            $current_data['specialties'] : 
            json_decode( $current_data['specialties'] ?? '[]', true );

        $new_specialties = is_array( $new_data['specialties'] ) ? 
            $new_data['specialties'] : 
            json_decode( $new_data['specialties'], true );

        // Trigger action if specialties changed
        if ( $old_specialties !== $new_specialties ) {
            do_action( 'kivicare_clinic_specialties_changed', $clinic_id, $old_specialties, $new_specialties );
        }
    }

    /**
     * Event handler: Clinic created
     *
     * @param int   $clinic_id   Clinic ID
     * @param array $clinic_data Clinic data
     * @since 1.0.0
     */
    public static function on_clinic_created( $clinic_id, $clinic_data ) {
        // Log the creation
        error_log( "Care: New clinic created - ID: {$clinic_id}, Name: " . ( $clinic_data['name'] ?? 'Unknown' ) );

        // Could trigger notifications, integrations, etc.
    }

    /**
     * Event handler: Clinic updated
     *
     * @param int   $clinic_id   Clinic ID
     * @param array $clinic_data Updated clinic data
     * @since 1.0.0
     */
    public static function on_clinic_updated( $clinic_id, $clinic_data ) {
        // Log the update
        error_log( "Care: Clinic updated - ID: {$clinic_id}" );

        // Clear related caches
        wp_cache_delete( "clinic_{$clinic_id}", 'kivicare' );
    }

    /**
     * Event handler: Clinic deleted
     *
     * @param int $clinic_id Clinic ID
     * @since 1.0.0
     */
    public static function on_clinic_deleted( $clinic_id ) {
        // Clean up related data
        delete_option( "kivicare_clinic_{$clinic_id}_working_hours" );
        delete_option( "kivicare_clinic_{$clinic_id}_settings" );

        // Clear caches
        wp_cache_delete( "clinic_{$clinic_id}", 'kivicare' );

        // Log the deletion
        error_log( "Care: Clinic deleted - ID: {$clinic_id}" );
    }
}