<?php
/**
 * AI-powered analytics via the OpenAI API (BYOK).
 *
 * @package MerchantKits\AttendanceManager
 */

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

/**
 * Compiles attendance data and generates AI insights through OpenAI.
 */
class MKAM_AI_Insights {

	/**
	 * Generate a cached monthly attendance summary.
	 *
	 * @param int $year  Year.
	 * @param int $month Month (1-12).
	 * @return string|WP_Error
	 */
	public function monthly_summary( $year, $month ) {
		$year  = absint( $year );
		$month = min( 12, max( 1, absint( $month ) ) );

		$cache_key = sprintf( 'mkam_ai_summary_%04d_%02d', $year, $month );
		$cached    = get_transient( $cache_key );

		if ( false !== $cached ) {
			return $cached;
		}

		$from = sprintf( '%04d-%02d-01', $year, $month );
		$to   = gmdate( 'Y-m-t', strtotime( $from ) );

		$data = $this->compile_employee_stats( $from, $to );

		if ( empty( $data ) ) {
			return new WP_Error( 'mkam_no_data', __( 'No attendance data found for this period.', 'merchantkits-attendance-manager' ) );
		}

		$prompt = sprintf(
			"You are an HR analytics assistant. Analyze this attendance data for %s and provide:\n"
			. "1. A brief executive summary (3-4 sentences)\n"
			. "2. Key observations (attendance patterns, frequently late employees, overtime trends)\n"
			. "3. Recommendations for improvement\n"
			. "4. Employees who deserve recognition for perfect attendance\n\n"
			. "Data: %s\n\n"
			. 'Respond in plain text with clear sections. Be specific with names and numbers.',
			gmdate( 'F Y', strtotime( $from ) ),
			wp_json_encode( $data )
		);

		$prompt = apply_filters( 'mkam_ai_prompt', $prompt, 'summary' );

		$result = $this->call_openai( $prompt, 1000 );

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		set_transient( $cache_key, $result, DAY_IN_SECONDS );

		do_action( 'mkam_ai_insight_generated', 'summary', $data );

		return $result;
	}

	/**
	 * Detect absence patterns over a date range.
	 *
	 * @param string $from Y-m-d.
	 * @param string $to   Y-m-d.
	 * @return string|WP_Error
	 */
	public function detect_patterns( $from, $to ) {
		$from = sanitize_text_field( $from );
		$to   = sanitize_text_field( $to );

		$cache_key = 'mkam_ai_patterns_' . md5( $from . $to );
		$cached    = get_transient( $cache_key );

		if ( false !== $cached ) {
			return $cached;
		}

		$data = $this->compile_absence_data( $from, $to );

		if ( empty( $data['by_weekday'] ) ) {
			return new WP_Error( 'mkam_no_data', __( 'No attendance data found for this period.', 'merchantkits-attendance-manager' ) );
		}

		$prompt = sprintf(
			"You are an HR analytics assistant. Analyze the following absence data covering %s to %s. "
			. "Identify which days of the week have the highest absence, employees who are frequently absent "
			. "on Mondays or Fridays, and any other notable patterns. Provide actionable recommendations.\n\n"
			. "Data: %s\n\nRespond in plain text with clear sections.",
			$from,
			$to,
			wp_json_encode( $data )
		);

		$prompt = apply_filters( 'mkam_ai_prompt', $prompt, 'patterns' );

		$result = $this->call_openai( $prompt, 1000 );

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		set_transient( $cache_key, $result, DAY_IN_SECONDS );

		do_action( 'mkam_ai_insight_generated', 'patterns', $data );

		return $result;
	}

	/**
	 * Generate a short digest summary from raw records (used by cron).
	 *
	 * @param array  $records Attendance rows.
	 * @param string $from    Range start.
	 * @param string $to      Range end.
	 * @return string|WP_Error
	 */
	public function generate_digest_summary( $records, $from, $to ) {
		if ( empty( $records ) ) {
			return '';
		}

		$counts = array();
		foreach ( $records as $record ) {
			$status            = $record['status'];
			$counts[ $status ] = isset( $counts[ $status ] ) ? $counts[ $status ] + 1 : 1;
		}

		$prompt = sprintf(
			'You are an HR analytics assistant. Write a concise weekly attendance digest (3-4 sentences) for the period %s to %s based on these status counts: %s.',
			$from,
			$to,
			wp_json_encode( $counts )
		);

		return $this->call_openai( apply_filters( 'mkam_ai_prompt', $prompt, 'digest' ), 400 );
	}

	/**
	 * Compile per-employee attendance stats for a range.
	 *
	 * @param string $from Y-m-d.
	 * @param string $to   Y-m-d.
	 * @return array
	 */
	private function compile_employee_stats( $from, $to ) {
		$employees = MKAM_Employee::query( array( 'status' => 'active' ) );
		$out       = array();

		foreach ( $employees as $employee ) {
			$records = MKAM_Attendance::query(
				array(
					'employee_id' => $employee['id'],
					'date_from'   => $from,
					'date_to'     => $to,
				)
			);

			$stats = array(
				'name'     => MKAM_Employee::full_name( $employee ),
				'present'  => 0,
				'absent'   => 0,
				'late'     => 0,
				'on_leave' => 0,
				'overtime' => 0.0,
			);

			foreach ( $records as $record ) {
				if ( isset( $stats[ $record['status'] ] ) ) {
					$stats[ $record['status'] ]++;
				}
				$stats['overtime'] += (float) $record['overtime_hours'];
			}

			$out[] = $stats;
		}

		return $out;
	}

	/**
	 * Compile absence data grouped by weekday and employee.
	 *
	 * @param string $from Y-m-d.
	 * @param string $to   Y-m-d.
	 * @return array
	 */
	private function compile_absence_data( $from, $to ) {
		$records = MKAM_Attendance::query(
			array(
				'status'    => 'absent',
				'date_from' => $from,
				'date_to'   => $to,
			)
		);

		$by_weekday  = array();
		$by_employee = array();

		foreach ( $records as $record ) {
			$weekday               = gmdate( 'l', strtotime( $record['date'] ) );
			$by_weekday[ $weekday ] = isset( $by_weekday[ $weekday ] ) ? $by_weekday[ $weekday ] + 1 : 1;

			$employee = MKAM_Employee::get( $record['employee_id'] );
			$name     = $employee ? MKAM_Employee::full_name( $employee ) : (string) $record['employee_id'];
			$by_employee[ $name ] = isset( $by_employee[ $name ] ) ? $by_employee[ $name ] + 1 : 1;
		}

		return array(
			'by_weekday'  => $by_weekday,
			'by_employee' => $by_employee,
		);
	}

	/**
	 * Call the OpenAI chat completions API.
	 *
	 * @param string $prompt     User prompt.
	 * @param int    $max_tokens Maximum response tokens.
	 * @return string|WP_Error
	 */
	public function call_openai( $prompt, $max_tokens = 1000 ) {
		$api_key = get_option( 'mkam_openai_api_key', '' );

		if ( empty( $api_key ) ) {
			return new WP_Error( 'mkam_no_api_key', __( 'OpenAI API key not configured.', 'merchantkits-attendance-manager' ) );
		}

		$model = get_option( 'mkam_ai_model', 'gpt-4o-mini' );

		$response = wp_remote_post(
			'https://api.openai.com/v1/chat/completions',
			array(
				'timeout' => 30,
				'headers' => array(
					'Authorization' => 'Bearer ' . $api_key,
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode(
					array(
						'model'       => $model,
						'messages'    => array(
							array(
								'role'    => 'system',
								'content' => 'You are an HR analytics assistant for a small business. Provide clear, actionable insights.',
							),
							array(
								'role'    => 'user',
								'content' => $prompt,
							),
						),
						'max_tokens'  => absint( $max_tokens ),
						'temperature' => 0.3,
					)
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( isset( $body['error'] ) ) {
			return new WP_Error( 'mkam_openai_error', $body['error']['message'] );
		}

		return isset( $body['choices'][0]['message']['content'] ) ? $body['choices'][0]['message']['content'] : '';
	}

	/**
	 * AJAX: test the configured API key with a minimal request.
	 *
	 * @return void
	 */
	public function ajax_test_connection() {
		check_ajax_referer( 'mkam_admin', 'nonce' );

		if ( ! current_user_can( MKAM_Core::admin_capability() ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'merchantkits-attendance-manager' ) ), 403 );
		}

		$result = $this->call_openai( 'Reply with the single word: OK.', 5 );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( array( 'message' => __( 'Connection successful.', 'merchantkits-attendance-manager' ) ) );
	}
}
