<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

require_once(plugin_dir_path(__FILE__) . '../vendor/autoload.php');
use Stripe\Stripe;
use Stripe\PaymentIntent;

class DevsAccounting_Invoice{
    public function __construct()
    {
        add_action('rest_api_init', [$this, 'invoice_api_endpoint']);
    }

    // Define your custom endpoint
    public function invoice_api_endpoint() {
        register_rest_route('devs-accounting/v1', '/add-invoice', array(
            'methods' => 'POST',
            'callback' => [$this, 'save_invoice_data'],
            'permission_callback' => [$this, 'verify_invoice_nonce'],
        ));
        
        register_rest_route('devs-accounting/v1', '/update-invoice/(?P<id>\d+)', array(
            'methods' => 'POST', 
            'callback' => [$this, 'update_invoice_data'],
            'permission_callback' => [$this, 'verify_invoice_nonce'],
        ));

        register_rest_route('devs-accounting/v1', '/send-mail/(?P<id>\d+)', array(
            'methods' => 'get', 
            'callback' => [$this, 'send_invoice_email'],
            'permission_callback' => function () {
                return true;
            },
        ));

        register_rest_route('devs-accounting/v1', '/invoices', array(
            'methods' => 'get', 
            'callback' => [$this, 'get_invoices'],
            'permission_callback' => function () {
                return true;
            },
        ));
        
        register_rest_route('devs-accounting/v1', '/show-invoice/(?P<id>\d+)', array(
            'methods' => 'get', 
            'callback' => [$this, 'get_single_invoice'],
            'permission_callback' => function () {
                return true;
            },
        ));        
        
        register_rest_route('devs-accounting/v1', '/delete-invoice/(?P<id>\d+)', array(
            'methods' => 'get', 
            'callback' => [$this, 'delete_single_invoice'],
            'permission_callback' => [$this, 'verify_invoice_nonce'],
        ));

        register_rest_route('devs-accounting/v1', '/create-payment-intent', [
            'methods' => 'POST',
            'callback' => 'create_payment_intent',
            'permission_callback' => '__return_true'
        ]);

        register_rest_route('devs-accounting/v1', '/get_invoice', [
            'methods' => 'GET',
            'callback' => [$this, 'get_invoice_type'],
            'permission_callback' => '__return_true'
        ]);

        register_rest_route('devs-accounting/v1', '/user-stats', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_user_stats'],
            'permission_callback' => [$this, 'verify_invoice_nonce'],
        ]);

    }

    function verify_invoice_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_invoices($request) {
        global $wpdb;
    
        $table_name_invoices = $wpdb->prefix . 'dac_invoices';
        $table_name_invoice_items = $wpdb->prefix . 'dac_invoice_items';
        $table_name_contacts = $wpdb->prefix . 'dac_contacts';
        $search = isset($request['search']) ? sanitize_text_field($request['search']) : '';
        $count = isset($request['count']) ? $request['count'] : false;
    
        // Count invoices
        if ($count) {
            $min_id = isset($request['min_id']) ? intval($request['min_id']) : 0;
            $latest = isset($request['latest']) ? boolval($request['latest']) : false;

            $select = $latest ? "MAX(id)" : "COUNT(*)";
            $query = "SELECT {$select} FROM $table_name_invoices WHERE deleted_at IS NULL";
            $prepare_args = [];

            if ($min_id > 0) {
                $query .= " AND id > %d";
                $prepare_args[] = $min_id;
            }

            if (!empty($search)) {
                $query .= " AND (invoice_no LIKE %s OR name LIKE %s OR email LIKE %s)";
                $prepare_args[] = "%$search%";
                $prepare_args[] = "%$search%";
                $prepare_args[] = "%$search%";
            }

            if (!empty($prepare_args)) {
                $query = $wpdb->prepare($query, ...$prepare_args);
            }

            return rest_ensure_response($wpdb->get_var($query));
        }
    
        // Fetch invoices
        $query = "
            SELECT invoices.*, 
                   invoice_items.invoice_items_data AS item_data, 
                   contacts.name AS contact_name, 
                   contacts.email AS contact_email
            FROM $table_name_invoices AS invoices
            INNER JOIN $table_name_contacts AS contacts 
                ON invoices.contact_id = contacts.id
            INNER JOIN $table_name_invoice_items AS invoice_items 
                ON invoices.id = invoice_items.invoice_no
            WHERE invoices.deleted_at IS NULL
        ";
    
        // Add search conditions
        if (!empty($search)) {
            $query .= " AND (invoices.invoice_no LIKE %s OR contacts.name LIKE %s OR contacts.email LIKE %s)";
            $prepared_query = $wpdb->prepare($query, "%$search%", "%$search%", "%$search%");
        } else {
            $prepared_query = $query . " ORDER BY invoices.id DESC";
        }
    
        $results = $wpdb->get_results($prepared_query);
    
 
        $settings = get_option('devsaccounting_settings');
        $settings = json_decode($settings);
    
  
        if ($settings && isset($settings->ordersync) && $settings->ordersync == 1 && class_exists('DevsAccounting_Wc')) {
            $formatted_invoices = (new DevsAccounting_Wc)->get_wc_all_orders();
            $merged_results = array_merge($formatted_invoices, $results);
        } else {
            $merged_results = $results;
        }
    
        return rest_ensure_response($merged_results);
    }
    
	public function get_invoice_type($request) 
	{
		global $wpdb;

		// Escape table names
		$table_name_invoices = esc_sql($wpdb->prefix . 'dac_invoices');
		$table_name_invoice_items = esc_sql($wpdb->prefix . 'dac_invoice_items');
		$table_name_contacts = esc_sql($wpdb->prefix . 'dac_contacts');

		// Sanitize input
		$invoice_type = isset($request['type']) ? sanitize_text_field($request['type']) : '';
		$search = isset($request['search']) ? sanitize_text_field($request['search']) : '';

		if (empty($invoice_type)) {
			return new WP_Error('missing_type', esc_html__('Invoice type is required', 'devs-accounting'), ['status' => 400]);
		}

		// Base query with placeholders
		$query = "
			SELECT invoices.*, 
				   invoice_items.invoice_items_data AS item_data, 
				   contacts.name AS contact_name, 
				   contacts.email AS contact_email
			FROM {$table_name_invoices} AS invoices
			INNER JOIN {$table_name_contacts} AS contacts 
				ON invoices.contact_id = contacts.id
			INNER JOIN {$table_name_invoice_items} AS invoice_items 
				ON invoices.id = invoice_items.invoice_no
			WHERE invoices.deleted_at IS NULL
			AND invoices.type = %s
		";

		// Prepare arguments
		$prepare_args = [$invoice_type];

		if (!empty($search)) {
			$query .= " AND (invoices.invoice_no LIKE %s OR contacts.name LIKE %s OR contacts.email LIKE %s)";
			$like = '%' . $wpdb->esc_like($search) . '%';
			$prepare_args[] = $like;
			$prepare_args[] = $like;
			$prepare_args[] = $like;
		}

		$query .= " ORDER BY invoices.id DESC";

		// Prepare and execute query safely
		$prepared_query = $wpdb->prepare($query, ...$prepare_args);
		$results = $wpdb->get_results($prepared_query, ARRAY_A);

		// Ensure results are arrays
		$results = $results ?? [];

		// Optionally merge WooCommerce orders if enabled
		$settings = get_option('devsaccounting_settings');
		$settings = json_decode($settings);

		if ($settings && isset($settings->ordersync) && $settings->ordersync == 1 && class_exists('DevsAccounting_Wc')) {
			$formatted_invoices = (new DevsAccounting_Wc)->get_wc_all_orders() ?? [];
			$merged_results = array_merge($formatted_invoices, $results);
		} else {
			$merged_results = $results;
		}

		// Optional: sanitize output before sending to REST
		foreach ($merged_results as &$invoice) {
			$invoice = array_map('wp_kses_post', $invoice);
		}

		return rest_ensure_response($merged_results);
	}


    public function get_user_stats($request) {
        global $wpdb;
    
        $user_email = isset($request['user_email']) ? sanitize_email($request['user_email']) : '';
        if (empty($user_email) || !is_email($user_email)) {
            return new WP_Error('invalid_user_email', esc_html__('User email must be valid.', 'devs-accounting'), ['status' => 400]);
        }
    
        $user = get_user_by('email', $user_email);
        if (!$user) {
            return new WP_Error('user_not_found', esc_html__('User not found.', 'devs-accounting'), ['status' => 404]);
        }
    
        $table_invoices     = $wpdb->prefix . 'dac_invoices';
        $table_transactions = $wpdb->prefix . 'dac_transactions';
        $table_contacts     = $wpdb->prefix . 'dac_contacts';
    
        // Look up contact_id by email
        $contact_id = (int) $wpdb->get_var(
            $wpdb->prepare("SELECT id FROM {$table_contacts} WHERE email = %s LIMIT 1", $user_email)
        );
    
        if ($contact_id <= 0) {
            return new WP_Error('contact_not_found', esc_html__('Contact not found for this email.', 'devs-accounting'), ['status' => 404]);
        }
    
        // Totals (exclude soft-deleted)
        $invoice_count = (int) $wpdb->get_var(
            $wpdb->prepare("SELECT COUNT(*) FROM {$table_invoices} WHERE contact_id = %d AND deleted_at IS NULL", $contact_id)
        );
    
        $total_paid = (float) $wpdb->get_var(
            $wpdb->prepare("
                SELECT COALESCE(SUM(t.amount), 0)
                FROM {$table_transactions} t
                INNER JOIN {$table_invoices} i ON i.id = t.document_id
                WHERE i.contact_id = %d
                  AND i.deleted_at IS NULL
            ", $contact_id)
        );
    
        $total_invoiced = (float) $wpdb->get_var(
            $wpdb->prepare("
                SELECT COALESCE(SUM(amount - discount), 0)
                FROM {$table_invoices}
                WHERE contact_id = %d AND deleted_at IS NULL
            ", $contact_id)
        );
    
        // Status breakdown (exclude soft-deleted)
        $status_rows = $wpdb->get_results(
            $wpdb->prepare("
                SELECT status, COUNT(*) as cnt
                FROM {$table_invoices}
                WHERE contact_id = %d AND deleted_at IS NULL
                GROUP BY status
            ", $contact_id),
            ARRAY_A
        );
    
        $status_counts = [
            'paid'    => 0,
            'draft'   => 0,
            'partial' => 0,
            'overdue' => 0,
            'other'   => 0,
        ];
    
        if ($status_rows) {
            foreach ($status_rows as $row) {
                $status = strtolower((string) $row['status']);
                $cnt    = (int) $row['cnt'];
                if (isset($status_counts[$status])) {
                    $status_counts[$status] += $cnt;
                } else {
                    $status_counts['other'] += $cnt;
                }
            }
        }
    
        $dues = max($total_invoiced - $total_paid, 0);
    
        $stats = [
            'user_email'     => $user_email,
            'contact_id'     => $contact_id,
            'invoice_count'  => $invoice_count,
            'total_invoiced' => $total_invoiced,
            'total_paid'     => $total_paid,
            'dues'           => $dues,
            'status_counts'  => $status_counts,
        ];
    
        return rest_ensure_response($stats);
    }
    
    


    // public function get_single_invoice($request) {
    //     global $wpdb;
    
    //     $table_name_invoices = $wpdb->prefix . 'dac_invoices';
    //     $table_name_invoice_items = $wpdb->prefix . 'dac_invoice_items';
    //     $table_name_contacts = $wpdb->prefix . 'dac_contacts';
    
       
    //     $id = intval($request['id']);

    //     if ($id) {
    //         $invoice = $wpdb->get_row($wpdb->prepare(
    //             "SELECT invoices.*, invoice_items.invoice_items_data AS item_data, contacts.name AS contact_name, contacts.email AS contact_email
    //              FROM $table_name_invoices AS invoices 
    //              INNER JOIN $table_name_contacts AS contacts 
    //              ON invoices.contact_id = contacts.id 
    //              INNER JOIN $table_name_invoice_items AS invoice_items 
    //              ON invoices.id = invoice_items.invoice_no   
    //              WHERE invoices.ID = %d",
    //             $id
    //         ));
    
    //         if ($invoice) {
    //             return rest_ensure_response($invoice);
    //         }
    //     }
        
    // }
    
    
    
    public function get_single_invoice($request) {
    global $wpdb;

    $table_invoices      = esc_sql($wpdb->prefix . 'dac_invoices');
    $table_invoice_items = esc_sql($wpdb->prefix . 'dac_invoice_items');
    $table_contacts      = esc_sql($wpdb->prefix . 'dac_contacts');

    $id = isset($request['id']) ?? intval($request['id']);

    if ($id > 0) {
        $query = "
            SELECT invoices.*, 
                   invoice_items.invoice_items_data AS item_data, 
                   contacts.name AS contact_name, 
                   contacts.email AS contact_email
            FROM {$table_invoices} AS invoices 
            INNER JOIN {$table_contacts} AS contacts 
                ON invoices.contact_id = contacts.id 
            INNER JOIN {$table_invoice_items} AS invoice_items 
                ON invoices.id = invoice_items.invoice_no   
            WHERE invoices.ID = %d
        ";

        $invoice = $wpdb->get_row($wpdb->prepare($query, $id));

        if ($invoice) {
            return rest_ensure_response($invoice);
        }
    }

    return new WP_Error('no_invoice', esc_html__('Invoice not found', 'devs-accounting'), ['status' => 404]);
}
    public function delete_single_invoice($request) 
    {
        global $wpdb;
    
        $table_name = $wpdb->prefix . 'dac_invoices';
    
        $invoice_id = isset($request['id']) ? intval($request['id']) : 0;
    
        if ($invoice_id <= 0) {
            return new WP_Error( 'invalid_item_id', esc_html__( 'Invalid item ID', 'devs-accounting' ), array( 'status' => 400 ) );
        }
    
        $existing_invoice = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM $table_name WHERE ID = %d",
                $invoice_id
            )
        );
    
        if (!$existing_invoice) {
            return new WP_Error( 'item_not_found', esc_html__( 'Item not found', 'devs-accounting' ), array( 'status' => 404 ) );
        }
    
        
        $current_time = gmdate('Y-m-d H:i:s'); 

        $result = $wpdb->update(
            $table_name,
            array( 
                'deleted_at' => $current_time,
                ),
            array( 'id' => $invoice_id ),
        );
    
        if ($result === false) {
            return new WP_Error( 'soft_delete_failed', esc_html__( 'Failed to soft delete invoice', 'devs-accounting' ), array( 'status' => 500 ) );
        }
    
        return rest_ensure_response( array( 'message' => esc_html__('Invoice soft deleted successfully', 'devs-accounting')) );
    }
    

    public function save_invoice_data($request) {
        global $wpdb;
        $table_name_invoice = $wpdb->prefix . 'dac_invoices';
        $table_name_invoice_items = $wpdb->prefix . 'dac_invoice_items';
        $table_name_inventory = $wpdb->prefix . 'dac_inventories';

        $errors = array();

        if (!isset($request['type'])) {
            $errors['type'] = esc_html__('Type is required.', 'devs-accounting');
        } else {
            $type = $request['type'];
        }
        if (!isset($request['contact_id']) || $request['contact_id'] <= 0) {
            $errors['contact_id'] = esc_html__('Contact ID must be a positive integer.', 'devs-accounting');
        } else {
            $contact_id = intval($request['contact_id']);
        }

        if (empty($request['invoice_no'])) {
            $errors['invoice_no'] = esc_html__('Invoice number is required.', 'devs-accounting');
        } else {
            $invoice_no = sanitize_text_field($request['invoice_no']);
        }

        if (empty($request['order_no'])) {
            $errors['order_no'] = esc_html__('Order number is required.', 'devs-accounting');
        } else {
            $order_no = sanitize_text_field($request['order_no']);
        }

        if (empty($request['issued_at']) || !strtotime($request['issued_at'])) {
            $errors['issued_at'] = esc_html__('Valid issued date is required.', 'devs-accounting');
        } else {
            $issued_at = gmdate('Y-m-d H:i:s', strtotime($request['issued_at']));
        }

        if (empty($request['due_at']) || !strtotime($request['due_at'])) {
            $errors['due_at'] = esc_html__('Valid due date is required.', 'devs-accounting');
        } else {
            $due_at = gmdate('Y-m-d H:i:s', strtotime($request['due_at']));
        }

        if (!isset($request['amount']) || $request['amount'] < 0) {
            $errors['amount'] = esc_html__('Amount must be a non-negative number.', 'devs-accounting');
        } else {
            $amount = floatval($request['amount']);
        }

        if (!isset($request['discount']) || $request['discount'] < 0) {
            $errors['discount'] = esc_html__('Discount must be a non-negative number.', 'devs-accounting');
        } else {
            $discount = floatval($request['discount']);
        }

        if (empty($request['selected_items'])) {
            $errors['selected_items'] = esc_html__('Selected items data is required.', 'devs-accounting');
        } else {
            $selected_items = sanitize_textarea_field($request['selected_items']);
        }

        if (!empty($errors)) {
            return new WP_REST_Response(array('errors' => $errors), 400); 
        }
        $current_user = wp_get_current_user();

        $insert_data_invoice = array(
            'type'=>$type,
            'contact_id' => $contact_id,
            'invoice_no' => $invoice_no,
            'order_no' => $order_no, 
            'issued_at' => $issued_at,
            'due_at' => $due_at,
            'amount' => $amount,
            'discount' => $discount,
            'status' => 'Draft',
        );

        $all_data = array(
            'type'=>$type,
            'contact_id' => $contact_id,
            'invoice_no' => $invoice_no,
            'order_no' => $order_no,
            'issued_at' => $issued_at,
            'due_at' => $due_at,
            'amount' => $amount,
            'discount' => $discount,
            'invoice_items_data' => $selected_items,
            'status' => 'Draft',
        );

        if (!empty($request['id'])) {
            $where = array('id' => intval($request['id'])); 
            $table = $wpdb->update($table_name_invoice, $insert_data_invoice, $where);
            $insert_data_invoice_items = array(
                'invoice_items_data' => $selected_items,
            );
            $table_invoice_item = $wpdb->update($table_name_invoice_items, $insert_data_invoice_items, ['invoice_no' => $request['id']]);
            $all_data['id'] = $request['id'];
        
            $previous_inventory = $wpdb->get_results(
                $wpdb->prepare("SELECT item_id, in_out_qty FROM $table_name_inventory WHERE  remarks = %s",$invoice_no)
            );
         
            $delete_result = $wpdb->delete($table_name_inventory, array('remarks' => $invoice_no));
            if ($delete_result === false) {
                throw new Exception( 'Failed to delete inventory items: ' . $wpdb->last_error ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            }
        
            $selected_items_arr = json_decode($selected_items, true);
            foreach ($selected_items_arr as $item) {
                $item_id = intval($item['id']);
                $quantity = floatval($item['quantity']);
                $variant_id = isset($item['variant_id']) ? intval($item['variant_id']) : null;

                $previous_in_out_qty = null;
                foreach($previous_inventory as $inventory){
                    if($inventory->item_id == $item_id){
                        $previous_in_out_qty = $inventory->in_out_qty;
                    }
                }
                $quantity_change = $quantity + $previous_in_out_qty;
              
                if ($item['type'] === 'product' && class_exists('DevsAccounting_Wc')) {
                    $item = (new DevsAccounting_Wc)->save_wc_product($item_id, $variant_id, $quantity_change);
                }
                
                $inventory_table = $wpdb->prefix . 'dac_inventories';
                $data = array(
                    'item_id' => $item_id,
                    'in_out_qty' => -$quantity,
                    'remarks' => $invoice_no,
                    'user_id' => $current_user->ID,
                    'variant_id' => $variant_id,
                );
    
                $result = $wpdb->insert($inventory_table, $data);
                
                if ($result === false) {
                    error_log("Failed to update inventory for item ID: $item_id, Variant ID: $variant_id");
                }
                
            }

            if ($table !== false && $table_invoice_item !== false) {
                $response = array(
                    'success'=> true,
                    'message' => esc_html__('Invoice updated successfully!', 'devs-accounting'),
                    'data' => $all_data,
                );
            } else {
                $response = array(
                    'success' => false,
                    'message' => esc_html__('Update invoice failed', 'devs-accounting'),
                );
            }
        }
        else{        
            $invoice_result = $wpdb->insert($table_name_invoice, $insert_data_invoice);
            $invoice_id = $wpdb->insert_id;
            $insert_data_invoice_items = array(
                'invoice_no' => $invoice_id,
                'invoice_items_data' => $selected_items,
            );
            $invoice_item_result = $wpdb->insert($table_name_invoice_items, $insert_data_invoice_items);
            $selected_items_arr = json_decode($selected_items, true);
            foreach ($selected_items_arr as $item) {
                $item_id = intval($item['id']);
                $quantity = floatval($item['quantity']);
                $variant_id = isset($item['variant_id']) ? intval($item['variant_id']) : null;
                $in_out_qty = ($type === 'bill') ? $quantity : -$quantity; 

            
                if ($item['type'] === 'product') {
                    $product = wc_get_product($item_id);
                    if ($product && $product->get_type() === 'simple') {
                        $current_stock = $product->get_stock_quantity();
                        $new_stock = $current_stock + $in_out_qty;
                        $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 + $in_out_qty;
                            $variation->set_stock_quantity($new_stock);
                            $variation->save();
                        }
                    }
                }

                
                    $inventory_table = $wpdb->prefix . 'dac_inventories';
                    $data = array(
                        'item_id' => $item_id,
                        'in_out_qty' => $in_out_qty,
                        'remarks' => $invoice_no,
                        'user_id' => $current_user->ID,
                        'variant_id' => $variant_id,
                    );

                    $result = $wpdb->insert($inventory_table, $data);
       
                    if ($result === false) {
                        error_log("Failed to update inventory for item ID: $item_id, Variant ID: $variant_id");
                    }
                
            }
            if ($invoice_result !== false && $invoice_item_result !== false) {
                $all_data['id'] = $invoice_id;
                $response = array(
                    'success' => true,
                    'message' => esc_html__('Invoice created successfully!', 'devs-accounting'),
                    'data' => $all_data,
                    'items'=>json_decode($selected_items, true),
                    'errors'=> $wpdb->last_error,
                    'id' => $invoice_id,
                );
            } else {
                $response = array(
                    'message' => esc_html__('Create invoice failed', 'devs-accounting'),
                );
            }
        }

        return new WP_REST_Response($response, 200);
    }

    // Update invoice
   public function update_invoice_data($request) {
    global $wpdb;
    $table_name_invoice = $wpdb->prefix . 'dac_invoices';
    $table_name_transaction = $wpdb->prefix . 'dac_transactions';

    // Debug logging
    error_log('=== UPDATE INVOICE REQUEST ===');
    error_log('Request data: ' . print_r($request, true));
    
    $errors = array();
    
    if (!isset($request['id']) || intval($request['id']) <= 0) {
        $errors[] = esc_html__('Invoice ID must be a positive integer.', 'devs-accounting');
    } else {
        $invoice_id = intval($request['id']);
        error_log('Invoice ID: ' . $invoice_id);
    }

    $make_paid = isset($request['make_paid']) && !empty($request['make_paid']) ? true : false;
    
    // Get payment method from request, default to 'Cash'
    $payment_method = isset($request['payment_method']) ? sanitize_text_field($request['payment_method']) : 'Cash';
    error_log('Payment method from request: ' . $payment_method);
    
    if (!empty($errors)) {
        error_log('Errors: ' . print_r($errors, true));
        return new WP_REST_Response(array('errors' => $errors), 400); 
    }
   
    $current_time = current_time('mysql'); // Use WordPress time function

    $invoice = $this->get_single_invoice($request);
    
    // Debug invoice data
    error_log('Invoice data: ' . print_r($invoice, true));
    
    if (empty($invoice) || empty($invoice->data) || !isset($invoice->data->amount) || !isset($invoice->data->contact_id)) {
        error_log('Invalid invoice data received');
        return new WP_REST_Response(array('message' => esc_html__('Invalid invoice data', 'devs-accounting')), 400);
    }
    
    // Calculate total amount
    $totalAmount = floatval($invoice->data->amount);
    if (isset($invoice->data->discount)) {
        $totalAmount -= floatval($invoice->data->discount);
    }
    error_log('Total amount: ' . $totalAmount);
    
    $transaction_obj = new DevsAccounting_Transactions();
    $total_paid = $transaction_obj->get_invoice_total_paid($invoice_id);
    error_log('Total paid so far: ' . $total_paid);
    
    $transaction_inserted = false;
    $invoice_updated = false;
    
    // If marking as paid and total paid is less than total amount
    if ($make_paid && $totalAmount > $total_paid) {
        $remaining_amount = $totalAmount - $total_paid;
        error_log('Remaining amount to pay: ' . $remaining_amount);
        
        // Generate transaction ID
        $transaction_id = 'MAN-' . date('Ymd') . '-' . wp_rand(1000, 9999);
        
        $insert_data = array(
            'type' => 'income',
            'paid_at' => $current_time,
            'amount' => $remaining_amount,
            'contact_id' => intval($invoice->data->contact_id), // Fixed: Should be contact_id
            'document_id' => $invoice_id,
            'payment_method' => $payment_method,
            'description' => 'Invoice #' . $invoice_id . ' - Manual payment (' . $payment_method . ')',
            'transaction_id' => $transaction_id,
            'created_at' => $current_time,
            'updated_at' => $current_time,
        );
        
        $transaction_inserted = $wpdb->insert($table_name_transaction, $insert_data);
        
        if ($transaction_inserted) {
            $total_paid += $remaining_amount;
            error_log('New total paid: ' . $total_paid);
        }
    }
    $tolerance = 0.01;
    $is_fully_paid = abs($total_paid - $totalAmount) < $tolerance;
    if ($is_fully_paid || $make_paid) { 
        $invoice_update_data = array(
            'status' => 'Paid',
            'updated_at' => $current_time,
        );
        
        $table_columns = $wpdb->get_col("DESCRIBE {$table_name_invoice}", 0);
        if (in_array('payment_method', $table_columns)) {
            $invoice_update_data['payment_method'] = $payment_method;
        }
        
        $invoice_update_result = $wpdb->update(
            $table_name_invoice, 
            $invoice_update_data, 
            array('id' => $invoice_id)
        );
        
        $invoice_updated = ($invoice_update_result !== false);
        
        if ($invoice_updated) {
            $response = array(
                'success' => true,
                'message' => esc_html__('Invoice marked as paid successfully!', 'devs-accounting'),
                'invoice_id' => $invoice_id,
                'total_amount' => $totalAmount,
                'total_paid' => $total_paid,
                'payment_method' => $payment_method,
                'transaction_added' => $transaction_inserted,
            );
            return new WP_REST_Response($response, 200);
        } else {
            $response = array(
                'success' => false,
                'message' => esc_html__('Failed to update invoice status.', 'devs-accounting'),
                'wpdb_error' => $wpdb->last_error,
            );
            return new WP_REST_Response($response, 500);
        }
    } else {
        $response = array(
            'success' => false,
            'message' => esc_html__('Invoice cannot be marked as paid. Total paid: ' . $total_paid . ', Required: ' . $totalAmount, 'devs-accounting'),
            'total_paid' => $total_paid,
            'total_amount' => $totalAmount,
            'make_paid_requested' => $make_paid,
            'payment_method_received' => $payment_method,
        );
        return new WP_REST_Response($response, 400);
    }
}

    // Function to send email
    public function send_invoice_email($request) {
        
        $data = $this->get_single_invoice($request);
        $setting = get_option('devsaccounting_settings');

        $transactionObj = new DevsAccounting_Transactions();
        $transactions = $transactionObj->get_single_transaction_invoice(['id'=>$request['id']]);
        $transactionData = $transactions->get_data(); 

        $totalAmount = array_reduce($transactionData, function($sum, $item) {
            return $sum + $item->amount;
        }, 0);

        // echo "Total Amount: " . $totalAmount;
        $settinguser = json_decode($setting);

        // echo '<pre>';
        // print_r($data);
        // echo '</pre>';

        $item_data = isset($data->data->item_data) ? json_decode($data->data->item_data, true) : [];

        // Example email content
        $to = sanitize_email($data->data->contact_email);
        $subject = esc_html__('Invoice for your purchase', 'devs-accounting');

        $message = '<html>
                        <head>
                            <style>
                                body {
                                    font-family: Arial, sans-serif;
                                    line-height: 1.6;
                                    color: #333;
                                    background-color: #f9f9f9;
                                    padding: 20px;
                                }
                                .email-header h1 {
                                    color: #444;
                                }
                                .email-body p {
                                    margin: 10px 0;
                                }
                                .email-table {
                                    width: 100%;
                                    border-collapse: collapse;
                                    margin-top: 20px;
                                }
                                .email-table th, .email-table td {
                                    border: 1px solid #ddd;
                                    padding: 8px;
                                    text-align: left;
                                    border: none;
                                }
                                .email-table th {
                                    background-color: #f4f4f4;
                                    font-weight: bold;
                                }
                                .email-footer {
                                    font-size: 0.9em;
                                    color: #666;
                                    margin-top: 20px;
                                    text-align: center;
                                }
                                
                            </style>
                        </head>
                        <body>
                        <div class="email-header">
                            <p>' . esc_html__('Dear customer,', 'devs-accounting') . '</p>
                            <p>' . esc_html__('Please find your invoice details below. Thank you for your purchase!', 'devs-accounting') . '</p>
                                
                        </div>
                            <div style="display: flex; justify-content: space-between; align-items: flex-start; padding: 10px; border-bottom: 1px solid #ccc;">
                            <div class="email-header">
                                <h1>' . esc_html__($settinguser->company_name) . '</h1>
                                <p>' . esc_html__($settinguser->address) . '</p>
                                <p>' . esc_html__($settinguser->phone) . '</p>
                                <p>Invoice To: ' . esc_html__($data->data->contact_name) . '</p>
                                <p>' . esc_html__($transactions->data[0]->payment_method) . '</p>


                            </div>
                            <div class="email-header" >
                                <h1>' . esc_html__($data->data->invoice_no) . '</h1>
                            </div>
                            </div>

                            
                            <table style="width:100%;text-align: right;">
                                <tbody>
                                    <tr style="text-align: right;">
                                        <td style="width: 25%;"></td>
                                        <td style="width: 25%;"></td>
                                        <td style="width: 25%;">Invoice date:</td>
                                        <td style="width: 25%;">' . esc_html__($data->data->due_at) . '</td>
                                    </tr>
                                    <tr style="text-align: right;">
                                        <td style="width: 25%;"></td>
                                        <td style="width: 25%;"></td>
                                        <td style="width: 25%;">Due date:</td>
                                        <td style="width: 25%;">' .  esc_html__($data->data->updated_at) .'</td>
                                    </tr>
                                </tbody>
                            </table>
                            <div class="email-body">
                                <table class="email-table" style="width: 100%; border-collapse: collapse;">
                                                <thead>
                                                    <tr>
                                                        <th style="border: 1px solid #ddd; padding: 8px;">' . esc_html__('Item', 'devs-accounting') . '</th>
                                                        <th style="border: 1px solid #ddd; padding: 8px;">' . esc_html__('Quantity', 'devs-accounting') . '</th>
                                                        <th style="border: 1px solid #ddd; padding: 8px;">' . esc_html__('Rate', 'devs-accounting') . '</th>
                                                    </tr>
                                                </thead>
                                                <tbody>';

                                    if (!empty($item_data) && is_array($item_data)) {
                                        foreach ($item_data as $item) {
                                            $message .= '<tr>
                                                            <td style="border: 1px solid #ddd; padding: 8px;">' . esc_html($item['name']) . '</td>
                                                            <td style="border: 1px solid #ddd; padding: 8px;">' . intval($item['quantity']) . '</td>
                                                            <td style="border: 1px solid #ddd; padding: 8px;">' . esc_html(number_format($item['sale_price'], 2)) . '</td>
                                                        </tr>';
                                        }
                                    } else {
                                        $message .= '<tr>
                                                        <td colspan="3" style="border: 1px solid #ddd; padding: 8px; text-align: center;">' . esc_html__('No items found.', 'devs-accounting') . '</td>
                                                    </tr>';
                                    }

                                    $message .= '</tbody>
                                </table>


                                <table style="width:100%;text-align: right; padding: 8px; border-collapse: collapse; margin-top: 20px;">
                                <tbody style="padding: 8px;">
                                    <tr style="text-align: right; padding: 8px; margin-top: 10px;">
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%; text-align: left;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">SubTotal</td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">' . esc_html(number_format($data->data->amount, 2))  . '</td>
                                    
                                    </tr>
                                    <tr style="text-align: right; padding: 8px; margin-top: 10px;">
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%; text-align: left;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">Discount</td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">' . esc_html(number_format($data->data->discount, 2)) . '</td>
                                        
                                    </tr>

                                    <tr style="text-align: right; padding: 8px; margin-top: 10px;">
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%; text-align: left;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">Total</td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">' . esc_html(number_format($data->data->amount -$data->data->discount, 2)) . '</td>
                                        
                                    </tr>

                                    <tr style="text-align: right; padding: 8px; margin-top: 10px;">
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%; text-align: left;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">Paid</td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">' . esc_html(number_format(($data->data->amount -$data->data->discount)-(($data->data->amount -$data->data->discount)-$totalAmount), 2)) . ' </td>
                                        
                                    </tr>

                                    <tr style="text-align: right; padding: 8px; margin-top: 10px;">
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%; text-align: left;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;"></td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">Dues</td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;">' . esc_html(number_format(($data->data->amount - $data->data->discount)-$totalAmount, 2)) . '</td>
                                        <td style="border: 0px solid #ddd; padding: 8px; width: 25%;"></td>
                                    </tr>
                                </tbody>
                            </table>
                                <p>' . esc_html__('If you have any questions, feel free to contact our support team.', 'devs-accounting') . '</p>
                            </div>
                            <div class="email-footer">
                                <p>&copy; 2025 ' . esc_html__('Devs Accounting. All rights reserved.', 'devs-accounting') . '</p>
                            </div>
                        </body>
                    </html>';

            $headers = array('Content-Type: text/html; charset=UTF-8');
        
            // Send email
            $result = wp_mail($to, $subject, $message, $headers);
        
            // Check if email was sent successfully
            if ($result) {
                $response = array(
                    'message' => esc_html__('Mail sent successfully!', 'devs-accounting'),
                );
            } else {
                $response = array(
                    'message' => esc_html__('Mail sent failed!', 'devs-accounting'),
                );
            }
            return new WP_REST_Response($response, 200);
        }

    }

    function create_payment_intent(WP_REST_Request $request) {
        $settings = get_option('devsaccounting_settings');
        $settings = json_decode($settings, true);

        $stripe_secret_key = $settings['stripe_secret_key'];
        
        if (!$stripe_secret_key) {
            return new WP_REST_Response(['error' => 'Stripe secret key not set'], 500);
        }
    
        \Stripe\Stripe::setApiKey($stripe_secret_key);
    
        $amount = $request->get_param('amount');
        $currency = $request->get_param('currency') ?: 'usd';
    
        // Validate and sanitize amount
        if (!is_numeric($amount) || $amount <= 0) {
            return new WP_REST_Response(['error' => 'Invalid amount'], 400);
        }
    
        try {

            $paymentIntent = \Stripe\PaymentIntent::create([
                'amount' => intval($amount), 
                'currency' => sanitize_text_field($currency),
            ]);
    
            return new WP_REST_Response(
                ['clientSecret' => $paymentIntent->client_secret],
                200
            );
        } catch (\Stripe\Exception\ApiErrorException $e) {
            return new WP_REST_Response(
                ['error' => $e->getMessage()],
                400
            );
        }
    }
    
$invoices = new DevsAccounting_Invoice();