<?php
/**
 * Languages Endpoint for BoostBot REST API.
 *
 * Provides language configuration and admin language switching.
 *
 * @package BoostBot
 * @since   1.2.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class BoostBot_Languages_Endpoint extends BoostBot_Base_Endpoint {

    protected $rest_base = 'languages';

    public function register() {
        // GET /languages — language config for admin
        $this->register_route(
            '',
            'GET',
            array( $this, 'get_config' ),
            array( $this, 'admin_access' )
        );

        // POST /languages/current — set admin language context
        $this->register_route(
            '/current',
            'POST',
            array( $this, 'set_current' ),
            array( $this, 'admin_access' )
        );
    }

    /**
     * GET /languages — Returns enabled languages, current admin language, and labels.
     */
    public function get_config( $request ) {
        $manager = BoostBot_Language_Manager::get_instance();

        return $this->success( $manager->get_language_config() );
    }

    /**
     * POST /languages/current — Sets the admin language context cookie.
     */
    public function set_current( $request ) {
        $language = sanitize_text_field( $request->get_param( 'language' ) ?? '' );

        if ( empty( $language ) ) {
            return $this->error( __( 'Language code is required', 'boostbot' ), 400 );
        }

        $manager = BoostBot_Language_Manager::get_instance();

        if ( ! $manager->is_language_enabled( $language ) ) {
            return $this->error( __( 'Language is not enabled', 'boostbot' ), 400 );
        }

        $manager->set_admin_language( $language );

        // Seed default data for this language if not yet done (idempotent)
        try {
            $db = new BoostBot_DB_Manager();
            $db->seed_language_defaults( $language );
        } catch ( \Throwable $e ) {
            if ( class_exists( 'BoostBot_Logger' ) ) {
                BoostBot_Logger::error( 'Failed to seed defaults for language', array( 'language' => $language, 'error' => $e->getMessage() ) );
            }
        }

        return $this->success( array(
            'language' => $language,
            'is_rtl'   => BoostBot_Language_Manager::is_rtl_language( $language ),
        ) );
    }
}
