<?php

namespace StoreEngine\Classes;

use StoreEngine\Classes\Exceptions\StoreEngineRuntimeException;
use StoreEngine\Utils\Constants;

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

class Logger {

	const SUCCESS = 'success';
	const WARNING = 'warning';
	const ERROR = 'error';
	const INFO = 'info';
	const DEBUG = 'debug';
	const EMERGENCY = 'emergency';
	const CRITICAL = 'critical';
	const ALERT = 'alert';

	public static function log( string $title, $content, string $status = 'success', string $module = 'system' ) {
		try {
			self::log_to_db( $title, $content, $status, $module );
		} catch ( \Throwable $t ) {
			error_log( 'Unable to write StoreEngine log data to database. Error: ' . $t->getMessage() );

			// Fallback.
			try {
				self::log_to_file( $title, $content, $status, $module );
			} catch ( \Throwable $t ) {
				error_log( 'Unable to write StoreEngine log data to log file. Error: ' . $t->getMessage() );
			}
		}
	}

	public static function log_to_db( string $title, $content, string $status = 'success', string $module = 'system' ) {
		$log = new LogItem();
		$log->set_props( [
			'date'    => current_time( 'mysql' ),
			'module'  => $module,
			'title'   => $title,
			'status'  => $status,
			'content' => is_array( $content ) || is_object( $content ) ? json_encode( $content ) : $content,
		] );

		$log->save();
	}

	public static function log_to_file( string $title, $content, string $status = 'success', string $module = 'system' ) {
		if ( ! defined( 'STOREENGINE_LOGS_DIR' ) ) {
			throw new StoreEngineRuntimeException( 'Logs directory is not defined.' );
		}

		if ( ! file_exists( STOREENGINE_LOGS_DIR ) ) {
			wp_mkdir_p( STOREENGINE_LOGS_DIR );
		}

		$message = is_string( $content ) ? $title . $content : $title;

		if ( ! is_scalar( $content ) ) {
			$message .= PHP_EOL . json_encode( $content );
		}

		$log_file  = STOREENGINE_LOGS_DIR . 'storeengine-' . $module . '-' . date( 'Y-m-d' ) . '.log';
		$timestamp = gmdate( 'c' );
		$module    = strtoupper( $module );
		$status    = strtoupper( $status );
		$message   = "[$timestamp] – [$module] [$status] $message";

		if ( ! file_exists( $log_file ) ) {
			$handle = @fopen( $log_file, 'w+' );
			if ( is_resource( $handle ) ) {
				@fclose( $handle );

				if ( Constants::is_defined( 'FS_CHMOD_FILE' ) ) {
					@chmod( $log_file, FS_CHMOD_FILE );
				}
			}
		}

		$handle = @fopen( $log_file, 'a' );
		if ( is_resource( $handle ) ) {
			@fwrite( $handle, $message . PHP_EOL );
			@fclose( $handle );
		}
	}
}
