<?php
if (!defined('ABSPATH'))
exit; // Exit if accessed directly
class DevsAccounting_Transfer{
    public $tr_table;
    
    public function __construct()
    {
        global $wpdb;
        $this->tr_table= $wpdb->prefix . 'dac_transfers';
        add_action('rest_api_init', [$this, 'transfer_api_endpoint']);
    }

    public function transfer_api_endpoint() {
        register_rest_route('devs-accounting/v1', '/add-transfer', array(
            'methods' => 'POST',
            'callback' => [$this, 'save_transfer_data'],
            'permission_callback' => [$this, 'verify_transfer_nonce'],
        ));

        register_rest_route('devs-accounting/v1', '/get-transfer', array(
            'methods' => 'get', 
            'callback' => [$this, 'get_transfer'],
            'permission_callback' => function () {
                return true;
            },
        ));
        
        register_rest_route('devs-accounting/v1', '/get-transfer/(?P<id>\d+)', array(
            'methods' => 'get',
            'callback' => [$this, 'get_single_transfer'],
            'permission_callback' => function () {
                return true;
            },
        ));
        
        register_rest_route('devs-accounting/v1', '/delete-transfer/(?P<id>\d+)', array(
            'methods' => 'get', 
            'callback' => [$this, 'delete_single_transfer'],
            'permission_callback' => [$this, 'verify_transfer_nonce'],
        ));
    }

    function verify_transfer_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_transfer() {
        global $wpdb;
    
        $table_name_transfers = $this->tr_table; 
        $table_name_accounts = $wpdb->prefix . 'dac_accounts';
    
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT t.*, t.from_account_id, t.to_account_id
             FROM $table_name_transfers AS t
             WHERE t.deleted_at IS NULL
             ORDER BY t.transfer_date DESC"
        ));
    
        foreach ($results as &$result) {
            $from_account_name = $wpdb->get_var($wpdb->prepare(
                "SELECT name FROM $table_name_accounts WHERE id = %d",
                $result->from_account_id
            ));
    
            $to_account_name = $wpdb->get_var($wpdb->prepare(
                "SELECT name FROM $table_name_accounts WHERE id = %d",
                $result->to_account_id
            ));
    
            $result->from_account_name = $from_account_name;
            $result->to_account_name = $to_account_name;
       
            if (!empty($result->data)) {
                $result->data = unserialize($result->data);
            }
        }

        return rest_ensure_response($results);
    }
    
    
    
    
    public function get_single_transfer($request) {
        global $wpdb;
    
        $id = (int) $request['id'];
    
        $table_name_transfers = $this->tr_table; 
        $table_name_accounts = $wpdb->prefix . 'dac_accounts';
    
        // Get the transfer
        $transfer = $wpdb->get_row($wpdb->prepare(
            "SELECT t.*
             FROM $table_name_transfers AS t
             WHERE t.id = %d AND t.deleted_at IS NULL",
            $id
        ));
    
        if (!$transfer) {
            return new WP_Error('not_found', __('Transfer not found.', 'devs-accounting'), array('status' => 404));
        }
    
        // Fetch from_account_name
        $from_account_name = $wpdb->get_var($wpdb->prepare(
            "SELECT name FROM $table_name_accounts WHERE id = %d",
            $transfer->from_account_id
        ));
    
        // Fetch to_account_name
        $to_account_name = $wpdb->get_var($wpdb->prepare(
            "SELECT name FROM $table_name_accounts WHERE id = %d",
            $transfer->to_account_id
        ));
    
        // Add the names to the result
        $transfer->from_account_name = $from_account_name;
        $transfer->to_account_name = $to_account_name;
    
        // Unserialize data if needed
        if (!empty($transfer->data)) {
            $transfer->data = maybe_unserialize($transfer->data);
        }
    
        return rest_ensure_response($transfer);
    }
    
    
    public function get_single_transaction($request) {
        global $wpdb;
    
        $table_name = $this->tr_table;
    
        $transaction_id = $request['id'];

        $transaction = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE ID = %d",
            $transaction_id
        ));
    
        if ($transaction) {
            if (!empty($transaction->data)) {
                $transaction->data = unserialize($transaction->data);
            }
    
            return rest_ensure_response($transaction);
        } else {
            return new WP_Error('transaction_not_found', esc_html__('Transaction not found', 'devs-accounting'), array('status' => 404));
        }
    }
    
    
    public function delete_single_transfer($request) {
        global $wpdb;

        $table_name = $this->tr_table;

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

        if ($transaction_id <= 0) {
            return new WP_Error( 'invalid_item_id', esc_html__( 'Invalid item ID', 'devs-accounting' ), array( 'status' => 400 ) );
        }

        $existing_transaction = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM $table_name WHERE ID = %d",
                $transaction_id
            )
        );

        if (!$existing_transaction) {
            return new WP_Error( 'item_not_found', esc_html__( 'Transaction 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' => $transaction_id ),
        );
    
        if ($result === false) {
            return new WP_Error( 'soft_delete_failed', esc_html__( 'Failed to soft delete item', 'devs-accounting' ), array( 'status' => 500 ) );
        }

        return rest_ensure_response( array( 'message' => esc_html__('Transaction soft deleted successfully', 'devs-accounting') ) );
    }

    // public function save_transfer_data($request) {
    //     global $wpdb;
    //     $table_name = $this->tr_table;
    //     $errors = array();
    
    //     // Validate transfer date
    //     $transfer_date = gmdate('Y-m-d H:i:s', strtotime($request['transfer_date']));
    //     if (!$transfer_date) {
    //         $errors['transfer_date'] = esc_html__('Invalid date format for transfer_date.', 'devs-accounting');
    //     }
    
    //     // Validate amount
    //     if (empty($request['amount']) || $request['amount'] <= 0) {
    //         $errors['amount'] = esc_html__('Amount must be a positive number.', 'devs-accounting');
    //     } else {
    //         $amount = floatval($request['amount']);
    //     }
    
    //     // Validate from and to accounts
    //     if (empty($request['from_account_id'])) {
    //         $errors['from_account_id'] = esc_html__('From account is required.', 'devs-accounting');
    //     } else {
    //         $from_account_id = intval($request['from_account_id']);
    //     }
    
    //     if (empty($request['to_account_id'])) {
    //         $errors['to_account_id'] = esc_html__('To account is required.', 'devs-accounting');
    //     } else {
    //         $to_account_id = intval($request['to_account_id']);
    //     }
    
    //     // Payment method validation
    //     if (empty($request['payment_method'])) {
    //         $errors['payment_method'] = esc_html__('Payment method is required.', 'devs-accounting');
    //     } else {
    //         $payment_method = sanitize_text_field($request['payment_method']);
    //     }
    
    //     // Optional reference field
    //     $reference = sanitize_text_field($request['reference']);
    
    //     // If any validation errors, return them
    //     if (!empty($errors)) {
    //         return new WP_REST_Response(array('errors' => $errors), 400);
    //     }
    
    //     // Prepare the data for insertion
    //     $insert_data = array(
    //         'transfer_date' => $transfer_date,
    //         'amount' => $amount,
    //         'from_account_id' => $from_account_id,
    //         'to_account_id' => $to_account_id,
    //         'payment_method' => $payment_method,
    //         'reference' => $reference,
    //         'created_at' => current_time('mysql'),
    //         'updated_at' => current_time('mysql'),
    //     );
    
    //     // If an ID is provided (updating an existing transfer)
    //     if (!empty($request['id'])) {
    //         $where = array('id' => intval($request['id']));
    //         $updated = $wpdb->update($table_name, $insert_data, $where);
    
    //         if ($updated !== false) {
    //             $response = array(
    //                 'message' => esc_html__('Transfer updated successfully!', 'devs-accounting'),
    //                 'data' => $updated,
    //             );
    //         } else {
    //             $response = array(
    //                 'message' => esc_html__('Update transfer failed', 'devs-accounting'),
    //             );
    //         }
    //     } else {
    //         // If no ID, create a new transfer
    //         $inserted = $wpdb->insert($table_name, $insert_data);
    
    //         if ($inserted) {
    //             $response = array(
    //                 'message' => esc_html__('Transfer created successfully!', 'devs-accounting'),
    //                 'data' => $wpdb->insert_id,  // Return the newly inserted transfer ID
    //             );
    //         } else {
    //             $response = array(
    //                 'message' => esc_html__('Create transfer failed', 'devs-accounting'),
    //                 'error' => $wpdb->last_error,
    //             );
    //         }
    //     }
    
    //     // Return the response
    //     return new WP_REST_Response($response, !empty($errors) ? 400 : 200);
    // }
    
    public function save_transfer_data($request) {
        global $wpdb;
        $table_name_transfers = $this->tr_table;
        $table_name_transactions = $wpdb->prefix . 'dac_transactions';
        $errors = array();
    
        // Validate transfer date
        $transfer_date = gmdate('Y-m-d H:i:s', strtotime($request['transfer_date']));
        if (!$transfer_date) {
            $errors['transfer_date'] = esc_html__('Invalid date format for transfer_date.', 'devs-accounting');
        }
    
        // Validate amount
        if (empty($request['amount']) || $request['amount'] <= 0) {
            $errors['amount'] = esc_html__('Amount must be a positive number.', 'devs-accounting');
        } else {
            $amount = floatval($request['amount']);
        }
    
        // Validate from and to accounts
        if (empty($request['from_account_id'])) {
            $errors['from_account_id'] = esc_html__('From account is required.', 'devs-accounting');
        } else {
            $from_account_id = intval($request['from_account_id']);
        }
    
        if (empty($request['to_account_id'])) {
            $errors['to_account_id'] = esc_html__('To account is required.', 'devs-accounting');
        } else {
            $to_account_id = intval($request['to_account_id']);
        }
    
        // Payment method validation
        if (empty($request['payment_method'])) {
            $errors['payment_method'] = esc_html__('Payment method is required.', 'devs-accounting');
        } else {
            $payment_method = sanitize_text_field($request['payment_method']);
        }
    
        // Optional reference
        $reference = sanitize_text_field($request['reference']);
    
        // If any validation errors, return them
        if (!empty($errors)) {
            return new WP_REST_Response(array('errors' => $errors), 400);
        }
    
        // Prepare transfer data for insertion
        $insert_data = array(
            'transfer_date'    => $transfer_date,
            'amount'           => $amount,
            'from_account_id'  => $from_account_id,
            'to_account_id'    => $to_account_id,
            'payment_method'   => $payment_method,
            'reference'        => $reference,
            'created_at'       => current_time('mysql'),
            'updated_at'       => current_time('mysql'),
        );
    
        // Insert or update transfer
        if (!empty($request['id'])) {
            $where = array('id' => intval($request['id']));
            $updated = $wpdb->update($table_name_transfers, $insert_data, $where);
    
            if ($updated !== false) {
                $transfer_id = intval($request['id']);
                $response_message = esc_html__('Transfer updated successfully!', 'devs-accounting');
            } else {
                return new WP_REST_Response(array('message' => esc_html__('Update transfer failed.', 'devs-accounting')), 500);
            }
        } else {
            $inserted = $wpdb->insert($table_name_transfers, $insert_data);
    
            if ($inserted) {
                $transfer_id = $wpdb->insert_id;
                $response_message = esc_html__('Transfer created successfully!', 'devs-accounting');
            } else {
                return new WP_REST_Response(array('message' => esc_html__('Create transfer failed.', 'devs-accounting'), 'error' => $wpdb->last_error), 500);
            }
        }
    
        // Now insert two transactions
        $common_transaction_data = array(
            'paid_at'         => $transfer_date,
            'amount'          => $amount,
            'description'     => esc_html__('Fund transfer', 'devs-accounting'),
            'category_id'     => 0,
            'contact_id'      => 0,
            'document_id'     => 0,
            'transaction_id'  => null,
            'data'            => maybe_serialize(array('transfer_id' => $transfer_id)), // Link transaction to transfer
            'payment_method'  => $payment_method,
        );
    
        // Insert Expense for from_account_id
        $wpdb->insert($table_name_transactions, array_merge($common_transaction_data, array(
            'account_id' => $from_account_id,
            'type'       => 'expense',
        )));
    
        // Insert Income for to_account_id
        $wpdb->insert($table_name_transactions, array_merge($common_transaction_data, array(
            'account_id' => $to_account_id,
            'type'       => 'income',
        )));
    
        return new WP_REST_Response(array(
            'message' => $response_message,
            'transfer_id' => $transfer_id,
        ), 200);
    }
    
   
}

$transfer = new DevsAccounting_Transfer(); 