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

class BLM_API {

    public static function register_routes() {
        register_rest_route( 'blm/v1', '/update', array(
            'methods'             => 'POST',
            'callback'            => array( __CLASS__, 'handle_update' ),
            'permission_callback' => array( __CLASS__, 'check_permission' ),
        ) );

        register_rest_route( 'blm/v1', '/data', array(
            'methods'             => 'GET',
            'callback'            => array( __CLASS__, 'handle_get_data' ),
            'permission_callback' => array( __CLASS__, 'check_permission' ),
        ) );
    }

    public static function check_permission( WP_REST_Request $request ) {
        if ( ! is_ssl() && ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) {
            return new WP_Error(
                'rest_forbidden',
                'HTTPS is required.',
                array( 'status' => 403 )
            );
        }

        $api_key = $request->get_header( 'X-BLM-Key' );

        if ( empty( $api_key ) ) {
            return new WP_Error(
                'rest_unauthorized',
                'API key is required.',
                array( 'status' => 401 )
            );
        }

        if ( ! BLM_Connection::validate_key( $api_key ) ) {
            return new WP_Error(
                'rest_unauthorized',
                'Invalid API key.',
                array( 'status' => 401 )
            );
        }

        return true;
    }

    public static function handle_update( WP_REST_Request $request ) {
        $body = $request->get_json_params();

        if ( empty( $body ) || ! is_array( $body ) ) {
            return new WP_Error(
                'rest_invalid_data',
                'Invalid request body.',
                array( 'status' => 400 )
            );
        }

        $data = self::sanitize_business_data( $body );

        update_option( 'blm_business_data', $data );
        $timestamp = current_time( 'mysql' );
        update_option( 'blm_last_updated', $timestamp );

        return rest_ensure_response( array(
            'status'     => 'success',
            'updated_at' => $timestamp,
        ) );
    }

    public static function handle_get_data( WP_REST_Request $request ) {
        $data = get_option( 'blm_business_data', array() );
        $last_updated = get_option( 'blm_last_updated', '' );

        if ( empty( $data ) || ! is_array( $data ) ) {
            return rest_ensure_response( array(
                'status' => 'empty',
                'data'   => array(),
            ) );
        }

        return rest_ensure_response( array(
            'status'       => 'success',
            'data'         => $data,
            'last_updated' => $last_updated,
        ) );
    }

    private static function sanitize_business_data( $input ) {
        $data = array();

        $data['business_name'] = sanitize_text_field( isset( $input['business_name'] ) ? $input['business_name'] : '' );
        $data['business_type'] = sanitize_key( isset( $input['business_type'] ) ? $input['business_type'] : 'local_business' );
        $data['description']   = sanitize_textarea_field( isset( $input['description'] ) ? $input['description'] : '' );
        $data['address']       = sanitize_text_field( isset( $input['address'] ) ? $input['address'] : '' );
        $data['city']          = sanitize_text_field( isset( $input['city'] ) ? $input['city'] : '' );
        $data['state']         = sanitize_text_field( isset( $input['state'] ) ? $input['state'] : '' );
        $data['postal_code']   = sanitize_text_field( isset( $input['postal_code'] ) ? $input['postal_code'] : '' );
        $data['country']       = sanitize_text_field( isset( $input['country'] ) ? $input['country'] : '' );
        $data['phone']         = sanitize_text_field( isset( $input['phone'] ) ? $input['phone'] : '' );
        $data['email']         = sanitize_email( isset( $input['email'] ) ? $input['email'] : '' );
        $data['website']       = esc_url_raw( isset( $input['website'] ) ? $input['website'] : '' );
        $data['logo']          = esc_url_raw( isset( $input['logo'] ) ? $input['logo'] : '' );
        $data['price_range']   = sanitize_text_field( isset( $input['price_range'] ) ? $input['price_range'] : '' );

        // Hours
        $data['open_247'] = ! empty( $input['open_247'] ) ? '1' : '';
        $data['hours']    = array();
        $days = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );
        if ( isset( $input['hours'] ) && is_array( $input['hours'] ) ) {
            foreach ( $days as $day ) {
                if ( isset( $input['hours'][ $day ] ) ) {
                    $data['hours'][ $day ] = array(
                        'open'       => ! empty( $input['hours'][ $day ]['open'] ) ? '1' : '',
                        'open_time'  => sanitize_text_field( isset( $input['hours'][ $day ]['open_time'] ) ? $input['hours'][ $day ]['open_time'] : '09:00' ),
                        'close_time' => sanitize_text_field( isset( $input['hours'][ $day ]['close_time'] ) ? $input['hours'][ $day ]['close_time'] : '17:00' ),
                    );
                }
            }
        }

        // Social
        $data['social'] = array();
        $social_keys = array( 'facebook', 'twitter', 'instagram', 'linkedin', 'youtube', 'yelp' );
        if ( isset( $input['social'] ) && is_array( $input['social'] ) ) {
            foreach ( $social_keys as $sk ) {
                $data['social'][ $sk ] = esc_url_raw( isset( $input['social'][ $sk ] ) ? $input['social'][ $sk ] : '' );
            }
        }

        // Type-specific fields
        $data['type_fields'] = array();
        $type_fields = BLM_Business_Types::get_type_fields( $data['business_type'] );
        if ( isset( $input['type_fields'] ) && is_array( $input['type_fields'] ) ) {
            foreach ( $type_fields as $field ) {
                $raw = isset( $input['type_fields'][ $field['key'] ] ) ? $input['type_fields'][ $field['key'] ] : '';
                if ( 'textarea' === $field['type'] ) {
                    $data['type_fields'][ $field['key'] ] = sanitize_textarea_field( $raw );
                } elseif ( 'checkboxes' === $field['type'] ) {
                    $data['type_fields'][ $field['key'] ] = is_array( $raw ) ? array_map( 'sanitize_text_field', $raw ) : array();
                } else {
                    $data['type_fields'][ $field['key'] ] = sanitize_text_field( $raw );
                }
            }
        }

        return $data;
    }
}
