<?php
if (!defined('ABSPATH')) exit;

class DevsAccounting_Order_Status {
    public function __construct() {
        add_action('rest_api_init', [$this, 'order_status_api_endpoint']);
        add_action('init', [$this, 'register_custom_order_statuses'], 20);
        add_filter('wc_order_statuses', [$this, 'add_custom_statuses_to_order_list']);
        add_filter('woocommerce_valid_order_statuses_for_order_counts', [$this, 'add_custom_statuses_to_order_counts']);
        add_action('admin_head', [$this, 'add_order_status_colors_css']);
    }

    public function order_status_api_endpoint() {
        register_rest_route('devs-accounting/v1', '/order-statuses', array(
            'methods' => 'GET',
            'callback' => [$this, 'get_order_statuses'],
            'permission_callback' => function () {
                return true;
            },
        ));

        register_rest_route('devs-accounting/v1', '/add-order-status', array(
            'methods' => 'POST',
            'callback' => [$this, 'save_order_status_data'],
            'permission_callback' => [$this, 'verify_nonce'],
        ));

        register_rest_route('devs-accounting/v1', '/delete-order-status/(?P<id>\d+)', array(
            'methods' => 'DELETE',
            'callback' => [$this, 'delete_order_status'],
            'permission_callback' => [$this, 'verify_nonce'],
        ));
    }

    public function verify_nonce($request) {
        $nonce = $request->get_header('X-WP-Nonce');
        if (!wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error('rest_forbidden', esc_html__('Invalid nonce.', 'devs-accounting'), array('status' => 403));
        }
        return true;
    }

    public function get_order_statuses() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_order_statuses';
        $results = $wpdb->get_results("SELECT * FROM $table_name WHERE deleted_at IS NULL ORDER BY created_at DESC");
        return rest_ensure_response($results);
    }

    public function save_order_status_data($request) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_order_statuses';

        $name = sanitize_text_field($request['name']);
        $slug = sanitize_title($name);
        $slug = substr($slug, 0, 17); // Limit to 17 chars to fit 'wc-' + slug in 20 char DB column
        $slug = rtrim($slug, '-');    // Remove trailing dash if truncation cut a word
        $color = sanitize_text_field($request['color'] ?? '#000000');
        $id = isset($request['id']) ? intval($request['id']) : 0;

        if (empty($name)) {
            return new WP_REST_Response(['message' => __('Name is required', 'devs-accounting')], 400);
        }

        // Check for unique slug
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $table_name WHERE slug = %s AND deleted_at IS NULL AND id != %d",
            $slug,
            $id
        ));

        if ($existing) {
            return new WP_REST_Response([
                'message' => __('Status with this name/slug already exists', 'devs-accounting'),
                'errors' => ['name' => __('This status already exists.', 'devs-accounting')]
            ], 400);
        }

        $data = [
            'name' => $name,
            'slug' => $slug,
            'color' => $color,
        ];

        if ($id > 0) {
            $wpdb->update($table_name, $data, ['id' => $id]);
            $response = ['message' => __('Order status updated successfully', 'devs-accounting'), 'id' => $id];
        } else {
            $wpdb->insert($table_name, $data);
            $response = ['message' => __('Order status created successfully', 'devs-accounting'), 'id' => $wpdb->insert_id];
        }

        return new WP_REST_Response($response, 200);
    }

    public function delete_order_status($request) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_order_statuses';
        $id = intval($request['id']);

        $wpdb->update($table_name, ['deleted_at' => current_time('mysql')], ['id' => $id]);

        return new WP_REST_Response(['message' => __('Order status deleted successfully', 'devs-accounting')], 200);
    }

    public function register_custom_order_statuses() {
        if (!class_exists('WooCommerce')) return;

        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_order_statuses';
        
        // Check if table exists to avoid errors during installation
        if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) return;

        $statuses = $wpdb->get_results("SELECT * FROM $table_name WHERE deleted_at IS NULL");

        foreach ($statuses as $status) {
            register_post_status('wc-' . $status->slug, array(
                'label'                     => $status->name,
                'public'                    => false,
                'exclude_from_search'       => false,
                'show_in_admin_all_list'    => true,
                'show_in_admin_status_list' => true,
                'label_count'               => _n_noop($status->name . ' <span class="count">(%s)</span>', $status->name . ' <span class="count">(%s)</span>')
            ));
        }
    }

    public function add_custom_statuses_to_order_list($order_statuses) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_order_statuses';

        if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) return $order_statuses;

        $statuses = $wpdb->get_results("SELECT * FROM $table_name WHERE deleted_at IS NULL");

        foreach ($statuses as $status) {
            $order_statuses['wc-' . $status->slug] = $status->name;
        }

        return $order_statuses;
    }

    public function add_custom_statuses_to_order_counts($statuses) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_order_statuses';

        if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) return $statuses;

        $results = $wpdb->get_results("SELECT slug FROM $table_name WHERE deleted_at IS NULL");

        foreach ($results as $status) {
            $statuses[] = 'wc-' . $status->slug;
        }

        return $statuses;
    }

    // public function add_order_status_colors_css() {
    //     global $wpdb;
    //     $table_name = $wpdb->prefix . 'dac_order_statuses';

    //     if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) return;

    //     $statuses = $wpdb->get_results("SELECT * FROM $table_name WHERE deleted_at IS NULL");

    //     if (empty($statuses)) return;

    //     echo '<style type="text/css">';
    //     foreach ($statuses as $status) {
    //         $slug = sanitize_html_class($status->slug);
    //         $color = esc_attr($status->color);
            
    //         // Comprehensive selectors for all possible WooCommerce table structures
    //         $selectors = [
    //             "mark.status-wc-$slug",
    //             ".column-order_status mark.status-wc-$slug",
    //             ".woocommerce-orders-table__cell-order_status mark.status-wc-$slug",
    //             "mark[class*='status-wc-$slug']",
    //             "mark[class*='status-$slug']",
    //             "mark.$slug",
    //             ".status-wc-$slug",
    //             ".wc-status-$slug"
    //         ];
            
    //         $sel = implode(', ', $selectors);
            
    //         echo "
    //             $sel { 
    //                 background-color: $color !important; 
    //                 background: $color !important; 
    //                 color: #fff !important; 
    //             }
    //             $sel::after, $sel span { 
    //                 color: #fff !important; 
    //             }
    //         ";
    //     }
    //     echo '</style>';
    // }
    public function add_order_status_colors_css()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_order_statuses';

        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) !== $table_name) {
            return;
        }

        $statuses = $wpdb->get_results("SELECT * FROM $table_name WHERE deleted_at IS NULL");

        if (empty($statuses)) {
            return;
        }

        $custom_css = '';
        foreach ($statuses as $status) {
            $slug = sanitize_html_class($status->slug);
            $color = esc_attr($status->color);

            $selectors = [
                "mark.status-wc-$slug",
                ".column-order_status mark.status-wc-$slug",
                ".woocommerce-orders-table__cell-order_status mark.status-wc-$slug",
                "mark[class*='status-wc-$slug']",
                "mark[class*='status-$slug']",
                "mark.$slug",
                ".status-wc-$slug",
                ".wc-status-$slug"
            ];

            $sel = implode(', ', $selectors);

            $custom_css .= "
            $sel { 
                background-color: $color !important; 
                background: $color !important; 
                color: #fff !important; 
            }
            $sel::after, $sel span { 
                color: #fff !important; 
            }
        ";
        }

        if (!empty($custom_css)) {
            echo '<style type="text/css">' . wp_kses($custom_css, array()) . '</style>';
        }
    }
}

new DevsAccounting_Order_Status();
