<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Dental Order Management
 * Handles dental order creation, submission, and management
 */



// AJAX handler for order submission
add_action('wp_ajax_submit_dental_order', 'handle_dental_order_submission');
add_action('wp_ajax_nopriv_submit_dental_order', 'handle_dental_order_submission');

function handle_dental_order_submission() {

    
    // Verify nonce for security
    if (!wp_verify_nonce($_POST['nonce'], 'dental_order_submit')) {
        wp_die(json_encode([
            'success' => false,
            'message' => 'Security check failed'
        ], JSON_UNESCAPED_UNICODE));
    }
    
    // Check if user is logged in
    if (!is_user_logged_in()) {
        wp_die(json_encode([
            'success' => false,
            'message' => 'User not authenticated'
        ], JSON_UNESCAPED_UNICODE));
    }
    
    // Validate required fields
    $required_fields = ['service_type', 'patient_name'];
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            wp_die(json_encode([
                'success' => false,
                'message' => "Required field missing: {$field}"
            ], JSON_UNESCAPED_UNICODE));
        }
    }
    
    // Process order submission
    $result = process_dental_order_submission($_POST);
    
    if ($result['success']) {
        wp_die(json_encode([
            'success' => true,
            'data' => $result['data']
        ], JSON_UNESCAPED_UNICODE));
    } else {
        wp_die(json_encode([
            'success' => false,
            'message' => $result['message']
        ], JSON_UNESCAPED_UNICODE));
    }
}

/**
 * Process dental order submission with proper field mapping
 */
function process_dental_order_submission($data) {
    global $wpdb;
    
    try {
        // Generate dental order ID starting from 1001
        $dental_id = generate_dental_id();
        
        // Generate secret key (8 characters, lowercase + numbers)
        $secret_key = generate_secret_key();
        
        // Prepare order data with separate columns
        $order_data = [
            'dental_id' => $dental_id,
            'secret_key' => $secret_key,
            'dental_status' => 'pending',
            'patient_name' => sanitize_text_field($data['patient_name']),
            'author_id' => get_current_user_id(),
            'author_info' => json_encode(get_user_info(get_current_user_id()), JSON_UNESCAPED_UNICODE),
            'attachment_ids' => '', // Will be updated with file data
            'links' => '[]',
            'service_type' => sanitize_text_field($data['service_type']),
            'sub_services' => null,
            'extras' => null,
            'order_note' => sanitize_textarea_field($data['order_note'] ?? ''),
            'invoice_id' => '[]',
            'assignee' => '[]',
            'priority' => 'normal',
            'start_date' => null,
            'due_date' => null,
            'dental_parent' => null,
            'aligners' => '[]',
            'created_at' => current_time('mysql')
        ];
        
        // Handle sub-services (from 2nd step)
        if (!empty($data['sub_services'])) {
            // Clean the JSON string if it has escaped quotes
            $clean_json = stripslashes($data['sub_services']);
            $sub_services = json_decode($clean_json, true);
            
            // Check if patient_age values are accidentally included in sub_services
            $patient_age_values = ['child', 'teen', 'adult'];
            $filtered_sub_services = array_filter($sub_services, function($service) use ($patient_age_values) {
                return !in_array($service, $patient_age_values);
            });
            
            if (is_array($filtered_sub_services)) {
                // Sanitize each field name in the sub-services array
                $order_data['sub_services'] = json_encode(array_map('sanitize_text_field', $filtered_sub_services), JSON_UNESCAPED_UNICODE);
            }
        }
        
        // Handle removable services (extras)
        if (!empty($data['removable_services'])) {
            // Clean the JSON string if it has escaped quotes
            $clean_json = stripslashes($data['removable_services']);
            $removable_services = json_decode($clean_json, true);
            if (is_array($removable_services)) {
                $order_data['extras'] = json_encode(array_map('sanitize_text_field', $removable_services), JSON_UNESCAPED_UNICODE);
            }
        }
        
        // Insert into database
        $table_name = $wpdb->prefix . 'dentals';
        $result = $wpdb->insert($table_name, $order_data);
        
        if (!$result) {
            return [
                'success' => false,
                'message' => 'Failed to create order in database'
            ];
        }
        
        $dental_db_id = $wpdb->insert_id;
        
        // Process uploaded files
		if (!empty($data['attachments'])) {
			// Clean the JSON string if it has escaped quotes
			$clean_json = stripslashes($data['attachments']);
			$attachments = json_decode($clean_json, true);
            
            if (is_array($attachments) && !empty($attachments)) {
                // Extract attachment IDs from attachments
                $attachment_ids = array_column($attachments, 'attachment_id');
                
                // Update attachments to permanent status
                update_attachments_to_permanent($attachment_ids, $dental_db_id);
                
                // Update attachment IDs in the main dental table
                update_dental_attachment_ids($dental_db_id);
            }
        }
        
        // Store patient_age in custom meta
        if (!empty($data['patient_age'])) {
            update_dental_meta($dental_db_id, 'patient_age', $data['patient_age']);
        }

        return [
            'success' => true,
            'data' => [
                'dental_id' => $dental_id,
                'dental_db_id' => $dental_db_id,
                'secret_key' => $secret_key
            ]
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => 'Order processing error: ' . $e->getMessage()
        ];
    }
}

/**
 * Get user information for order
 */
function get_user_info($user_id) {
    $user = get_userdata($user_id);
    
    return [
        'name' => $user->first_name . ' ' . $user->last_name,
        'phone' => get_user_meta($user_id, 'user_phone', true),
        'address' => get_user_meta($user_id, 'user_address', true),
        'address_note' => get_user_meta($user_id, 'user_address_note', true),
        'geo_location' => get_user_meta($user_id, 'user_geo_location', true)
    ];
}

/**
 * Generate dental ID starting from 1001
 */
function generate_dental_id() {
    global $wpdb;
    
    // Get the highest existing dental_id
    $table_name = $wpdb->prefix . 'dentals';
    $highest_id = $wpdb->get_var("SELECT MAX(CAST(SUBSTRING(dental_id, 3) AS UNSIGNED)) FROM $table_name WHERE dental_id LIKE 'D-%'");
    
    // If no existing IDs, start from 1001, otherwise increment
    $next_id = $highest_id ? $highest_id + 1 : 1001;
    
    return 'D-' . $next_id;
}

/**
 * Generate secret key (8 characters, lowercase + numbers)
 */
function generate_secret_key() {
    $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $secret_key = '';
    
    for ($i = 0; $i < 8; $i++) {
        $secret_key .= $characters[rand(0, strlen($characters) - 1)];
    }
    
    return $secret_key;
}

/**
 * Get file information by ID
 */
function get_dental_file_info($attachment_id) {
    return get_dental_attachment_by_id($attachment_id);
}

/**
 * Get user dental orders with filtering, pagination, and sorting
 */
function get_user_dental_orders($user_id, $args = array()) {
    global $wpdb;
    
    // Default arguments
    $defaults = array(
        'limit' => 15,
        'offset' => 0,
        'search' => '',
        'service_types' => array(),
        'status' => '',
        // 'date_from' => '',
        // 'date_to' => '',
        'sort_by' => 'created_at',
        'sort_order' => 'DESC'
    );
    
    $args = wp_parse_args($args, $defaults);
    
    // Validate user ID
    if (!$user_id || !is_numeric($user_id)) {
        return array();
    }
    
    $table_name = $wpdb->prefix . 'dentals';
    
    // Build WHERE clause
    $where_conditions = array('author_id = %d');
    $where_values = array($user_id);
    
    // Search filter
    if (!empty($args['search']) && strlen($args['search']) >= 3) {
        $search_term = '%' . $wpdb->esc_like($args['search']) . '%';
        $where_conditions[] = '(patient_name LIKE %s OR dental_id LIKE %s)';
        $where_values[] = $search_term;
        $where_values[] = $search_term;
    }
    
    // Service type filter
    if (!empty($args['service_types'])) {
        $where_conditions[] = 'service_type = %s';
        $where_values[] = $args['service_types'];
    }
    
    // Status filter
    if (!empty($args['status'])) {
        $where_conditions[] = 'dental_status = %s';
        $where_values[] = $args['status'];
    }
    
    // Date filters (placeholder for future implementation)
    // ! Date filters are disabled for now
    // if (!empty($args['date_from'])) {
    //     $where_conditions[] = 'DATE(created_at) >= %s';
    //     $where_values[] = $args['date_from'];
    // }
    
    // if (!empty($args['date_to'])) {
    //     $where_conditions[] = 'DATE(created_at) <= %s';
    //     $where_values[] = $args['date_to'];
    // }
    
    // Build the complete WHERE clause
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
    
    // Validate sort parameters
    $allowed_sort_fields = array('dental_id', 'service_type', 'created_at');
    $sort_by = in_array($args['sort_by'], $allowed_sort_fields) ? $args['sort_by'] : 'created_at';
    $sort_order = strtoupper($args['sort_order']) === 'ASC' ? 'ASC' : 'DESC';
    

    
    // Build the complete query - only select needed fields
    $sql = $wpdb->prepare(
        "SELECT dental_id, patient_name, sub_services, created_at, dental_status, service_type, order_note 
         FROM $table_name 
         $where_clause 
         ORDER BY $sort_by $sort_order 
         LIMIT %d OFFSET %d",
        array_merge($where_values, array($args['limit'], $args['offset']))
    );
    

    
    $orders = $wpdb->get_results($sql);
    
    // Get total count for pagination
    $count_sql = $wpdb->prepare(
        "SELECT COUNT(*) FROM $table_name $where_clause",
        $where_values
    );
    $total_count = $wpdb->get_var($count_sql);
    
    // Process each order to format the data and remove unnecessary fields
    foreach ($orders as $order) {
        // Keep timestamp for JavaScript conversion to Jalali
        $order->timestamp = strtotime($order->created_at);
        $order->status_display = format_status_display($order->dental_status);
        
        // Translate service_type to Persian
        if (!empty($order->service_type)) {
            $order->service_type_display = etiuse_translate_value($order->service_type, 'service_type', $order->service_type);
        }
        
        // Translate sub_services to Persian
        if (!empty($order->sub_services)) {
            $translated_sub_services = etiuse_translate_values($order->sub_services, 'sub_services');
            $order->sub_services_display = $translated_sub_services;
        }
        
        // Remove unnecessary fields from the response
        unset($order->aligners);
        unset($order->assignee);
        unset($order->attachment_ids);
        unset($order->author_id);
        unset($order->due_date);
        unset($order->extras);
        unset($order->created_at);
        unset($order->links);
        unset($order->priority);
        unset($order->secret_key);
        unset($order->start_date);
        
        // Keep service_type and dental_status for internal use but don't send in response
        $order->status_class = $order->dental_status;
        // Keep service_type for display purposes
        unset($order->dental_status);
    }
    
    return array(
        'orders' => $orders,
        'total_count' => (int) $total_count,
        'has_more' => ($args['offset'] + $args['limit']) < $total_count
    );
}



/**
 * Format status display
 * Note: This function is now defined in helpers.php for centralized translation management
 * This is kept here for backward compatibility if needed
 */

/**
 * AJAX handler for getting user dental orders with filters
 */
add_action('wp_ajax_get_user_dental_orders', 'handle_get_user_dental_orders');



function handle_get_user_dental_orders() {
    // Verify nonce
    if (!wp_verify_nonce($_POST['nonce'], 'get_user_dental_orders')) {
        wp_die(json_encode(array(
            'success' => false,
            'message' => 'Security check failed'
        )));
    }
    
    // Check if user is logged in
    if (!is_user_logged_in()) {
        wp_die(json_encode(array(
            'success' => false,
            'message' => 'User not authenticated'
        )));
    }
    
    $user_id = get_current_user_id();
    
    // Get and validate parameters
    $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 15;
    $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
    $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
    $service_types = '';
    if (isset($_POST['service_types']) && !empty($_POST['service_types'])) {
        $service_types = sanitize_text_field($_POST['service_types']);
        
        // Ensure we only accept valid service types
        $valid_service_types = array('orthodontics', 'fixed_prosthesis', 'removable_prosthesis');
        if (!in_array($service_types, $valid_service_types)) {
            $service_types = '';
        }
    }
    $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : '';
    // ! Date filters are disabled for now
    // $date_from = isset($_POST['date_from']) ? sanitize_text_field($_POST['date_from']) : '';
    // $date_to = isset($_POST['date_to']) ? sanitize_text_field($_POST['date_to']) : '';
    $sort_by = isset($_POST['sort_by']) ? sanitize_text_field($_POST['sort_by']) : 'created_at';
    $sort_order = isset($_POST['sort_order']) ? sanitize_text_field($_POST['sort_order']) : 'DESC';
    
    // Validate limits
    $limit = max(1, min(50, $limit)); // Between 1 and 50
    $offset = max(0, $offset); // Non-negative
    
    // Build arguments array
    $args = array(
        'limit' => $limit,
        'offset' => $offset,
        'search' => $search,
        'service_types' => $service_types,
        'status' => $status,
        // 'date_from' => $date_from,
        // 'date_to' => $date_to,
        'sort_by' => $sort_by,
        'sort_order' => $sort_order
    );
    

    
    // Get orders
    $result = get_user_dental_orders($user_id, $args);
    
    if ($result === false) {
        // Return empty result instead of failing completely
        wp_die(json_encode(array(
            'success' => true,
            'data' => array(),
            'total_count' => 0,
            'has_more' => false,
            'filters_applied' => array(
                'search' => $search,
                'service_types' => $service_types,
                'status' => $status,
                // 'date_from' => $date_from,
                // 'date_to' => $date_to
            )
        )));
    }
    

    
    // Return success response
    wp_die(json_encode(array(
        'success' => true,
        'data' => $result['orders'],
        'total_count' => $result['total_count'],
        'has_more' => $result['has_more'],
        'filters_applied' => array(
            'search' => $search,
            'service_types' => $service_types,
            'status' => $status,
            // 'date_from' => $date_from,
            // 'date_to' => $date_to
        )
    )));
}
