<?php
/**
 * Prescription Database Service
 *
 * Handles advanced prescription 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\Prescription;
use Care_API\Services\Permission_Service;

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

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

    /**
     * Prescription status constants
     */
    const STATUS_ACTIVE = 'active';
    const STATUS_COMPLETED = 'completed';
    const STATUS_CANCELLED = 'cancelled';
    const STATUS_DISCONTINUED = 'discontinued';

    /**
     * Initialize the service
     *
     * @since 1.0.0
     */
    public static function init() {
        // Hook into WordPress actions
        add_action( 'kivicare_prescription_created', array( self::class, 'on_prescription_created' ), 10, 2 );
        add_action( 'kivicare_prescription_updated', array( self::class, 'on_prescription_updated' ), 10, 2 );
        add_action( 'kivicare_prescription_cancelled', array( self::class, 'on_prescription_cancelled' ), 10, 1 );
        add_action( 'kivicare_prescription_completed', array( self::class, 'on_prescription_completed' ), 10, 1 );
    }

    /**
     * Create prescription with advanced business logic
     *
     * @param array $prescription_data Prescription data
     * @param int   $user_id           Creating user ID
     * @return array|WP_Error Prescription data or error
     * @since 1.0.0
     */
    public static function create_prescription( $prescription_data, $user_id = null ) {
        // Permission check
        if ( ! Permission_Service::can_prescribe_medication( get_current_user_id() ) ) {
            return new \WP_Error(
                'insufficient_permissions',
                'You do not have permission to create prescriptions',
                array( 'status' => 403 )
            );
        }

        // Enhanced validation
        $validation = self::validate_prescription_business_rules( $prescription_data );
        if ( is_wp_error( $validation ) ) {
            return $validation;
        }

        // Check drug interactions
        $interaction_check = self::check_drug_interactions( $prescription_data );
        if ( is_wp_error( $interaction_check ) ) {
            return $interaction_check;
        }

        // Add metadata
        $prescription_data['created_by'] = $user_id ?: get_current_user_id();
        $prescription_data['created_at'] = current_time( 'mysql' );
        $prescription_data['status'] = self::STATUS_ACTIVE;

        // Generate prescription number if not provided
        if ( empty( $prescription_data['prescription_number'] ) ) {
            $prescription_data['prescription_number'] = self::generate_prescription_number();
        }

        // Set prescription date if not provided
        if ( empty( $prescription_data['prescription_date'] ) ) {
            $prescription_data['prescription_date'] = current_time( 'Y-m-d' );
        }

        // Calculate end date based on duration
        if ( ! empty( $prescription_data['duration_days'] ) && empty( $prescription_data['end_date'] ) ) {
            $start_date = new \DateTime( $prescription_data['prescription_date'] );
            $start_date->add( new \DateInterval( 'P' . $prescription_data['duration_days'] . 'D' ) );
            $prescription_data['end_date'] = $start_date->format( 'Y-m-d' );
        }

        // Create prescription
        $prescription_id = Prescription::create( $prescription_data );
        
        if ( is_wp_error( $prescription_id ) ) {
            return $prescription_id;
        }

        // Post-creation tasks
        self::setup_prescription_defaults( $prescription_id, $prescription_data );
        
        // Add to patient medication history
        self::update_patient_medication_history( $prescription_id, 'added' );
        
        // Check for allergies and warnings
        self::check_patient_allergies( $prescription_id );
        
        // Trigger action
        do_action( 'kivicare_prescription_created', $prescription_id, $prescription_data );

        // Return full prescription data
        return self::get_prescription_with_metadata( $prescription_id );
    }

    /**
     * Update prescription with business logic
     *
     * @param int   $prescription_id   Prescription ID
     * @param array $prescription_data Updated data
     * @return array|WP_Error Updated prescription data or error
     * @since 1.0.0
     */
    public static function update_prescription( $prescription_id, $prescription_data ) {
        // Get current prescription data
        $current_prescription = Prescription::get_by_id( $prescription_id );
        if ( ! $current_prescription ) {
            return new \WP_Error(
                'prescription_not_found',
                'Prescription not found',
                array( 'status' => 404 )
            );
        }

        // Permission check
        if ( ! Permission_Service::can_modify_prescription( get_current_user_id(), $prescription_id ) ) {
            return new \WP_Error(
                'insufficient_permissions',
                'You do not have permission to update this prescription',
                array( 'status' => 403 )
            );
        }

        // Check if prescription can be modified
        if ( in_array( $current_prescription['status'], array( self::STATUS_COMPLETED, self::STATUS_CANCELLED ) ) ) {
            return new \WP_Error(
                'cannot_modify_prescription',
                'Cannot modify a completed or cancelled prescription',
                array( 'status' => 400 )
            );
        }

        // Enhanced validation
        $validation = self::validate_prescription_business_rules( $prescription_data, $prescription_id );
        if ( is_wp_error( $validation ) ) {
            return $validation;
        }

        // Check drug interactions for medication changes
        if ( isset( $prescription_data['medication_name'] ) || isset( $prescription_data['dosage'] ) ) {
            $interaction_check = self::check_drug_interactions( array_merge( $current_prescription, $prescription_data ) );
            if ( is_wp_error( $interaction_check ) ) {
                return $interaction_check;
            }
        }

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

        // Recalculate end date if duration changed
        if ( isset( $prescription_data['duration_days'] ) ) {
            $start_date = new \DateTime( $current_prescription['prescription_date'] );
            $start_date->add( new \DateInterval( 'P' . $prescription_data['duration_days'] . 'D' ) );
            $prescription_data['end_date'] = $start_date->format( 'Y-m-d' );
        }

        // Update prescription
        $result = Prescription::update( $prescription_id, $prescription_data );
        
        if ( is_wp_error( $result ) ) {
            return $result;
        }

        // Handle status changes
        self::handle_status_changes( $prescription_id, $current_prescription, $prescription_data );

        // Handle medication changes
        if ( isset( $prescription_data['medication_name'] ) ) {
            self::handle_medication_changes( $prescription_id, $current_prescription, $prescription_data );
        }

        // Trigger action
        do_action( 'kivicare_prescription_updated', $prescription_id, $prescription_data );

        // Return updated prescription data
        return self::get_prescription_with_metadata( $prescription_id );
    }

    /**
     * Cancel prescription
     *
     * @param int    $prescription_id Prescription ID
     * @param string $reason          Cancellation reason
     * @return array|WP_Error Updated prescription data or error
     * @since 1.0.0
     */
    public static function cancel_prescription( $prescription_id, $reason = '' ) {
        $prescription = Prescription::get_by_id( $prescription_id );
        if ( ! $prescription ) {
            return new \WP_Error(
                'prescription_not_found',
                'Prescription not found',
                array( 'status' => 404 )
            );
        }

        // Permission check
        if ( ! Permission_Service::can_modify_prescription( get_current_user_id(), $prescription_id ) ) {
            return new \WP_Error(
                'insufficient_permissions',
                'You do not have permission to cancel this prescription',
                array( 'status' => 403 )
            );
        }

        // Check if prescription can be cancelled
        if ( in_array( $prescription['status'], array( self::STATUS_COMPLETED, self::STATUS_CANCELLED ) ) ) {
            return new \WP_Error(
                'cannot_cancel_prescription',
                'Cannot cancel a completed or already cancelled prescription',
                array( 'status' => 400 )
            );
        }

        // Update prescription status
        $update_data = array(
            'status' => self::STATUS_CANCELLED,
            'cancellation_reason' => $reason,
            'cancelled_by' => get_current_user_id(),
            'cancelled_at' => current_time( 'mysql' ),
            'updated_at' => current_time( 'mysql' )
        );

        $result = Prescription::update( $prescription_id, $update_data );
        
        if ( is_wp_error( $result ) ) {
            return $result;
        }

        // Update patient medication history
        self::update_patient_medication_history( $prescription_id, 'cancelled' );

        // Send cancellation notifications
        self::send_prescription_notifications( $prescription_id, 'cancelled' );

        // Trigger action
        do_action( 'kivicare_prescription_cancelled', $prescription_id );

        return self::get_prescription_with_metadata( $prescription_id );
    }

    /**
     * Complete prescription
     *
     * @param int   $prescription_id Prescription ID
     * @param array $completion_data Completion data
     * @return array|WP_Error Updated prescription data or error
     * @since 1.0.0
     */
    public static function complete_prescription( $prescription_id, $completion_data = array() ) {
        $prescription = Prescription::get_by_id( $prescription_id );
        if ( ! $prescription ) {
            return new \WP_Error(
                'prescription_not_found',
                'Prescription not found',
                array( 'status' => 404 )
            );
        }

        // Permission check
        if ( ! Permission_Service::can_modify_prescription( get_current_user_id(), $prescription_id ) ) {
            return new \WP_Error(
                'insufficient_permissions',
                'You do not have permission to complete this prescription',
                array( 'status' => 403 )
            );
        }

        // Check if prescription can be completed
        if ( $prescription['status'] === self::STATUS_CANCELLED ) {
            return new \WP_Error(
                'cannot_complete_cancelled',
                'Cannot complete a cancelled prescription',
                array( 'status' => 400 )
            );
        }

        if ( $prescription['status'] === self::STATUS_COMPLETED ) {
            return new \WP_Error(
                'already_completed',
                'Prescription is already completed',
                array( 'status' => 400 )
            );
        }

        // Update prescription status
        $update_data = array_merge( $completion_data, array(
            'status' => self::STATUS_COMPLETED,
            'completed_by' => get_current_user_id(),
            'completed_at' => current_time( 'mysql' ),
            'updated_at' => current_time( 'mysql' )
        ));

        $result = Prescription::update( $prescription_id, $update_data );
        
        if ( is_wp_error( $result ) ) {
            return $result;
        }

        // Update patient medication history
        self::update_patient_medication_history( $prescription_id, 'completed' );

        // Send completion notifications
        self::send_prescription_notifications( $prescription_id, 'completed' );

        // Trigger action
        do_action( 'kivicare_prescription_completed', $prescription_id );

        return self::get_prescription_with_metadata( $prescription_id );
    }

    /**
     * Get prescription with enhanced metadata
     *
     * @param int $prescription_id Prescription ID
     * @return array|WP_Error Prescription data with metadata or error
     * @since 1.0.0
     */
    public static function get_prescription_with_metadata( $prescription_id ) {
        $prescription = Prescription::get_by_id( $prescription_id );
        
        if ( ! $prescription ) {
            return new \WP_Error(
                'prescription_not_found',
                'Prescription not found',
                array( 'status' => 404 )
            );
        }

        // Permission check
        if ( ! Permission_Service::can_view_prescription( get_current_user_id(), $prescription_id ) ) {
            return new \WP_Error(
                'access_denied',
                'You do not have access to this prescription',
                array( 'status' => 403 )
            );
        }

        // Add enhanced metadata
        $prescription['patient'] = self::get_prescription_patient( $prescription['patient_id'] );
        $prescription['doctor'] = self::get_prescription_doctor( $prescription['doctor_id'] );
        $prescription['clinic'] = self::get_prescription_clinic( $prescription['clinic_id'] ?? null );
        $prescription['encounter'] = self::get_prescription_encounter( $prescription['encounter_id'] ?? null );
        $prescription['medication_info'] = self::get_medication_info( $prescription['medication_name'] );
        $prescription['interactions'] = self::get_drug_interactions_for_patient( $prescription['patient_id'], $prescription['medication_name'] );
        $prescription['adherence'] = self::get_prescription_adherence( $prescription_id );
        $prescription['refills'] = self::get_prescription_refills( $prescription_id );

        return $prescription;
    }

    /**
     * Search prescriptions with advanced criteria
     *
     * @param array $filters Search filters
     * @return array Search results
     * @since 1.0.0
     */
    public static function search_prescriptions( $filters = array() ) {
        global $wpdb;

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

        // Build search query
        $where_clauses = array();
        $where_values = array();

        // Clinic filter
        if ( ! empty( $accessible_clinic_ids ) ) {
            $where_clauses[] = "(pr.clinic_id IN (" . implode( ',', $accessible_clinic_ids ) . ") OR pr.clinic_id IS NULL)";
        }

        // Date range filter
        if ( ! empty( $filters['start_date'] ) ) {
            $where_clauses[] = "DATE(pr.prescription_date) >= %s";
            $where_values[] = $filters['start_date'];
        }

        if ( ! empty( $filters['end_date'] ) ) {
            $where_clauses[] = "DATE(pr.prescription_date) <= %s";
            $where_values[] = $filters['end_date'];
        }

        // Doctor filter
        if ( ! empty( $filters['doctor_id'] ) ) {
            $where_clauses[] = "pr.doctor_id = %d";
            $where_values[] = $filters['doctor_id'];
        }

        // Patient filter
        if ( ! empty( $filters['patient_id'] ) ) {
            $where_clauses[] = "pr.patient_id = %d";
            $where_values[] = $filters['patient_id'];
        }

        // Status filter
        if ( ! empty( $filters['status'] ) ) {
            if ( is_array( $filters['status'] ) ) {
                $status_placeholders = implode( ',', array_fill( 0, count( $filters['status'] ), '%s' ) );
                $where_clauses[] = "pr.status IN ({$status_placeholders})";
                $where_values = array_merge( $where_values, $filters['status'] );
            } else {
                $where_clauses[] = "pr.status = %s";
                $where_values[] = $filters['status'];
            }
        }

        // Medication filter
        if ( ! empty( $filters['medication'] ) ) {
            $where_clauses[] = "pr.medication_name LIKE %s";
            $where_values[] = '%' . $wpdb->esc_like( $filters['medication'] ) . '%';
        }

        // Search term
        if ( ! empty( $filters['search'] ) ) {
            $where_clauses[] = "(p.first_name LIKE %s OR p.last_name LIKE %s OR d.first_name LIKE %s OR d.last_name LIKE %s OR pr.prescription_number LIKE %s OR pr.medication_name LIKE %s)";
            $search_term = '%' . $wpdb->esc_like( $filters['search'] ) . '%';
            $where_values = array_merge( $where_values, array_fill( 0, 6, $search_term ) );
        }

        $where_sql = ! empty( $where_clauses ) ? 'WHERE ' . implode( ' AND ', $where_clauses ) : '';

        // Pagination
        $limit = isset( $filters['limit'] ) ? (int) $filters['limit'] : 20;
        $offset = isset( $filters['offset'] ) ? (int) $filters['offset'] : 0;

        $query = "SELECT pr.*, 
                         p.first_name as patient_first_name, p.last_name as patient_last_name,
                         d.first_name as doctor_first_name, d.last_name as doctor_last_name,
                         c.name as clinic_name
                  FROM {$wpdb->prefix}kc_prescriptions pr
                  LEFT JOIN {$wpdb->prefix}kc_patients p ON pr.patient_id = p.id
                  LEFT JOIN {$wpdb->prefix}kc_doctors d ON pr.doctor_id = d.id
                  LEFT JOIN {$wpdb->prefix}kc_clinics c ON pr.clinic_id = c.id
                  {$where_sql}
                  ORDER BY pr.prescription_date DESC
                  LIMIT {$limit} OFFSET {$offset}";

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

        // Get total count for pagination
        $count_query = "SELECT COUNT(*) FROM {$wpdb->prefix}kc_prescriptions pr
                        LEFT JOIN {$wpdb->prefix}kc_patients p ON pr.patient_id = p.id
                        LEFT JOIN {$wpdb->prefix}kc_doctors d ON pr.doctor_id = d.id
                        LEFT JOIN {$wpdb->prefix}kc_clinics c ON pr.clinic_id = c.id
                        {$where_sql}";

        if ( ! empty( $where_values ) ) {
            $total = (int) $wpdb->get_var( $wpdb->prepare( $count_query, $where_values ) );
        } else {
            $total = (int) $wpdb->get_var( $count_query );
        }

        return array(
            'prescriptions' => array_map( function( $prescription ) {
                $prescription['id'] = (int) $prescription['id'];
                return $prescription;
            }, $results ),
            'total' => $total,
            'has_more' => ( $offset + $limit ) < $total
        );
    }

    /**
     * Get patient prescription history
     *
     * @param int $patient_id Patient ID
     * @param int $limit      Limit
     * @return array Prescription history
     * @since 1.0.0
     */
    public static function get_patient_prescription_history( $patient_id, $limit = 10 ) {
        global $wpdb;

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

        $where_clause = "pr.patient_id = %d";
        $where_values = array( $patient_id );

        if ( ! empty( $accessible_clinic_ids ) ) {
            $where_clause .= " AND (pr.clinic_id IN (" . implode( ',', $accessible_clinic_ids ) . ") OR pr.clinic_id IS NULL)";
        }

        $query = "SELECT pr.*, 
                         d.first_name as doctor_first_name, d.last_name as doctor_last_name,
                         c.name as clinic_name
                  FROM {$wpdb->prefix}kc_prescriptions pr
                  LEFT JOIN {$wpdb->prefix}kc_doctors d ON pr.doctor_id = d.id
                  LEFT JOIN {$wpdb->prefix}kc_clinics c ON pr.clinic_id = c.id
                  WHERE {$where_clause}
                  ORDER BY pr.prescription_date DESC
                  LIMIT %d";

        $where_values[] = $limit;

        $results = $wpdb->get_results( 
            $wpdb->prepare( $query, $where_values ), 
            ARRAY_A 
        );

        return array_map( function( $prescription ) {
            $prescription['id'] = (int) $prescription['id'];
            $prescription['medication_info'] = self::get_medication_info( $prescription['medication_name'] );
            return $prescription;
        }, $results );
    }

    /**
     * Generate unique prescription number
     *
     * @return string Prescription number
     * @since 1.0.0
     */
    private static function generate_prescription_number() {
        global $wpdb;

        $date_prefix = 'RX' . current_time( 'Ymd' );
        
        // Get the highest existing prescription number for today
        $max_number = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT MAX(CAST(SUBSTRING(prescription_number, 11) AS UNSIGNED)) 
                 FROM {$wpdb->prefix}kc_prescriptions 
                 WHERE prescription_number LIKE %s",
                $date_prefix . '%'
            )
        );

        $next_number = ( $max_number ? $max_number + 1 : 1 );
        
        return $date_prefix . str_pad( $next_number, 4, '0', STR_PAD_LEFT );
    }

    /**
     * Validate prescription business rules
     *
     * @param array $prescription_data Prescription data
     * @param int   $prescription_id   Prescription ID (for updates)
     * @return bool|WP_Error True if valid, WP_Error otherwise
     * @since 1.0.0
     */
    private static function validate_prescription_business_rules( $prescription_data, $prescription_id = null ) {
        $errors = array();

        // Validate required fields
        $required_fields = array( 'patient_id', 'doctor_id', 'medication_name', 'dosage', 'frequency' );
        
        foreach ( $required_fields as $field ) {
            if ( empty( $prescription_data[$field] ) ) {
                $errors[] = "Field {$field} is required";
            }
        }

        // Validate patient exists
        if ( ! empty( $prescription_data['patient_id'] ) ) {
            global $wpdb;
            $patient_exists = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT id FROM {$wpdb->prefix}kc_patients WHERE id = %d",
                    $prescription_data['patient_id']
                )
            );
            
            if ( ! $patient_exists ) {
                $errors[] = 'Invalid patient ID';
            }
        }

        // Validate doctor exists and has prescription privileges
        if ( ! empty( $prescription_data['doctor_id'] ) ) {
            global $wpdb;
            $doctor = $wpdb->get_row(
                $wpdb->prepare(
                    "SELECT id, license_number FROM {$wpdb->prefix}kc_doctors WHERE id = %d",
                    $prescription_data['doctor_id']
                ),
                ARRAY_A
            );
            
            if ( ! $doctor ) {
                $errors[] = 'Invalid doctor ID';
            } elseif ( empty( $doctor['license_number'] ) ) {
                $errors[] = 'Doctor must have a valid license number to prescribe medication';
            }
        }

        // Validate dosage format
        if ( ! empty( $prescription_data['dosage'] ) ) {
            if ( ! preg_match( '/^\d+(\.\d+)?\s*(mg|g|ml|units?)$/i', $prescription_data['dosage'] ) ) {
                $errors[] = 'Invalid dosage format. Use format like "10 mg", "5.5 ml", etc.';
            }
        }

        // Validate frequency format
        if ( ! empty( $prescription_data['frequency'] ) ) {
            $valid_frequencies = array(
                'once daily', 'twice daily', 'three times daily', 'four times daily',
                'every 4 hours', 'every 6 hours', 'every 8 hours', 'every 12 hours',
                'as needed', 'before meals', 'after meals', 'at bedtime'
            );
            
            if ( ! in_array( strtolower( $prescription_data['frequency'] ), $valid_frequencies ) ) {
                $errors[] = 'Invalid frequency format';
            }
        }

        // Validate duration
        if ( ! empty( $prescription_data['duration_days'] ) ) {
            $duration = (int) $prescription_data['duration_days'];
            if ( $duration <= 0 || $duration > 365 ) {
                $errors[] = 'Duration must be between 1 and 365 days';
            }
        }

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

        return true;
    }

    /**
     * Check drug interactions
     *
     * @param array $prescription_data Prescription data
     * @return bool|WP_Error True if no interactions, WP_Error otherwise
     * @since 1.0.0
     */
    private static function check_drug_interactions( $prescription_data ) {
        $patient_id = $prescription_data['patient_id'];
        $new_medication = strtolower( $prescription_data['medication_name'] );

        // Get patient's current active prescriptions
        global $wpdb;
        $active_prescriptions = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT medication_name FROM {$wpdb->prefix}kc_prescriptions 
                 WHERE patient_id = %d AND status = %s",
                $patient_id, self::STATUS_ACTIVE
            ),
            ARRAY_A
        );

        $interactions = array();
        $warnings = array();

        // Check against current medications
        foreach ( $active_prescriptions as $prescription ) {
            $existing_medication = strtolower( $prescription['medication_name'] );
            
            // Check for known interactions (simplified example)
            $interaction = self::check_medication_interaction( $new_medication, $existing_medication );
            if ( $interaction ) {
                if ( $interaction['severity'] === 'major' ) {
                    $interactions[] = "Major interaction between {$new_medication} and {$existing_medication}: {$interaction['description']}";
                } else {
                    $warnings[] = "Minor interaction between {$new_medication} and {$existing_medication}: {$interaction['description']}";
                }
            }
        }

        // Check patient allergies
        $patient_allergies = self::get_patient_allergies( $patient_id );
        foreach ( $patient_allergies as $allergy ) {
            if ( stripos( $new_medication, $allergy ) !== false ) {
                $interactions[] = "Patient is allergic to {$allergy}";
            }
        }

        if ( ! empty( $interactions ) ) {
            return new \WP_Error(
                'drug_interaction_detected',
                'Drug interaction detected',
                array( 
                    'status' => 400,
                    'interactions' => $interactions,
                    'warnings' => $warnings
                )
            );
        }

        return true;
    }

    /**
     * Additional helper methods for prescription management
     */

    private static function setup_prescription_defaults( $prescription_id, $prescription_data ) {
        // Initialize prescription tracking
        self::initialize_prescription_tracking( $prescription_id );

        // Setup refill information
        if ( ! empty( $prescription_data['refills_allowed'] ) ) {
            self::setup_refill_tracking( $prescription_id, $prescription_data['refills_allowed'] );
        }

        // Create medication reminder if needed
        self::create_medication_reminder( $prescription_id );
    }

    private static function update_patient_medication_history( $prescription_id, $action ) {
        $prescription = Prescription::get_by_id( $prescription_id );
        $patient_id = $prescription['patient_id'];
        
        $medical_history = get_option( "kivicare_patient_{$patient_id}_medical_history", array() );
        
        if ( ! isset( $medical_history['medications'] ) ) {
            $medical_history['medications'] = array();
        }
        
        $medication_entry = array(
            'prescription_id' => $prescription_id,
            'medication_name' => $prescription['medication_name'],
            'dosage' => $prescription['dosage'],
            'frequency' => $prescription['frequency'],
            'action' => $action,
            'date' => current_time( 'Y-m-d' ),
            'doctor_id' => $prescription['doctor_id']
        );
        
        $medical_history['medications'][] = $medication_entry;
        
        update_option( "kivicare_patient_{$patient_id}_medical_history", $medical_history );
    }

    private static function check_patient_allergies( $prescription_id ) {
        $prescription = Prescription::get_by_id( $prescription_id );
        $patient_id = $prescription['patient_id'];
        
        $allergies = self::get_patient_allergies( $patient_id );
        $medication = strtolower( $prescription['medication_name'] );
        
        foreach ( $allergies as $allergy ) {
            if ( stripos( $medication, $allergy ) !== false ) {
                // Create allergy alert
                self::create_allergy_alert( $prescription_id, $allergy );
            }
        }
    }

    private static function handle_status_changes( $prescription_id, $current_prescription, $new_data ) {
        if ( isset( $new_data['status'] ) && $new_data['status'] != $current_prescription['status'] ) {
            $status_change = array(
                'prescription_id' => $prescription_id,
                'from_status' => $current_prescription['status'],
                'to_status' => $new_data['status'],
                'changed_by' => get_current_user_id(),
                'changed_at' => current_time( 'mysql' )
            );

            do_action( 'kivicare_prescription_status_changed', $status_change );
        }
    }

    private static function handle_medication_changes( $prescription_id, $current_prescription, $new_data ) {
        if ( $new_data['medication_name'] != $current_prescription['medication_name'] ) {
            // Log medication change
            $change_log = array(
                'prescription_id' => $prescription_id,
                'old_medication' => $current_prescription['medication_name'],
                'new_medication' => $new_data['medication_name'],
                'changed_by' => get_current_user_id(),
                'changed_at' => current_time( 'mysql' ),
                'reason' => $new_data['change_reason'] ?? 'Not specified'
            );

            do_action( 'kivicare_prescription_medication_changed', $change_log );
        }
    }

    private static function get_prescription_patient( $patient_id ) {
        global $wpdb;
        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT id, first_name, last_name, user_email, contact_no, dob FROM {$wpdb->prefix}kc_patients WHERE id = %d",
                $patient_id
            ),
            ARRAY_A
        );
    }

    private static function get_prescription_doctor( $doctor_id ) {
        global $wpdb;
        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT id, first_name, last_name, user_email, license_number, specialties FROM {$wpdb->prefix}kc_doctors WHERE id = %d",
                $doctor_id
            ),
            ARRAY_A
        );
    }

    private static function get_prescription_clinic( $clinic_id ) {
        if ( ! $clinic_id ) return null;
        
        global $wpdb;
        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT id, name, address, city, telephone_no FROM {$wpdb->prefix}kc_clinics WHERE id = %d",
                $clinic_id
            ),
            ARRAY_A
        );
    }

    private static function get_prescription_encounter( $encounter_id ) {
        if ( ! $encounter_id ) return null;
        
        global $wpdb;
        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT id, encounter_number, encounter_date, chief_complaint FROM {$wpdb->prefix}kc_encounters WHERE id = %d",
                $encounter_id
            ),
            ARRAY_A
        );
    }

    private static function get_medication_info( $medication_name ) {
        // This would typically connect to a medication database
        // For now, return basic info
        return array(
            'name' => $medication_name,
            'generic_name' => self::get_generic_name( $medication_name ),
            'drug_class' => self::get_drug_class( $medication_name ),
            'common_side_effects' => self::get_common_side_effects( $medication_name )
        );
    }

    private static function get_drug_interactions_for_patient( $patient_id, $medication_name ) {
        // Get patient's current medications and check interactions
        global $wpdb;
        $active_medications = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT medication_name FROM {$wpdb->prefix}kc_prescriptions 
                 WHERE patient_id = %d AND status = %s",
                $patient_id, self::STATUS_ACTIVE
            )
        );

        $interactions = array();
        foreach ( $active_medications as $med ) {
            $interaction = self::check_medication_interaction( $medication_name, $med );
            if ( $interaction ) {
                $interactions[] = $interaction;
            }
        }

        return $interactions;
    }

    private static function get_prescription_adherence( $prescription_id ) {
        // This would track patient adherence to medication
        return get_option( "kivicare_prescription_{$prescription_id}_adherence", array() );
    }

    private static function get_prescription_refills( $prescription_id ) {
        // Track prescription refills
        return get_option( "kivicare_prescription_{$prescription_id}_refills", array() );
    }

    private static function get_patient_allergies( $patient_id ) {
        $medical_history = get_option( "kivicare_patient_{$patient_id}_medical_history", array() );
        return isset( $medical_history['allergies'] ) ? $medical_history['allergies'] : array();
    }

    private static function check_medication_interaction( $med1, $med2 ) {
        // Simplified interaction checker - in real implementation, 
        // this would use a comprehensive drug interaction database
        $known_interactions = array(
            array(
                'drug1' => 'warfarin',
                'drug2' => 'aspirin',
                'severity' => 'major',
                'description' => 'Increased risk of bleeding'
            ),
            array(
                'drug1' => 'digoxin',
                'drug2' => 'furosemide',
                'severity' => 'moderate',
                'description' => 'May increase digoxin toxicity'
            )
        );

        foreach ( $known_interactions as $interaction ) {
            if ( ( stripos( $med1, $interaction['drug1'] ) !== false && stripos( $med2, $interaction['drug2'] ) !== false ) ||
                 ( stripos( $med1, $interaction['drug2'] ) !== false && stripos( $med2, $interaction['drug1'] ) !== false ) ) {
                return $interaction;
            }
        }

        return null;
    }

    // Placeholder methods for medication information
    private static function get_generic_name( $medication_name ) {
        // This would connect to a medication database
        return $medication_name;
    }

    private static function get_drug_class( $medication_name ) {
        // This would connect to a medication database
        return 'Unknown';
    }

    private static function get_common_side_effects( $medication_name ) {
        // This would connect to a medication database
        return array();
    }

    private static function initialize_prescription_tracking( $prescription_id ) {
        $tracking_data = array(
            'created_at' => current_time( 'mysql' ),
            'doses_taken' => 0,
            'doses_missed' => 0,
            'adherence_rate' => 0
        );

        update_option( "kivicare_prescription_{$prescription_id}_tracking", $tracking_data );
    }

    private static function setup_refill_tracking( $prescription_id, $refills_allowed ) {
        $refill_data = array(
            'refills_allowed' => $refills_allowed,
            'refills_used' => 0,
            'refills_remaining' => $refills_allowed,
            'refill_history' => array()
        );

        update_option( "kivicare_prescription_{$prescription_id}_refills", $refill_data );
    }

    private static function create_medication_reminder( $prescription_id ) {
        // This would create medication reminders for the patient
        // Implementation depends on reminder system
    }

    private static function create_allergy_alert( $prescription_id, $allergy ) {
        // Create an alert for allergy interaction
        $alert = array(
            'prescription_id' => $prescription_id,
            'allergy' => $allergy,
            'severity' => 'high',
            'message' => "Patient is allergic to {$allergy}",
            'created_at' => current_time( 'mysql' )
        );

        // Store alert
        $alerts = get_option( "kivicare_prescription_{$prescription_id}_alerts", array() );
        $alerts[] = $alert;
        update_option( "kivicare_prescription_{$prescription_id}_alerts", $alerts );

        // Notify doctor
        do_action( 'kivicare_allergy_alert_created', $alert );
    }

    private static function send_prescription_notifications( $prescription_id, $type ) {
        // Send notifications to patient, doctor, pharmacy, etc.
        do_action( "kivicare_send_prescription_{$type}_notification", $prescription_id );
    }

    /**
     * Event handlers
     */
    public static function on_prescription_created( $prescription_id, $prescription_data ) {
        error_log( "Care: New prescription created - ID: {$prescription_id}, Patient: " . ( $prescription_data['patient_id'] ?? 'Unknown' ) );
    }

    public static function on_prescription_updated( $prescription_id, $prescription_data ) {
        error_log( "Care: Prescription updated - ID: {$prescription_id}" );
        wp_cache_delete( "prescription_{$prescription_id}", 'kivicare' );
    }

    public static function on_prescription_cancelled( $prescription_id ) {
        error_log( "Care: Prescription cancelled - ID: {$prescription_id}" );
        wp_cache_delete( "prescription_{$prescription_id}", 'kivicare' );
    }

    public static function on_prescription_completed( $prescription_id ) {
        error_log( "Care: Prescription completed - ID: {$prescription_id}" );
        wp_cache_delete( "prescription_{$prescription_id}", 'kivicare' );
    }
}