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

if (!class_exists('DevsAccounting_Wc')) {
   class DevsAccounting_Wc {
      public $posts_table;
      public $product_meta;
      public $postmetaTable;
      public $termRelationship;
      public $termtaxonomy;

      function __construct() {
         global $wpdb;
         $this->posts_table = $wpdb->prefix . 'posts';
         $this->product_meta = $wpdb->prefix . 'wc_product_meta_lookup';
         $this->postmetaTable = $wpdb->prefix . 'postmeta';
         $this->termRelationship = $wpdb->prefix . 'term_relationships';
         $this->termtaxonomy = $wpdb->prefix . 'term_taxonomy';
      }

      private function is_woocommerce_active() {
         return class_exists('WooCommerce') && function_exists('wc_get_product');
      }

      public function save_wc_product($item_id, $variant_id, $quantity_change) {
         if (!$this->is_woocommerce_active()) return [];

         $product = wc_get_product($item_id);
         if ($product && $product->get_type() === 'simple') {
            $current_stock = $product->get_stock_quantity();
            $new_stock = $current_stock - $quantity_change;
            $product->set_stock_quantity($new_stock);
            $product->save();
         } elseif ($product && $product->get_type() === 'variable') {
            if ($variant_id) {
               $variation = new WC_Product_Variation($variant_id);
               $current_stock = $variation->get_stock_quantity();
               $new_stock = $current_stock + $quantity_change;
               $variation->set_stock_quantity($new_stock);
               $variation->save();
            }
         }
      }

      public function get_wc_all_product() {
         if (!$this->is_woocommerce_active()) return [];

         global $wpdb;

         $posts_results = $wpdb->get_results(
            $wpdb->prepare(
               "SELECT p.ID AS id, 
                       p.post_title AS name, 
                       p.post_content AS description, 
                       p.post_date AS created_at, 
                       pm.max_price AS sale_price,
                       p.guid AS image,
                       p.post_type AS type
                FROM $this->posts_table p
                LEFT JOIN $this->product_meta pm ON p.ID = pm.product_id
                LEFT JOIN $this->postmetaTable pm2 ON p.ID = pm2.post_id AND pm2.meta_key = '_thumbnail_id'
                LEFT JOIN $this->posts_table p2 ON p2.ID = pm2.meta_value
                WHERE p.post_type = %s AND p.post_status = %s",
               'product', 
               'publish'
            ),
            ARRAY_A
         );

         return $posts_results;
      }

      public function get_wc_single_product($product_id) {
         if (!$this->is_woocommerce_active()) return [];

         global $wpdb;
         $item = $wpdb->get_row($wpdb->prepare(
            "SELECT 
               p.post_title AS name, 
               p.post_content AS description,
               p2.guid AS image, 
               pm2.meta_value AS thumbnail_id,
               pm3.meta_value AS purchase_price,
               pm4.meta_value AS sale_price,
               pm5.meta_value AS stock_limit,
               pm.sku AS sku,
               p4.term_id AS category_id
            FROM $this->posts_table p
            LEFT JOIN $this->product_meta pm ON p.ID = pm.product_id
            LEFT JOIN $this->postmetaTable pm2 ON p.ID = pm2.post_id AND pm2.meta_key = '_thumbnail_id'
            LEFT JOIN $this->postmetaTable pm3 ON p.ID = pm3.post_id AND pm3.meta_key = '_regular_price'
            LEFT JOIN $this->postmetaTable pm4 ON p.ID = pm4.post_id AND pm4.meta_key = '_sale_price'
            LEFT JOIN $this->postmetaTable pm5 ON p.ID = pm5.post_id AND pm5.meta_key = '_stock'
            LEFT JOIN $this->posts_table p2 ON p2.ID = pm2.meta_value
            LEFT JOIN $this->termRelationship p3 ON p.ID = p3.object_id
            INNER JOIN $this->termtaxonomy p4 ON p3.term_taxonomy_id = p4.term_taxonomy_id AND p4.taxonomy = 'product_cat'
            WHERE p.ID = %d",
            $product_id
         ));

         return $item;
      }

      public function update_wc_single_product($post_id, $post_input, $purchase_price, $sale_price, $stock_limit, $sku) {
         if (!$this->is_woocommerce_active()) return [];

         global $wpdb;
         $post_id = intval($post_id);

         $wpdb->update($this->posts_table, $post_input, ['ID' => $post_id]);

         update_post_meta($post_id, '_regular_price', $purchase_price);
         update_post_meta($post_id, '_sale_price', $sale_price);
         update_post_meta($post_id, '_stock', $stock_limit);

         $wpdb->update($this->product_meta, ['sku' => $sku], ['product_id' => $post_id]);
         $wpdb->update($this->product_meta, ['min_price' => $purchase_price], ['product_id' => $post_id]);
         $wpdb->update($this->product_meta, ['max_price' => $sale_price], ['product_id' => $post_id]);
      }

      public function update_wc_inventory_single_product($item_id, $in_out_qty) {
         if (!$this->is_woocommerce_active()) {
            return new WP_Error('woocommerce_inactive', __('WooCommerce is not active.', 'devs-accounting'), ['status' => 400]);
         }

         global $wpdb;

         $current_stock = get_post_meta($item_id, '_stock', true);
         $new_stock = $current_stock + $in_out_qty;

         if ($new_stock < 0) {
            return new WP_Error('negative_stock', __('Stock cannot be negative.', 'devs-accounting'), ['status' => 400]);
         }

         $update_stock = update_post_meta($item_id, '_stock', $new_stock);
         if ($update_stock === false) {
            return new WP_Error('stock_update_failed', __('Failed to update stock in postmeta.', 'devs-accounting'), ['status' => 500]);
         }

         $update_stock_quantity = $wpdb->update(
            $this->product_meta,
            ['stock_quantity' => $new_stock],
            ['product_id' => $item_id]
         );
         
         if ($update_stock_quantity === false) {
            return new WP_Error('stock_update_failed_wc_meta', __('Failed to update stock in wc_product_meta_lookup.', 'devs-accounting'), ['status' => 500]);
         }
      }

      public function get_wc_all_orders() {
         if (!$this->is_woocommerce_active()) return [];

         $orders = wc_get_orders([
            'limit' => -1, 
            'status' => 'any',
         ]);

         $formatted_invoices = [];

         foreach ($orders as $order) {
            $item_data = [];
            foreach ($order->get_items() as $item) {
               $product = $item->get_product();
               $item_data[] = [
                  'id' => $item->get_id(),
                  'name' => $item->get_name(),
                  'description' => $item->get_meta('description', true),
                  'created_at' => $product ? $product->get_date_created()->date('Y-m-d H:i:s') : null,
                  'sale_price' => $product ? $product->get_sale_price() : null,
                  'image' => $product ? wp_get_attachment_url($product->get_image_id()) : null,
                  'type' => $product ? $product->get_type() : 'product',
                  'quantity' => $item->get_quantity(),
               ];
            }

            $formatted_invoices[] = [
               'id' => $order->get_id(),
               'type' => 'invoice', 
               'invoice_no' => $order->get_meta('_invoice_number', true),
               'order_no' => $order->get_order_number(),
               'status' => $order->get_status(),
               'issued_at' => $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i:s') : null,
               'due_at' => null,
               'amount' => $order->get_total(),
               'discount' => $order->get_discount_total(),
               'currency_code' => $order->get_currency(),
               'currency_rate' => null,
               'category_id' => null,
               'contact_id' => null,
               'contact_name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
               'contact_email' => null,
               'contact_tax_number' => null,
               'contact_phone' => null,
               'contact_address' => null,
               'uuid' => null,
               'notes' => null,
               'footer' => null,
               'parent_id' => null,
               'share_code' => null,
               'deleted_at' => null,
               'created_at' => $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i:s') : null,
               'updated_at' => $order->get_date_modified() ? $order->get_date_modified()->date('Y-m-d H:i:s') : null,
               'item_data' => json_encode($item_data),
            ];
         }

         return $formatted_invoices;
      }

      public function get_wc_order($order_id) {
         if (!$this->is_woocommerce_active()) return null;

         $order = wc_get_order($order_id);
         if (!$order) return null;

         $item_data = [];
         foreach ($order->get_items() as $item_id => $item) {
            $product = $item->get_product();
            $meta_display = [];
            foreach ($item->get_formatted_meta_data() as $meta) {
                $meta_display[] = $meta->display_key . ': ' . $meta->display_value;
            }

            $item_data[] = [
               'id' => $product ? $product->get_id() : $item->get_id(),
               'name' => $item->get_name(),
               'meta' => implode(', ', $meta_display),
               'description' => $item->get_meta('description', true),
               'created_at' => ($product && $product->get_date_created()) ? $product->get_date_created()->date('Y-m-d H:i:s') : null,
               'sale_price' => $item->get_subtotal() / $item->get_quantity(),
               'image' => $product ? wp_get_attachment_url($product->get_image_id()) : null,
               'type' => $product ? $product->get_type() : 'product',
               'quantity' => $item->get_quantity(),
               'total' => $item->get_total(),
            ];
         }

         return [
            'id' => $order->get_id(),
            'type' => 'invoice', 
            'invoice_no' => $order->get_meta('_invoice_number', true),
            'order_no' => $order->get_order_number(),
            'status' => $order->get_status(),
            'issued_at' => $order->get_date_created() ? $order->get_date_created()->date('F j, Y') : null,
            'amount' => $order->get_total(),
            'subtotal' => $order->get_subtotal(),
            'discount' => $order->get_discount_total(),
            'shipping_total' => $order->get_shipping_total(),
            'shipping_method' => $order->get_shipping_method(),
            'payment_method' => $order->get_payment_method_title(),
            'currency_code' => $order->get_currency(),
            'contact_name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
            'contact_email' => $order->get_billing_email(),
            'contact_phone' => $order->get_billing_phone(),
            'contact_address' => implode("\n", array_filter([
                $order->get_billing_address_1(),
                $order->get_billing_address_2(),
                $order->get_billing_city(),
                $order->get_billing_state(),
                $order->get_billing_postcode(),
                $order->get_billing_country()
            ])),
            'notes' => $order->get_customer_note(),
            'item_data' => json_encode($item_data),
         ];
      }
   }
}
