<?php
/**
 * File: Defaults/SettingsHelper.php
 * Default settings configuration
 */

namespace RadiusTheme\RadiusBooking\Helpers;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * Class SettingsHelper
 *
 * @package RadiusTheme\RadiusBooking\Helpers
 * @since 1.0.0
 * @author
 * @version 1.0.0
 * @see https://github.com/RadiusTheme/RadiusBooking/blob/master/includes/Helpers/SettingsHelper.php
 */
class SettingsHelper {

	/**
	 * Retrieves an array containing various configuration data and settings.
	 *
	 * @return array An associative array with keys representing configuration categories and values containing their respective data.
	 */
	public static function all(): array {
		$data = array(
			'statuses'          => self::statuses(),
			'dateTime'          => self::dateTime(),
			'restrictions'      => self::restrictions(),
			'bookingBuffer'     => self::bookingBuffer(),
			'currency'          => self::currency(),
			'phone'             => self::phone(),
			'logic'             => self::logic(),
			'permissions'       => self::permissions(),
			'staffPermissions'  => self::staffPermissions(),
			'auth'              => self::auth(),
			'security'          => self::security(),
			'pages'             => self::pages(),
			'display'           => self::display(),
			'business'          => self::business(),
			'integrations'      => self::integrations(),
			'weeklySchedule'    => self::weeklySchedule(),
			'customSchedules'   => array(),
			'holidays'          => array(),
			'languages'         => array( 'English', 'Assamese' ),
			'email'             => self::email(),
			'payment'           => self::payment(),
			'formCustomization' => self::formCustomization(),
			'serviceList'       => self::serviceList(),
			'modules'           => self::modules(),
		);

		return apply_filters( 'rtrb_settings', $data );
	}

	/**
	 * Retrieves an array of status configurations.
	 *
	 * @return array An associative array with keys representing status categories and values containing corresponding status values or lists.
	 */
	public static function statuses(): array {
		return array(
			'default'          => 'pending',
			'hiddenOnCalendar' => array( 'canceled' ),
		);
	}

	/**
	 * Provides configuration settings related to date and time formatting and representation.
	 *
	 * @return array An associative array containing date and time configuration options and their values.
	 */
	public static function dateTime(): array {
		return array(
			'timeSystem'             => '12h',
			'dateFormat'             => 'm/d/Y',
			'selectableInterval'     => 30,
			'showAppointmentEndTime' => true,
			'verboseDates'           => false,
			'numericMonth'           => true,
		);
	}

	/**
	 * Retrieves the restrictions for booking and scheduling.
	 *
	 * @return array An associative array containing keys such as 'earliest', 'latest', 'minCancelTime', 'minRescheduleTime', and 'maxFutureBookingsPerCustomer' with their respective time or value constraints.
	 */
	public static function restrictions(): array {
		return array(
			'earliest'                     => '+1 hour',
			'latest'                       => '+6 months',
			'minCancelTime'                => '+24 hours',
			'minRescheduleTime'            => '+12 hours',
			'maxFutureBookingsPerCustomer' => 0,
		);
	}

	/**
	 * Retrieves the configuration for the booking buffer.
	 *
	 * @return array An associative array containing keys such as 'useServiceDuration' and 'includeBufferTime', indicating whether the service duration and buffer time should be included in the booking process.
	 */
	public static function bookingBuffer(): array {
		return array(
			'useServiceDuration' => true,
			'includeBufferTime'  => true,
		);
	}

	/**
	 * Retrieves the currency settings and formatting details.
	 *
	 * @return array An associative array containing keys such as 'symbol', 'symbolPosition', 'thousand', 'decimal', 'decimals', and 'hideBreakdownIfZero' with their respective values specifying currency attributes and display formatting.
	 */
	public static function currency(): array {
		return array(
			'symbol'              => 'USD',
			'symbolPosition'      => 'before',
			'thousand'            => ',',
			'decimal'             => '.',
			'decimals'            => 2,
			'hideBreakdownIfZero' => true,
		);
	}

	/**
	 * Retrieves the configuration settings for phone-related options.
	 *
	 * @return array An associative array containing keys such as 'showAllCountries', 'defaultCountry', 'mandatory', 'validateIfRequired', 'rejectInvalidIfRequired', 'formatOnInput', and 'showDialCode', with their respective settings and values.
	 */
	public static function phone(): array {
		return array(
			'showAllCountries'        => true,
			'defaultCountry'          => 'US',
			'mandatory'               => false,
			'validateIfRequired'      => true,
			'rejectInvalidIfRequired' => true,
			'formatOnInput'           => false,
			'showDialCode'            => true,
		);
	}

	/**
	 * Provides configuration logic settings related to location and agent constraints.
	 *
	 * @return array An associative array containing keys like 'exclusiveLocation' and 'singleLocationPerAgent' with boolean values indicating their respective settings.
	 */
	public static function logic(): array {
		return array(
			'exclusiveLocation'      => true,
			'singleLocationPerAgent' => true,
		);
	}

	/**
	 * Retrieves the permissions related to booking configurations.
	 *
	 * @return array An associative array containing keys like 'multiServiceSameTimeslot' with boolean values indicating specific permission settings.
	 */
	public static function permissions(): array {
		return array(
			'multiServiceSameTimeslot' => false,
		);
	}

	/**
	 * Retrieves the staff/employee permission settings.
	 *
	 * Controls what employees can do from their dashboard panel.
	 *
	 * @return array An associative array of staff permission flags.
	 */
	public static function staffPermissions(): array {
		return array(
			'canEditService'      => true,
			'canCreateService'    => false,
			'canDeleteService'    => true,
			'canManageStaff'      => true,
			'canEditWorkSchedule' => true,
		);
	}

	/**
	 * Retrieves the authentication settings and configurations.
	 *
	 * @return array An associative array containing keys such as 'useWordPressUsers', 'requirePasswordOnRegister', 'removeLoginRegisterTabs', 'hideCreateAccountPrompt', and 'mandatoryEmail' with their respective boolean values indicating specific authentication behaviors.
	 */
	public static function auth(): array {
		return array(
			'useWordPressUsers'         => true,
			'allowCustomerRegistration' => true,
			'requirePasswordOnRegister' => true,
			'removeLoginRegisterTabs'   => false,
			'hideCreateAccountPrompt'   => false,
			'mandatoryEmail'            => true,
		);
	}

	/**
	 * Retrieves the security configuration settings.
	 *
	 * @return array An associative array containing keys such as 'enableRecaptcha', 'invisibleRecaptcha', 'recaptchaSiteKey', and 'recaptchaSecretKey' with their respective configurations for security features.
	 */
	public static function security(): array {
		return array(
			'enableRecaptcha'    => false,
			'invisibleRecaptcha' => true,
			'recaptchaSiteKey'   => '',
			'recaptchaSecretKey' => '',
		);
	}

	/**
	 * Retrieves an array of page URLs for a customer.
	 *
	 * @return array Returns an associative array where keys represent page identifiers and values are the corresponding URLs.
	 */
	public static function pages(): array {
		return array(
			'bookingFormPage' => 0,
			'myBookingPage'   => 0,
		);
	}

	/**
	 * Provides display configuration settings.
	 *
	 * @return array Returns an associative array where keys represent configuration options and values are their respective settings.
	 */
	public static function display(): array {
		return array(
			'frontendItemsPerPage' => 10,
			'backendItemsPerPage'  => 20,
			'defaultBackendPage'   => 'appointments',
			'showClientTimezone'   => true,
			'showAddToCalendar'    => true,
		);
	}

	/**
	 * Retrieves an array containing business details.
	 *
	 * @return array Returns an associative array where the keys represent business attributes and the values are their corresponding details.
	 */
	public static function business(): array {
		return array(
			'logoUrl'     => '',
			'companyName' => '',
			'phone'       => '',
			'address'     => '',
		);
	}

	/**
	 * Retrieves the email sender configuration settings.
	 *
	 * @return array An associative array containing email sender settings such as senderName, senderEmail, and replyToEmail.
	 */
	public static function email(): array {
		return array(
			'senderName'   => get_bloginfo( 'name' ),
			'senderEmail'  => get_option( 'admin_email' ),
			'replyToEmail' => '',
		);
	}

	/**
	 * Retrieves an array of integration settings and related configurations.
	 *
	 * @return array Returns an associative array containing integration details for various services such as Google Maps, IP location,
	 * Zoom, Google Calendar, and Apple Calendar. Settings include API keys, paths, feature flags, and configuration parameters specific to each service.
	 */
	public static function integrations(): array {
		$data = array(
			'googleMapApiKey' => '',
			'ipLocateApiKey'  => '',
			'redirectUrl'     => '',
			'attachmentPath'  => '/wp-content/uploads/bookings',
			'googleCalendar'  => array(
				'enabled'        => false,
				'clientId'       => '',
				'clientSecret'   => '',
				'redirectUri'    => admin_url( 'admin.php?page=radius-booking#/settings' ),
				'twoWaySync'     => false,
				'syncOnCreate'   => true,
				'syncOnUpdate'   => true,
				'syncOnDelete'   => true,
				'blockTimeSlots' => false,
				'calendarId'     => 'primary',
				'eventColor'     => '9',
			),
			'classifiedListing' => array(
				'enabled'            => false,
				'listingMappingMode' => 'service',
				'autoCreateEmployee' => true,
				'defaultDuration'    => 60,
				'defaultCategory'    => 0,
				'defaultServiceName' => __( 'Consultation', 'radius-booking' ),
				'syncPrice'          => true,
				'syncDescription'    => true,
				'bookNowButtonText'  => __( 'Book Now', 'radius-booking' ),
			),
		);

		return apply_filters( 'rtrb_integrations', $data );
	}

	/**
	 * Retrieves the tax configuration settings.
	 *
	 * @return array Returns an associative array containing tax-related settings such as enabled status, rate, and whether it is inclusive.
	 */
	public static function tax(): array {
		return array(
			'enabled'   => false,
			'rate'      => 0,
			'inclusive' => false,
			'label'     => 'Tax',
		);
	}

	/**
	 * Retrieves the weekly schedule with operational details for each day.
	 *
	 * @return array Returns an associative array where keys represent the days of the week,
	 *               and values are sub-arrays containing the day's operational status, start time, and end time.
	 */
	public static function weeklySchedule(): array {
		return array(
			'monday'    => array(
				'enabled' => true,
				'start'   => '09:00',
				'end'     => '17:00',
			),
			'tuesday'   => array(
				'enabled' => true,
				'start'   => '09:00',
				'end'     => '17:00',
			),
			'wednesday' => array(
				'enabled' => true,
				'start'   => '09:00',
				'end'     => '17:00',
			),
			'thursday'  => array(
				'enabled' => true,
				'start'   => '09:00',
				'end'     => '17:00',
			),
			'friday'    => array(
				'enabled' => true,
				'start'   => '09:00',
				'end'     => '17:00',
			),
			'saturday'  => array(
				'enabled' => true,
				'start'   => '09:00',
				'end'     => '17:00',
			),
			'sunday'    => array(
				'enabled' => true,
				'start'   => '09:00',
				'end'     => '17:00',
			),
		);
	}

	/**
	 * Retrieves an array of payment methods and their configuration details.
	 *
	 * @return array Returns an associative array where keys represent payment method identifiers and values contain their respective settings, such as enable status, label, and API keys.
	 */
	public static function payment(): array {
		$data = array(
			'paypal'  => array(
				'enabled'       => false,
				'testMode'      => true,
				'liveClientId'  => '',
				'liveSecretKey' => '',
				'testClientId'  => '',
				'testSecretKey' => '',
			),
			'offline' => array(
				'enabled'      => true,
				'label'        => 'Pay at venue',
				'instructions' => 'Please bring payment to your appointment. We accept cash, check, and credit cards.',
			),
		);

		return apply_filters( 'rtrb_payment_methods', $data );
	}

	/**
	 * Retrieves the form customization settings for the booking form appearance and labels.
	 *
	 * @return array An associative array containing design, labels, buttons, and toggles settings.
	 */
	public static function formCustomization(): array {
		return array(
			'design'  => array(
				'primaryColor'         => '#0040ff',
				'secondaryColor'       => '#E2E8F0',
				'backgroundColor'      => '#FFFFFF',
				'textColor'            => '#323E5B',
				'sidebarColor'         => '',
				'stepButtonColor'      => '#00154C',
				'stepButtonHoverColor' => '#062576',
				'borderColor'          => '#DAE0E5',
				'fontFamily'           => 'Inter, ui-sans-serif, system-ui',
				'borderRadius'         => '0.75rem',
				'sidebarImageUrl'      => '',
			),
			'labels'  => array(
				'services'     => array(
					'heading'             => 'Easily book your appointments & Get the Service you deserve.',
					'serviceLabel'        => 'Which Service you want to take',
					'locationLabel'       => 'Location',
					'staffLabel'          => 'Choose a Staff',
					'servicePlaceholder'  => 'Select service',
					'locationPlaceholder' => 'Select location',
					'staffPlaceholder'    => 'Select staff',
				),
				'datetime'     => array(
					'heading'         => 'Date & Time Selection',
					'subheading'      => 'Select your appointment date and time',
					'loadingText'     => 'Loading available dates...',
					'noAvailableText' => 'No available dates found',
				),
				'timeslot'     => array(
					'heading'                => 'Available Time Slots',
					'subheading'             => 'Select your appointment date and time',
					'loadingText'            => 'Loading time slots...',
					'noSlotsText'            => 'No available time slots for the selected date.',
					'bringingAnyoneLabel'    => 'Bringing Anyone?',
					'bringingAnyoneSubLabel' => 'Add extra people to your booking',
				),
				'details'      => array(
					'heading'             => 'Customer Details',
					'subheading'          => 'Customer Information',
					'fullNameLabel'       => 'Full Name',
					'fullNamePlaceholder' => 'Enter name here ...',
					'phoneLabel'          => 'Phone number',
					'emailLabel'          => 'E-mail',
					'emailPlaceholder'    => 'Enter e-mail...',
					'noteLabel'           => 'Note',
					'notePlaceholder'     => 'Add any additional notes...',
				),
				'payment'      => array(
					'heading'      => 'Payment',
					'subheading'   => 'Payment Summary',
					'summaryTitle' => 'Appointment summary',
				),
				'checkout'     => array(
					'heading'            => 'Checkout',
					'subheading'         => 'Make your payment',
					'paymentMethodTitle' => 'Payment method',
				),
				'confirmation' => array(
					'heading'      => 'Appointment Confirmed',
					'subheading'   => 'We Look Forward To Seeing You.',
					'detailsTitle' => 'Appointment Details',
				),
				'sidebar'      => array(
					'summaryTitle'  => 'Summary:',
					'customerTitle' => 'Customer:',
					'helpTitle'     => 'Questions?',
					'helpText'      => 'Call %s for help',
				),
			),
			'buttons' => array(
				'nextText'       => 'Next',
				'backText'       => 'Back',
				'confirmText'    => 'Continue',
				'processingText' => 'Processing…',
			),
			'toggles' => array(
				'showNoteField'       => true,
				'showSidebar'         => true,
				'showSidebarImage'    => true,
				'showCalendarExport'  => true,
				'allowBackNavigation' => true,
			),
		);
	}

	/**
	 * Retrieves the service list shortcode display settings.
	 *
	 * @return array An associative array containing layout, pagination, and design settings.
	 */
	public static function serviceList(): array {
		return array(
			'layout'             => 'grid',
			'columns'            => 3,
			'perPage'            => 9,
			'showImage'          => true,
			'showPrice'          => true,
			'showDuration'       => true,
			'showCategory'       => true,
			'showDescription'    => true,
			'showCategoryFilter' => true,
			'showStaff'          => true,
			'buttonText'         => 'Book Now',
			'primaryColor'       => '#0040ff',
			'cardRadius'         => '0.75rem',
		);
	}

	/**
	 * Retrieves the module activation settings.
	 *
	 * @since 1.2.0
	 *
	 * @return array An associative array of module names and their enabled status.
	 */
	public static function modules(): array {
		return array(
			'service' => true,
			'meeting' => false,
			'event'   => false,
		);
	}

	/**
	 * Retrieves a specific setting based on a given key.
	 *
	 * @param string $key The key identifying the setting to retrieve.
	 *
	 * @return mixed Returns the value of the setting if found, or a default value if the setting does not exist.
	 */
	public static function get_setting( $key ) {
		if ( method_exists( static::class, $key ) ) {
			$default = self::$key();
		} else {
			// Fallback to filtered defaults from all() for pro-added settings.
			$all_defaults = self::all();
			$default      = $all_defaults[ $key ] ?? array();
		}

		$option_key = 'rtrb_' . $key . '_settings';
		$saved      = get_option( $option_key, $default );

		// Merge saved values with defaults so newly added keys are always available.
		if ( is_array( $default ) && is_array( $saved ) ) {
			return wp_parse_args( $saved, $default );
		}
		return $saved;
	}
}
