<?php
/**
 * Settings storage and helpers.
 *
 * @package TradeSchoolManager
 */

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

class TSM_Settings {

	const OPTION = 'tsm_settings';

	public static function get_all() {
		return get_option( self::OPTION, array() );
	}

	public static function update( array $data ) {
		$existing = self::get_all();
		$merged   = array_merge( $existing, $data );
		update_option( self::OPTION, $merged );
		return $merged;
	}

	/**
	 * Sanitize POSTed settings. Only fields actually present in $post are returned,
	 * so a per-tab form submit doesn't wipe values from other tabs (the update()
	 * method merges the result into existing options).
	 */
	public static function sanitize_post( $post ) {
		$out = array();
		$set = function( $key, $cb ) use ( $post, &$out ) {
			if ( array_key_exists( $key, $post ) ) {
				$out[ $key ] = $cb( $post[ $key ] );
			}
		};

		$set( 'school_name',   function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'school_logo',   function( $v ) { return esc_url_raw( wp_unslash( $v ) ); } );
		$set( 'brand_color',   function( $v ) { return sanitize_hex_color( wp_unslash( $v ) ) ?: '#1f6feb'; } );
		// v1.19.0  -  Portal Theme.
		$set( 'portal_theme_preset',   function( $v ) { return sanitize_key( wp_unslash( $v ) ); } );
		$set( 'portal_layout',         function( $v ) { $k = sanitize_key( wp_unslash( $v ) ); return in_array( $k, array( 'profile', 'console', 'command' ), true ) ? $k : 'console'; } );
		$set( 'portal_color_primary',  function( $v ) { $h = sanitize_hex_color( wp_unslash( $v ) ); return $h ?: ''; } );
		$set( 'portal_color_accent',   function( $v ) { $h = sanitize_hex_color( wp_unslash( $v ) ); return $h ?: ''; } );
		$set( 'portal_color_surface',  function( $v ) { $h = sanitize_hex_color( wp_unslash( $v ) ); return $h ?: ''; } );
		$set( 'portal_color_ink',      function( $v ) { $h = sanitize_hex_color( wp_unslash( $v ) ); return $h ?: ''; } );
		$set( 'grading_scale', function( $v ) { return sanitize_textarea_field( wp_unslash( $v ) ); } );
		$set( 'application_notify_email', function( $v ) { return sanitize_email( wp_unslash( $v ) ); } );

		$set( 'student_login_page',  function( $v ) { return absint( $v ); } );
		$set( 'student_portal_page', function( $v ) { return absint( $v ); } );
		$set( 'teacher_login_page',  function( $v ) { return absint( $v ); } );
		$set( 'teacher_portal_page', function( $v ) { return absint( $v ); } );

		// Terminology  -  handled as a sub-array; only set if any term_* posted.
		if ( isset( $post['term_class'] ) || isset( $post['term_student'] ) || isset( $post['term_teacher'] ) ) {
			$existing = self::get_all();
			$existing_terms = isset( $existing['terminology'] ) && is_array( $existing['terminology'] ) ? $existing['terminology'] : array();
			$out['terminology'] = array(
				'class'   => isset( $post['term_class'] )   ? sanitize_text_field( wp_unslash( $post['term_class'] ) )   : ( $existing_terms['class']   ?? 'Class' ),
				'student' => isset( $post['term_student'] ) ? sanitize_text_field( wp_unslash( $post['term_student'] ) ) : ( $existing_terms['student'] ?? 'Student' ),
				'teacher' => isset( $post['term_teacher'] ) ? sanitize_text_field( wp_unslash( $post['term_teacher'] ) ) : ( $existing_terms['teacher'] ?? 'Teacher' ),
			);
		}

		$set( 'currency',            function( $v ) { return strtoupper( sanitize_text_field( wp_unslash( $v ) ) ); } );
		$set( 'currency_symbol',     function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'invoice_prefix',      function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'invoice_next_number', function( $v ) { return max( 1, absint( $v ) ); } );
		$set( 'tax_rate',            function( $v ) { return floatval( $v ); } );
		$set( 'tax_label',           function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'late_fee_amount',     function( $v ) { return floatval( $v ); } );
		$set( 'late_fee_grace_days', function( $v ) { return absint( $v ); } );
		$set( 'reminder_schedule',   function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'invoice_terms',       function( $v ) { return sanitize_textarea_field( wp_unslash( $v ) ); } );

		$set( 'stripe_mode',       function( $v ) { return 'live' === $v ? 'live' : 'test'; } );
		$set( 'stripe_test_pk',    function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'stripe_test_sk',    function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'stripe_test_whsec', function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'stripe_live_pk',    function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'stripe_live_sk',    function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );
		$set( 'stripe_live_whsec', function( $v ) { return sanitize_text_field( wp_unslash( $v ) ); } );

		// v1.10.26  -  Legal / Tuition Contracts.
		$set( 'contract_template_html',  function( $v ) { return wp_kses_post( wp_unslash( $v ) ); } );
		$set( 'contract_extra_clauses',  function( $v ) { return wp_kses_post( wp_unslash( $v ) ); } );
		$set( 'contract_esign_consent',  function( $v ) { return sanitize_textarea_field( wp_unslash( $v ) ); } );
		$set( 'contract_sign_page',      function( $v ) { return absint( $v ); } );

		return $out;
	}

	/* ---------- Convenience helpers (v1.6.0) ---------- */

	public static function currency_symbol() {
		return tsm_get_setting( 'currency_symbol', '$' );
	}

	public static function format_money( $amount ) {
		return self::currency_symbol() . number_format_i18n( (float) $amount, 2 );
	}

	public static function next_invoice_number() {
		$prefix = tsm_get_setting( 'invoice_prefix', 'INV-' );
		$num    = (int) tsm_get_setting( 'invoice_next_number', 1001 );
		self::update( array( 'invoice_next_number' => $num + 1 ) );
		return $prefix . str_pad( (string) $num, 5, '0', STR_PAD_LEFT );
	}

	public static function stripe_keys() {
		$mode = tsm_get_setting( 'stripe_mode', 'test' );
		return array(
			'mode'   => $mode,
			'pk'     => tsm_get_setting( 'live' === $mode ? 'stripe_live_pk' : 'stripe_test_pk', '' ),
			'sk'     => tsm_get_setting( 'live' === $mode ? 'stripe_live_sk' : 'stripe_test_sk', '' ),
			'whsec'  => tsm_get_setting( 'live' === $mode ? 'stripe_live_whsec' : 'stripe_test_whsec', '' ),
		);
	}
}
