<?php
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly
class DevsAccounting_Account
{
    public function __construct()
    {
        add_action('rest_api_init', [$this, 'account_api_endpoint']);
    }

    // Define your custom endpoint
    public function account_api_endpoint()
    {
        register_rest_route('devs-accounting/v1', '/add-account', array(
            'methods' => 'POST', // Change to POST method to handle data insertion
            'callback' => [$this, 'save_accounting_data'],
            'permission_callback' => [$this, 'verify_accounts_nonce'],
        ));

        register_rest_route('devs-accounting/v1', '/accounts', array(
            'methods' => 'get', // Change to POST method to handle data insertion
            'callback' => [$this, 'get_accounts'],
            'permission_callback' => function () {
                return true;
            },
        ));

        register_rest_route('devs-accounting/v1', '/get-account/(?P<id>\d+)', array(
            'methods' => 'get', // Change to POST method to handle data insertion
            'callback' => [$this, 'get_single_account'],
            'permission_callback' => function () {
                return true;
            },
        ));

        register_rest_route('devs-accounting/v1', '/delete-account/(?P<id>\d+)', array(
            'methods' => 'get', // Change to POST method to handle data insertion
            'callback' => [$this, 'delete_single_account'],

        ));

        // register_rest_route('devsaccounting/v1', '/auth-check', array(
        //     'methods' => 'get',
        //     'callback' => [$this, 'devsaccounting_auth_check'],
        //     'permission_callback' => [$this, 'verify_accounts_nonce'],
        // ));

        // register_rest_route('devsaccounting/v1', '/login', array(
        //     'methods'             => 'POST',
        //     'callback'            => [$this, 'devsaccounting_login_callback'],
        //     'permission_callback' => '__return_true',
        // ));


        // register_rest_route('devsaccounting/v1', '/logout', array(
        //     'methods' => 'POST',
        //     'callback' => [$this, 'devsaccounting_logout_callback'],
        //     'permission_callback' => [$this, 'verify_accounts_nonce'],
        // ));

        // register_rest_route('devs-accounting/v1', '/update-user-meta', array(
        //     'methods' => 'POST',
        //     'callback' => [$this, 'update_user_meta_data'],
        //     'permission_callback' => function () {
        //         return is_user_logged_in(); 
        //     }
        // ));

        // register_rest_route('devs-accounting/v1', '/get-user-meta', array(
        //     'methods' => 'GET',
        //     'callback' => [$this, 'get_user_meta_data'],
        //     'permission_callback' => function () {
        //         return is_user_logged_in(); 
        //     }
        // ));

        register_rest_route('devs-accounting/v1', '/toggle-account/(?P<id>\d+)', array(
            'methods' => 'POST',
            'callback' => [$this, 'toggle_account_enabled'],
            'permission_callback' => [$this, 'verify_accounts_nonce'],
        ));
    }

    function verify_accounts_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_accounts()
    {
        global $wpdb;

        $table_name_accounts = $wpdb->prefix . 'dac_accounts';
        $table_name_transactions = $wpdb->prefix . 'dac_transactions';

        // This query joins the accounts table with the transactions table
        // It calculates the current balance based on the transaction type
        // If the transaction type is 'income', it adds the transaction amount to the opening balance
        // If the transaction type is 'expense', it subtracts the transaction amount from the opening balance

        $results = $wpdb->get_results($wpdb->prepare("
            SELECT 
                accounts.*, 
                COALESCE(SUM(
                    CASE 
                        WHEN transactions.type = 'income' THEN transactions.amount 
                        ELSE 0 
                    END
                ), 0) AS total_income,
                COALESCE(SUM(
                    CASE 
                        WHEN transactions.type = 'expense' THEN transactions.amount 
                        ELSE 0 
                    END
                ), 0) AS total_expense,
                (accounts.opening_balance + 
                 COALESCE(SUM(
                    CASE 
                        WHEN transactions.type = 'income' THEN transactions.amount 
                        ELSE 0 
                    END
                ), 0) - 
                 COALESCE(SUM(
                    CASE 
                        WHEN transactions.type = 'expense' THEN transactions.amount 
                        ELSE 0 
                    END
                ), 0)) AS current_balance
            FROM $table_name_accounts AS accounts
            LEFT JOIN $table_name_transactions AS transactions
            ON accounts.id = transactions.account_id
            WHERE accounts.deleted_at IS NULL
            GROUP BY accounts.id, accounts.name, accounts.opening_balance
            ORDER BY accounts.id DESC
        "));

        return rest_ensure_response($results);
    }



    public function get_single_account($request)
    {
        global $wpdb;

        $table_name = $wpdb->prefix . 'dac_accounts';

        // Retrieve the task ID from the request
        $account_id = $request['id'];


        // Fetch the task details using custom query
        $account = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $account_id));

        // Check if the task exists
        if ($account) {
            // Return the task details
            return rest_ensure_response($account);
        } else {
            // Task not found, return error response
            return new WP_Error('task_not_found', esc_html__('Task not found', 'devs-accounting'), array('status' => 404));
        }
    }

    public function delete_single_account($request)
    {
        global $wpdb;

        $table_name = $wpdb->prefix . 'dac_accounts';

        // Retrieve the task ID from the request
        $account_id = isset($request['id']) ? intval($request['id']) : 0;

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

        // Check if the item exists
        $existing_contact = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM $table_name WHERE ID = %d",
                $account_id
            )
        );

        if (!$existing_contact) {
            return new WP_Error('item_not_found', esc_html__('Account not found', 'devs-accounting'), array('status' => 404));
        }

        // Get current time
        $current_time = gmdate('Y-m-d H:i:s'); // 'mysql' format returns time in MySQL datetime format

        // Soft delete the item by updating its status
        $result = $wpdb->update(
            $table_name,
            array(
                'deleted_at' => $current_time,
            ),
            array('id' => $account_id),
        );

        // Check if update was successful
        if ($result === false) {
            return new WP_Error('soft_delete_failed', esc_html__('Failed to soft delete Account', 'devs-accounting'), array('status' => 500));
        }

        // Return success response
        return rest_ensure_response(array('message' => esc_html__('Account soft deleted successfully', 'devs-accounting')));
    }


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

        $errors = array();

        // Validate and sanitize input data
        $name = isset($request['name']) ? sanitize_text_field($request['name']) : '';
        if (empty($name)) {
            $errors['name'] = esc_html__('Name is required.', 'text-domain');
        }

        $bank_name = isset($request['bank_name']) ? sanitize_text_field($request['bank_name']) : '';
        if (empty($bank_name)) {
            $errors['bank_name'] = esc_html__('Bank Name is required.', 'text-domain');
        }
        $opening_balance = isset($request['opening_balance']) ? sanitize_text_field($request['opening_balance']) : '';
        $enabled = isset($request['enabled']) ? (int)$request['enabled'] : 1;
        // Return errors if validation failed
        if (!empty($errors)) {
            return new WP_REST_Response(array('errors' => $errors), 400); // Bad Request
        }

        // Prepare data for insertion/update
        $insert_data = array(
            'name' => $name,
            'bank_name' => $bank_name,
            'opening_balance' => $opening_balance,
            'enabled' => $enabled
        );

        // Check if account ID is provided for update
        if (!empty($request['id'])) {
            $where = array('id' => intval($request['id']));
            $table = $wpdb->update($table_name, $insert_data, $where);
            if ($table !== false) {
                $response['message'] = esc_html__('Account updated successfully!', 'devs-accounting');
                $response['data'] = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", intval($request['id'])));
            } else {
                $response['message'] = esc_html__('Update Account failed', 'devs-accounting');
                return new WP_REST_Response($response, 500); // Internal Server Error
            }
        } else {
            // Insert new account
            $table = $wpdb->insert($table_name, $insert_data);
            if ($table !== false) {
                $response['message'] = esc_html__('Account created successfully!', 'devs-accounting');
                $response['data'] = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $wpdb->insert_id));
            } else {
                $response['message'] = esc_html__('Create Account failed', 'devs-accounting');
                return new WP_REST_Response($response, 500); // Internal Server Error
            }
        }

        return new WP_REST_Response($response, 200);
    }
    public function toggle_account_enabled($request)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_accounts';
        $acc_id = (int)$request->get_param('id');

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

        $current_item = $wpdb->get_row($wpdb->prepare(
            "SELECT enabled FROM $table_name WHERE id = %d",
            $acc_id
        ));

        if (!$current_item) {
            return new WP_Error('item_not_found', esc_html__('Account not found', 'devs-accounting'), array('status' => 404));
        }


        $new_status = $current_item->enabled ? 0 : 1;

        $result = $wpdb->update(
            $table_name,
            array('enabled' => $new_status),
            array('id' => $acc_id),
            array('%d'),
            array('%d')
        );

        if ($result === false) {
            return new WP_Error('update_failed', esc_html__('Failed to toggle account status', 'devs-accounting'), array('status' => 500));
        }

        $action = $new_status ? 'enabled' : 'disabled';
        return rest_ensure_response(array(
            'success' => true,
            'enabled' => (bool)$new_status,
            'message' => esc_html__("Account successfully $action", 'devs-accounting'),
            'action' => $action
        ));
    }
    // function devsaccounting_auth_check() {
    //     if (is_user_logged_in()) {
    //         return new WP_REST_Response(['authenticated' => true, 'user' => wp_get_current_user()], 200);
    //     } else {
    //         return new WP_REST_Response(['authenticated' => false], 401);
    //     }
    // }

    // function devsaccounting_login_callback( $data ) {
    //     $username = sanitize_text_field( $data['username'] );
    //     $password = sanitize_text_field( $data['password'] );

    //     $user = wp_signon( array(
    //         'user_login'    => $username,
    //         'user_password' => $password,
    //     ), false );


    //     if ( is_wp_error( $user ) ) {
    //         return new WP_Error( 'login_failed', 'Invalid username or password', array( 'status' => 403 ) );
    //     }

    //     return rest_ensure_response( array(
    //         'authenticated' => true,
    //         'user' => wp_get_current_user(),
    //     ));

    // }


    // function devsaccounting_logout_callback( WP_REST_Request $request ) {
    //     if (is_user_logged_in()) {
    //         wp_logout(); 
    //         wp_clear_auth_cookie(); 
    //         return new WP_REST_Response(['success' => true, 'message' => 'Logged out successfully'], 200);
    //     } else {
    //         return new WP_REST_Response(['success' => false, 'message' => 'User not logged in'], 401);
    //     }
    // }


    // function update_user_meta_data($params) {
    //     $user_id = get_current_user_id(); 

    //     if (!$user_id) {
    //         return new WP_REST_Response(['message' => 'User not logged in'], 401);
    //     }

    //     $key = sanitize_text_field($params['meta_key']); 
    //     $value = sanitize_text_field($params['meta_value']); 

    //     if (empty($key) || empty($value)) {
    //         return new WP_REST_Response(['message' => 'Missing parameters'], 400);
    //     }

    //     // Update user meta
    //     update_user_meta($user_id, $key, $value);

    //     return new WP_REST_Response(['message' => 'Billing information updated successfully'], 200);
    // }


    // function get_user_meta_data(WP_REST_Request $request) {
    //     $user_id = get_current_user_id(); 

    //     if (!$user_id) {
    //         return new WP_REST_Response(['message' => 'User not logged in'], 401); 
    //     }

    //     $params = $request->get_query_params(); 
    //     $key = sanitize_text_field($params['key']); 

    //     if (empty($key)) {
    //         return new WP_REST_Response(['message' => 'Missing key parameter'], 400); 
    //     }

    //     $user_meta = get_user_meta($user_id, $key, true);

    //     if (empty($user_meta)) {
    //         return new WP_REST_Response(['message' => 'No data found for this key'], 404); 
    //     }

    //     if (is_serialized($user_meta)) {
    //         $user_meta = unserialize($user_meta);
    //     }

    //     return new WP_REST_Response(['data' => $user_meta], 200);  
    // }


}

$accounts = new DevsAccounting_Account();
