<?php
/**
 * Basic Authentication Strategy
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Strategies\Authentication
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Strategies\Authentication;

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

use WP_Error;
use MOWCPS\Common\Abstracts\Auth_Base_Strategy;
use MOWCPS\Common\Constants\Constants;

/**
 * Class Basic_Auth_Strategy
 *
 * Handles basic authentication with username/password
 */
class Basic_Auth_Strategy extends Auth_Base_Strategy {
	/**
	 * Generate authorization headers
	 *
	 * @param int   $supplier_id Supplier ID.
	 * @param array $settings Auth settings.
	 * @return array|WP_Error Headers array or error
	 */
	public function generate_headers( $settings, $supplier_id ) {
		// Validate settings first.
		$validation = $this->validate_settings( $settings );
		if ( is_wp_error( $validation ) ) {
			return $validation;
		}

		$client_id     = $settings['client_id'];
		$client_secret = $settings['client_secret'];
		$header_name   = $settings['authorization_header_name'] ?? Constants::DEFAULT_AUTH_HEADER_NAME;

		$credentials = base64_encode( $client_id . ':' . $client_secret ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- The code is not used for obfuscation.

		return array(
			$header_name => 'Basic ' . $credentials,
		);
	}

	/**
	 * Validate auth settings
	 *
	 * @param array $settings Auth settings.
	 * @return bool|WP_Error True if valid, WP_Error if invalid
	 */
	public function validate_settings( $settings ) {
		if ( empty( $settings['client_id'] ) || empty( $settings['client_secret'] ) ) {
			return new WP_Error(
				'invalid_basic_auth_settings',
				'Invalid basic auth settings: missing client_id/client_secret',
				array( 'status' => 400 )
			);
		}

		return true;
	}
}
