<?php
/**
 * Single-option settings storage for the plugin (option name: cpecs_settings).
 */

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

class CPECS_Settings {

	const OPTION_KEY = 'cpecs_settings';

	public static function defaults() {
		return array(
			'enabled'            => true,
			'welcome_message'    => __( 'Hi there! How can we help you today?', 'capripio-easy-chat-support' ),
			'offline_message'    => __( 'We are currently offline. Leave a message and we will get back to you.', 'capripio-easy-chat-support' ),
			'widget_color'       => '#5b3df5',
			'widget_position'    => 'bottom-right', // bottom-right | bottom-left
			'business_hours_on'  => false,
			'business_hours'     => self::default_business_hours(),
			'timezone'           => 'site', // 'site' uses WP timezone setting
			'notify_email'       => get_option( 'admin_email' ),
			'notify_on_message'  => true,
			// Retention.
			'retention_enabled'  => false,
			'retention_days'     => 30, // used when retention_enabled is true
			'delete_data_on_uninstall' => false,
			// Branding backlink (off by default; site owner opts in).
			'show_branding'      => false,
		);
	}

	public static function default_business_hours() {
		$days  = array( 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun' );
		$hours = array();
		foreach ( $days as $day ) {
			$hours[ $day ] = array(
				'enabled' => in_array( $day, array( 'sat', 'sun' ), true ) ? false : true,
				'start'   => '09:00',
				'end'     => '17:00',
			);
		}
		return $hours;
	}

	public function get_all() {
		$saved = get_option( self::OPTION_KEY, array() );
		return wp_parse_args( $saved, self::defaults() );
	}

	public function get( $key, $fallback = null ) {
		$all = $this->get_all();
		return isset( $all[ $key ] ) ? $all[ $key ] : $fallback;
	}

	public function update( array $new_values ) {
		$current = $this->get_all();
		$merged  = array_merge( $current, $this->sanitize( $new_values, $current ) );
		update_option( self::OPTION_KEY, $merged );
		return $merged;
	}

	/**
	 * Sanitize incoming settings values against known keys/types.
	 */
	private function sanitize( array $input, array $current ) {
		$clean = array();

		if ( isset( $input['enabled'] ) ) {
			$clean['enabled'] = (bool) $input['enabled'];
		}
		if ( isset( $input['welcome_message'] ) ) {
			$clean['welcome_message'] = sanitize_textarea_field( $input['welcome_message'] );
		}
		if ( isset( $input['offline_message'] ) ) {
			$clean['offline_message'] = sanitize_textarea_field( $input['offline_message'] );
		}
		if ( isset( $input['widget_color'] ) ) {
			$clean['widget_color'] = sanitize_hex_color( $input['widget_color'] ) ? $input['widget_color'] : $current['widget_color'];
		}
		if ( isset( $input['widget_position'] ) ) {
			$clean['widget_position'] = in_array( $input['widget_position'], array( 'bottom-right', 'bottom-left' ), true )
				? $input['widget_position']
				: $current['widget_position'];
		}
		if ( isset( $input['business_hours_on'] ) ) {
			$clean['business_hours_on'] = (bool) $input['business_hours_on'];
		}
		if ( isset( $input['business_hours'] ) && is_array( $input['business_hours'] ) ) {
			$clean['business_hours'] = $this->sanitize_business_hours( $input['business_hours'] );
		}
		if ( isset( $input['notify_email'] ) ) {
			$clean['notify_email'] = sanitize_email( $input['notify_email'] );
		}
		if ( isset( $input['notify_on_message'] ) ) {
			$clean['notify_on_message'] = (bool) $input['notify_on_message'];
		}

		// Retention / message trimming.
		if ( isset( $input['retention_enabled'] ) ) {
			$clean['retention_enabled'] = (bool) $input['retention_enabled'];
		}
		if ( isset( $input['retention_days'] ) ) {
			$days = absint( $input['retention_days'] );
			// Guard rail: minimum 1 day so a mistake can't nuke everything instantly.
			$clean['retention_days'] = max( 1, $days );
		}
		if ( isset( $input['delete_data_on_uninstall'] ) ) {
			$clean['delete_data_on_uninstall'] = (bool) $input['delete_data_on_uninstall'];
		}
		if ( isset( $input['show_branding'] ) ) {
			$clean['show_branding'] = (bool) $input['show_branding'];
		}

		return $clean;
	}

	private function sanitize_business_hours( $hours ) {
		$clean = array();
		foreach ( self::default_business_hours() as $day => $default ) {
			if ( ! isset( $hours[ $day ] ) ) {
				$clean[ $day ] = $default;
				continue;
			}
			$row = $hours[ $day ];
			$clean[ $day ] = array(
				'enabled' => ! empty( $row['enabled'] ),
				'start'   => isset( $row['start'] ) ? sanitize_text_field( $row['start'] ) : $default['start'],
				'end'     => isset( $row['end'] ) ? sanitize_text_field( $row['end'] ) : $default['end'],
			);
		}
		return $clean;
	}

	/**
	 * Is "now" (site timezone) within configured business hours?
	 * Returns true if business hours are disabled (i.e. always "online").
	 */
	public function is_within_business_hours() {
		if ( ! $this->get( 'business_hours_on' ) ) {
			return true;
		}

		$hours    = $this->get( 'business_hours', self::default_business_hours() );
		$now      = current_datetime();
		$day_key  = strtolower( $now->format( 'D' ) ); // mon, tue, ...
		$day_key  = substr( $day_key, 0, 3 );

		if ( empty( $hours[ $day_key ]['enabled'] ) ) {
			return false;
		}

		$current_minutes = ( (int) $now->format( 'H' ) * 60 ) + (int) $now->format( 'i' );
		$start            = $this->time_to_minutes( $hours[ $day_key ]['start'] );
		$end              = $this->time_to_minutes( $hours[ $day_key ]['end'] );

		return $current_minutes >= $start && $current_minutes <= $end;
	}

	private function time_to_minutes( $hms ) {
		$parts = explode( ':', $hms );
		$h     = isset( $parts[0] ) ? (int) $parts[0] : 0;
		$m     = isset( $parts[1] ) ? (int) $parts[1] : 0;
		return ( $h * 60 ) + $m;
	}
}
