<?php

namespace PixelioCartAbandonRecoveryMore\Frontend\Repositories;


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

use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

class Pixelio_Cart_Abandon_Recovery_More_Email_Logs_Repository
{
	private $wpdb;
	private string $table;
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;

	public function __construct($pixelio_wordpress_wrapper)
	{
		$this->wpdb = $pixelio_wordpress_wrapper->pixelio_get_wpdb();
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->table = $this->wpdb->prefix . Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_db_prefix . 'email_logs';
	}


	/**
	 * Get all emails
	 */
	public function pixelio_get_all_emails(?int $limit = null): ?array
	{
		$sql = "SELECT * FROM {$this->table} ORDER BY sent_at DESC";

		if ($limit) {
			$sql .= $this->wpdb->prepare(" LIMIT %d", $limit);
		}

		return $this->wpdb->get_results($sql);
	}

	/**
	 * Get email by ID
	 */
	public function pixelio_get_email_by_id(int $id): ?array
	{
		if ($id <= 0) {
			return null;
		}

		return $this->wpdb->get_row(
			$this->wpdb->prepare(
				"SELECT * FROM {$this->table} WHERE id = %d",
				$id
			),
			ARRAY_A
		);
	}

	public function pixelio_email_is_already_sent_for_wishlist_email(
		string $email,
		int    $type_of_email
	): bool
	{

		$count = $this->wpdb->get_var(
			$this->wpdb->prepare(
				"
			SELECT COUNT(id)
			FROM {$this->table}
			 WHERE recipient = %s
			 AND type = %d",
				$email,
				$type_of_email
			)
		);

		return (int) $count > 0;
	}

	/**
	 * Get unsynced emails
	 */
	public function get_not_yet_synced(): ?array
	{
		return $this->wpdb->get_results(
			$this->wpdb->prepare(
				"SELECT * FROM {$this->table} WHERE synced = %d",
				0
			)
		);
	}

	/**
	 * Mark emails as synced
	 */
	public function synced(array $items): bool
	{
		if (!$items) {
			return false;
		}

		foreach ($items as $item) {

			if (!isset($item->id)) {
				continue;
			}

			$this->wpdb->update(
				$this->table,
				['synced' => 1],
				['id' => (int)$item->id],
				['%d'],
				['%d']
			);
		}

		return true;
	}

	/**
	 * Insert email log
	 */
	public function pixelio_add_email(
		int    $cart_id,
		string $subject,
		string $recipient,
		int    $template_id,
		int    $type = 1
	): int|false
	{

		$inserted = $this->wpdb->insert(
			$this->table,
			[
				'cart_id' => $cart_id,
				'sent_at' => $this->pixelio_wordpress_wrapper->pixelio_current_time(),
				'template_id' => $template_id,
				'subject' => $subject,
				'type' => $type,
				'recipient' => $recipient,
			],
			[
				'%d',
				'%s',
				'%d',
				'%s',
				'%d',
				'%s'
			]
		);

		return $inserted ? $this->wpdb->insert_id : false;
	}
}
