<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * REST API: /vlens/v1/settings
 * Read and update plugin settings.
 */
class VLENS_REST_Settings {

    public function register_routes() {
        $admin_perm = function () {
            return current_user_can( 'manage_options' );
        };

        register_rest_route( 'vlens/v1', '/settings', [
            [
                'methods'             => 'GET',
                'callback'            => [ $this, 'get_settings' ],
                'permission_callback' => $admin_perm,
            ],
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'update_settings' ],
                'permission_callback' => $admin_perm,
            ],
        ] );

        // 19b: Storage usage for all vs_* tables
        register_rest_route( 'vlens/v1', '/settings/storage', [
            'methods'             => 'GET',
            'callback'            => [ $this, 'get_storage' ],
            'permission_callback' => $admin_perm,
        ] );
    }

    public function get_settings() {
        $settings = VLENS_Settings::get_all();

        // Premium can add settings tabs
        $settings['_tabs'] = apply_filters( 'vlens_admin_tabs', [
            'general' => __( 'General', 'visitor-lens' ),
            'privacy' => __( 'Privacy', 'visitor-lens' ),
            'data'    => __( 'Data Management', 'visitor-lens' ),
        ] );

        return new WP_REST_Response( $settings );
    }

    public function update_settings( WP_REST_Request $request ) {
        $data = $request->get_json_params();
        VLENS_Settings::update( $data );

        $updated = VLENS_Settings::get_all();

        // Fire hook after settings saved
        do_action( 'vlens_settings_updated', $updated );

        return new WP_REST_Response( [
            'ok'       => true,
            'settings' => $updated,
        ] );
    }

    /**
     * 19b — Return disk usage for every vs_* database table.
     * Queries information_schema.TABLES; sizes are in bytes.
     */
    public function get_storage() {
        global $wpdb;

        $db_name    = DB_NAME;
        $tbl_prefix = $wpdb->prefix . 'vlens_';

        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT TABLE_NAME AS name,
                    CAST(DATA_LENGTH + INDEX_LENGTH AS UNSIGNED) AS bytes,
                    TABLE_ROWS AS row_count
             FROM information_schema.TABLES
             WHERE TABLE_SCHEMA = %s
               AND TABLE_NAME LIKE %s
             ORDER BY bytes DESC",
            $db_name,
            $tbl_prefix . '%'
        ), ARRAY_A );

        if ( ! is_array( $rows ) ) {
            $rows = [];
        }

        // Strip the full WP+VS prefix so JS sees short names (e.g. "sessions")
        $short_prefix = $tbl_prefix;
        $tables = array_map( function ( $r ) use ( $short_prefix ) {
            return [
                'name'      => str_replace( $short_prefix, '', $r['name'] ),
                'bytes'     => (int) $r['bytes'],
                'row_count' => (int) $r['row_count'],
            ];
        }, $rows );

        $total_bytes = array_sum( array_column( $rows, 'bytes' ) );

        return new WP_REST_Response( [
            'tables'      => $tables,
            'total_bytes' => (int) $total_bytes,
        ] );
    }
}
