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

    // Define your custom endpoint
    public function user_api_endpoint() {
        register_rest_route('devsaccounting/v1', '/auth-check', array(
            'methods' => 'get',
            'callback' => [$this, 'devsaccounting_auth_check'],
            'permission_callback' => [$this, 'verify_users_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_users_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(); 
            }
        ));

    }

    function verify_users_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;
    }

    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($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);  
    }
    

}

$devs_users = new DevsAccounting_User(); 