<?php

namespace Bookingor\Backend\Controller\Notification;

use Bookingor\Integrations\Email\EmailNotification;
use Bookingor\Helper\HelperControl;

class NotificationControl
{

	private static $bookingorDb;
	/**
	 * Database table prefix for booking-related tables.
	 *
	 * @var string
	 */
	public static $dp_prefix = "bookingor_";
	/**
	 * Stores a collection of all email addresses retrieved from the database.
	 *
	 * @var array|null
	 */
	public static $get_all_emails;
	/**
	 * Retrieve a list of all email notifications from the database.
	 *
	 * This method returns a list of all email notifications with their details.
	 * The list includes the email's ID, name, name action, subject, text, send to,
	 * type, paid amount, tax charges, coupon ID, book date, book time, and status.
	 *
	 * @return array List of all email notifications with their details.
	 */
	public static function bp_get_emails_all()
	{
		global $wpdb;
		self::$bookingorDb = $wpdb;
		$email_notification = $wpdb->prefix . self::$dp_prefix . 'notifications';
		$query = "SELECT id, name_action, name, subject, text, send_to, type, paid_amount, tax_charges, coupon_id, book_date, book_time, send_on_time, status FROM %1\$s where type = 'email'";
		return self::$get_all_emails = self::$bookingorDb->get_results(self::$bookingorDb->prepare($query, $email_notification));
	}
	/**
	 * Update email notification in the database.
	 *
	 * This method updates an email notification in the database with the
	 * provided subject and text.
	 *
	 * @since 1.0.0
	 */
	public function bp_notification_email_update()
	{
		global $wpdb;
		self::$bookingorDb = $wpdb;
		$email_notification = $wpdb->prefix . self::$dp_prefix . 'notifications';
		if (isset($_REQUEST['action'])) {


			if (isset($_POST['nonce'])) {
				if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
					$response = [
						'status' => htmlspecialchars('error'),
						'message' => htmlspecialchars('Nonce verification failed.')
					];
					echo wp_json_encode($response);
					exit;
				}
			}
			if (!current_user_can('manage_options')) {
				$response = [
					'status' => htmlspecialchars('error'),
					'message' => htmlspecialchars('You do not have permission.')
				];
				echo wp_json_encode($response);
				die();
			}

			$email_get_id = sanitize_text_field(wp_unslash($_POST['email_id'] ?? ""));
			$email_subject = sanitize_text_field(wp_unslash($_POST['subject'] ?? ""));
			$email_content = wp_kses_post(wp_unslash($_POST['body'] ?? ""));
			$email_status = sanitize_text_field(wp_unslash($_POST['status'] ?? "0"));

			$data_to_update = array(
				'subject' => $email_subject,
				'text' => $email_content,
				'status' => $email_status,
			);
			if (isset($_POST['send_on_time'])) {
				$data_to_update['send_on_time'] = sanitize_text_field(wp_unslash($_POST['send_on_time']));
			}
			// approved
			self::$bookingorDb->update(
				$email_notification,
				$data_to_update,
				array('id' => $email_get_id)
			);
			$response = [
				'status' => htmlspecialchars('success'),
				'message' => htmlspecialchars('Notification Updated Successfully')
			];
			echo wp_json_encode($response);
			exit;
		}
	}

	/**
	 * Schedule the next-day reminder cron job.
	 */
	public function bookingor_schedule_reminder_cron()
	{
		if (!wp_next_scheduled('bookingor_send_reminders_cron_hook')) {
			wp_schedule_event(time(), 'hourly', 'bookingor_send_reminders_cron_hook');
		}
	}

	/**
	 * Cron callback to send Next Day Reminders automatically.
	 */
	public function bookingor_send_reminders_callback()
	{
		global $wpdb;
		$prefix = $wpdb->prefix . self::$dp_prefix;

		$current_timestamp = current_time('timestamp');
		$current_time = date('H:i', $current_timestamp);

		// Query active next-day reminder templates
		$reminder_templates = $wpdb->get_results(
			"SELECT * FROM {$prefix}notifications WHERE name_action IN ('customer_email_next_day_reminder', 'employee_email_next_day_reminder') AND type = 'email' AND status = 1"
		);

		if (empty($reminder_templates)) {
			return;
		}

		foreach ($reminder_templates as $template) {
			$send_on_time = !empty($template->send_on_time) ? substr($template->send_on_time, 0, 5) : '09:00';
			
			// If the current time has not reached the scheduled send_on_time yet, skip sending for this template
			if ($current_time < $send_on_time) {
				continue;
			}

			// Tomorrow's date
			$tomorrow = date('Y-m-d', strtotime('+1 day', $current_timestamp));

			// Fetch all appointments for tomorrow
			$appointments = $wpdb->get_results($wpdb->prepare(
				"SELECT * FROM {$prefix}booked_appointment WHERE picked_date = %s AND appoint_status IN ('approved', 'confirmed')",
				$tomorrow
			));

			foreach ($appointments as $appt) {
				// Check if we already sent this reminder
				$already_sent = $wpdb->get_var($wpdb->prepare(
					"SELECT COUNT(*) FROM {$prefix}notification_log WHERE appoint_get_id = %d AND name_action = %s",
					$appt->book_id,
					$template->name_action
				));

				if ($already_sent > 0) {
					continue;
				}

				// Load booking placeholder data
				$bookingData = HelperControl::get_last_booking_data($appt->book_id);
				if (empty($bookingData)) {
					continue;
				}

				// Send email
				$to_email = '';
				if ($template->name_action === 'customer_email_next_day_reminder') {
					$to_email = isset($bookingData['customerString'][3]) ? $bookingData['customerString'][3] : '';
				} else if ($template->name_action === 'employee_email_next_day_reminder') {
					$to_email = isset($bookingData['staffString'][2]) ? $bookingData['staffString'][2] : '';
				}

				if (empty($to_email)) {
					continue;
				}

				// Parse subject and body placeholders
				$subject = EmailNotification::string_Placeholder_variable(
					$bookingData['categoryString'],
					$bookingData['serviceString'],
					$bookingData['staffString'],
					$bookingData['customerString'],
					$bookingData['bookedString'],
					$bookingData['locationString'],
					$bookingData['businessString'],
					$template->subject
				);

				$body = EmailNotification::string_Placeholder_variable(
					$bookingData['categoryString'],
					$bookingData['serviceString'],
					$bookingData['staffString'],
					$bookingData['customerString'],
					$bookingData['bookedString'],
					$bookingData['locationString'],
					$bookingData['businessString'],
					$template->text
				);

				EmailNotification::sendEmail($to_email, $subject, $body);

				// Log notification in notification_log table
				$wpdb->insert(
					"{$prefix}notification_log",
					array(
						'name_action' => $template->name_action,
						'notification_get_id' => $template->id,
						'customer_get_id' => $appt->customer_get_id,
						'employee_get_id' => $appt->staff_get_id,
						'appoint_get_id' => $appt->book_id,
						'created_at' => current_time('mysql'),
					)
				);
			}
		}
	}

	/**
	 * Public endpoint to trigger scheduled email reminders via AJAX.
	 */
	public function bookingor_api_handler()
	{
		$call = isset($_REQUEST['call']) ? sanitize_text_field(wp_unslash($_REQUEST['call'])) : '';
		if ($call === '/notifications/scheduled/send') {
			$this->bookingor_send_reminders_callback();
			wp_send_json_success(['message' => 'Scheduled reminders sent successfully.']);
		} else {
			wp_send_json_error(['message' => 'Invalid call action.']);
		}
	}
}
