<?php

defined('ABSPATH') or die('No script kiddies please!!');
if (!class_exists('CIWS_API')) {
    class CIWS_API
    {
        function __construct()
        {
            

            add_action('rest_api_init', [$this,'ciws_register_account_endpoint']);
        }

        function ciws_register_account_endpoint() {
            register_rest_route('ciws/v1', '/accounts', array(
                'methods' => 'GET',
                'callback' => array($this, 'ciws_get_accounts'),
                'permission_callback' => function() {
                    return current_user_can('manage_options');
                },
            ));
        }
        
        function ciws_get_accounts() {
            global $wpdb;
         
            // Query to get account data
           
            $account_rows = $wpdb->get_results($wpdb->prepare("select * from %i order by account_id desc", CIWS_TABLE));
            $accounts = [];
        
            foreach ($account_rows as $account_row) {
                $ciws_account_details = maybe_unserialize($account_row->ciws_account_details);
                $accounts[] = [
                    'id' => $account_row->account_id,
                    'name' => $account_row->account_name,
                    'number' => !empty($ciws_account_details['account']['account_number']) ? $ciws_account_details['account']['account_number'] : '',
                    'default_msg' => !empty($ciws_account_details['account']['default_msg']) ? $ciws_account_details['account']['default_msg'] : ''
                ];
            }
        
            return new WP_REST_Response($accounts, 200);
        }
      
    }

    new CIWS_API();
}