<?php
namespace BayarCash\GiveWP;

class DataStore
{
	private function note_exists($payment_id, $exchange_reference, $new_status): bool {
		global $wpdb;

		// Get current payment status
		$current_status = get_post_meta($payment_id, '_give_payment_status', true);

		// If current status is failed and new status is complete, allow the update
		if ($current_status === 'failed' && $new_status === 'complete') {
			return false;
		}

		$query = $wpdb->prepare(
			"SELECT COUNT(*) FROM {$wpdb->prefix}give_comments 
             WHERE comment_parent = %d 
             AND comment_content LIKE %s
             AND comment_content LIKE %s",
			$payment_id,
			'%' . $wpdb->esc_like($exchange_reference) . '%',
			'%Transaction Status: ' . $wpdb->esc_like($new_status) . '%'
		);

		error_log('Checking for duplicate note with query: ' . $query);

		$count = $wpdb->get_var($query);
		error_log('Found notes count: ' . var_export($count, true));

		return $count > 0;
	}

	public function update_payment_fpx($transaction_data)
	{
		if (!isset($transaction_data['order_number']) || !isset($transaction_data['status'])) {
			error_log('Missing order_number or status in transaction data');
			return;
		}

		$payment_id = $transaction_data['order_number'];
		$status_number = $transaction_data['status'];

		$status_list = ['new', 'pending', 'unsuccessful', 'successful', 'cancelled'];
		$status_name = $status_list[$status_number] ?? 'unknown';

		$form_url = Give()->payment_meta->get_meta($payment_id, '_give_current_url', true);
		$request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '';

		$payment_note_arr = static function ($records, $status = '') {
			$amount = number_format((float)$records['amount'], 2, '.', '');
			return implode(' | ', [
				'Donation ID: '.$records['order_number'],
				'Exchange Reference Number: '.$records['exchange_reference_number'],
				'ID Number: '.$records['transaction_id'],
				'Transaction Status: '.$status,
				'Transaction Status Description: '.$records['status_description'],
				'Donor Bank Name: '.$records['payer_bank_name'],
				'Transaction Amount: '.$records['currency'].' '.$amount,
				'Donor Name: '.$records['payer_name'],
				'Donor Email: '.$records['payer_email']
			]);
		};

		// Map status names to payment statuses
		if ($status_name === 'successful') {
			$payment_status = 'complete';
		} elseif (in_array($status_name, ['unsuccessful', 'cancelled'], true)) {
			$payment_status = 'failed';
		} else {
			$payment_status = 'pending';
		}

		// Create note content
		$note_content = $payment_note_arr($transaction_data, $payment_status);

		// Check if this exact status update already exists
		if (!$this->note_exists($payment_id, $transaction_data['exchange_reference_number'], $payment_status)) {
			give_update_payment_status($payment_id, $payment_status);
			give_insert_payment_note($payment_id, $note_content);

			$log_content = $payment_status === 'pending'
				? 'The payment status of #' . $payment_id . ' is still not resolved yet.'
				: $note_content;

			debug_log([
				'caller'      => __METHOD__,
				'form-url'    => $form_url,
				'request-uri' => $request_uri,
				'content'     => $log_content,
			]);

			error_log('Payment ' . $payment_id . ' updated to ' . $payment_status . ' status');
		} else {
			error_log('Duplicate status update skipped for payment ' . $payment_id);
		}
	}
}