<?php
/**
 * Table Reservation List & Details admin page.
 * Under Unlock Addons menu. Status: Pending (default), Complete, Cancel. Cancel requires reason. Sends email on change.
 *
 * @package Unlock_Addons_For_Elementor
 */

namespace Unlockafe_addons\Admin;

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

use Unlockafe_addons\Classes\Table_Reservation_Handler;

class Table_Reservation_List {

	private static $instance = null;

	public static function get_instance() {
		if (is_null(self::$instance)) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action('admin_menu', [$this, 'register_menu'], 98);
		add_action('wp_ajax_unlockafe_update_reservation_status', [$this, 'ajax_update_status']);
		add_action('admin_init', [$this, 'maybe_save_email_settings']);
		add_action('wp_ajax_unlockafe_send_reservation_test_email', [$this, 'ajax_send_test_email']);
	}

	public function ajax_send_test_email() {
		check_ajax_referer('unlockafe_reservation_test_email', 'nonce');
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => __('Permission denied.', 'unlock-addons-for-elementor')]);
		}
		$to = isset($_POST['to']) ? sanitize_email(wp_unslash($_POST['to'])) : get_option('admin_email');
		if (!is_email($to)) {
			wp_send_json_error(['message' => __('Invalid email address.', 'unlock-addons-for-elementor')]);
		}
		$subject = __('[Test] Reservation email from Unlock Addons', 'unlock-addons-for-elementor');
		$body = __('This is a test email. If you received this, your reservation email settings are working.', 'unlock-addons-for-elementor') . "\n\n" . __('Sent at:', 'unlock-addons-for-elementor') . ' ' . current_time('mysql');
		$sent = Table_Reservation_Handler::send_test_email($to, $subject, $body);
		if ($sent) {
			wp_send_json_success(['message' => __('Test email sent. Check your inbox.', 'unlock-addons-for-elementor')]);
		}
		$detail = Table_Reservation_Handler::get_last_mail_error();
		$message = __('Test email could not be sent.', 'unlock-addons-for-elementor');
		if ($detail !== '') {
			$message .= ' ' . $detail;
		} else {
			$message .= ' ' . __('Check App Password and SMTP settings.', 'unlock-addons-for-elementor');
		}
		wp_send_json_error(['message' => $message]);
	}

	public function register_menu() {
		add_submenu_page(
			'unlock-addons',
			__('Reservation List & Details', 'unlock-addons-for-elementor'),
			__('Reservation List & Details', 'unlock-addons-for-elementor'),
			'manage_options',
			'unlockafe-table-reservations',
			[$this, 'render_page']
		);
	}

	public function maybe_save_email_settings() {
		if (!current_user_can('manage_options')) {
			return;
		}
		if (empty($_POST['unlockafe_reservation_email_nonce']) || empty($_POST['unlockafe_save_reservation_email'])) {
			return;
		}
		if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['unlockafe_reservation_email_nonce'])), 'unlockafe_reservation_email_settings')) {
			return;
		}
		$from_name   = isset($_POST['reservation_from_name']) ? sanitize_text_field(wp_unslash($_POST['reservation_from_name'])) : '';
		$from_email = isset($_POST['reservation_from_email']) ? sanitize_email(wp_unslash($_POST['reservation_from_email'])) : '';
		$smtp_pass   = isset($_POST['reservation_smtp_password']) ? $_POST['reservation_smtp_password'] : '';
		$smtp_host   = isset($_POST['reservation_smtp_host']) ? sanitize_text_field(wp_unslash($_POST['reservation_smtp_host'])) : '';
		$smtp_port   = isset($_POST['reservation_smtp_port']) ? sanitize_text_field(wp_unslash($_POST['reservation_smtp_port'])) : '587';
		$smtp_enc    = isset($_POST['reservation_smtp_encryption']) && in_array($_POST['reservation_smtp_encryption'], ['tls', 'ssl', ''], true) ? $_POST['reservation_smtp_encryption'] : 'tls';
		$smtp_no_ssl = !empty($_POST['reservation_smtp_disable_ssl_verify']);
		$opts = get_option(Table_Reservation_Handler::OPTION_EMAIL_KEY, []);
		if (!is_array($opts)) {
			$opts = [];
		}
		$opts['from_name']               = $from_name;
		$opts['from_email']              = $from_email;
		$opts['smtp_host']               = $smtp_host;
		$opts['smtp_port']               = $smtp_port;
		$opts['smtp_encryption']          = $smtp_enc;
		$opts['smtp_disable_ssl_verify'] = $smtp_no_ssl ? 'yes' : '';
		if ($smtp_pass !== '') {
			$opts['smtp_password'] = $smtp_pass;
		}
		update_option(Table_Reservation_Handler::OPTION_EMAIL_KEY, $opts);
		wp_safe_redirect(add_query_arg('reservation_email_saved', '1', wp_get_referer() ?: admin_url('admin.php?page=unlockafe-table-reservations')));
		exit;
	}

	public function render_page() {
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('You do not have sufficient permissions.', 'unlock-addons-for-elementor'));
		}
		$reservations = Table_Reservation_Handler::get_all_reservations();
		$email_settings = Table_Reservation_Handler::get_email_settings();
		$email_saved_message = isset($_GET['reservation_email_saved']) ? __('Email sender settings saved.', 'unlock-addons-for-elementor') : '';
		$has_smtp_password = !empty($email_settings['smtp_password']);
		$is_gmail_like = (strpos(isset($email_settings['from_email']) ? $email_settings['from_email'] : '', 'gmail.com') !== false)
			|| (isset($email_settings['smtp_host']) && stripos($email_settings['smtp_host'], 'gmail') !== false);
		include_once UNLOCKAFE_INCLUDE_PATH . 'Admin/views/table-reservation-list.php';
	}

	public function ajax_update_status() {
		check_ajax_referer('unlockafe_reservation_status', 'nonce');
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => __('Permission denied.', 'unlock-addons-for-elementor')]);
		}
		$id     = isset($_POST['id']) ? sanitize_text_field(wp_unslash($_POST['id'])) : '';
		$status = isset($_POST['status']) ? sanitize_text_field(wp_unslash($_POST['status'])) : '';
		$reason = isset($_POST['reason']) ? sanitize_textarea_field(wp_unslash($_POST['reason'])) : '';
		$allowed = ['pending', 'complete', 'cancel'];
		if ($id === '' || !in_array($status, $allowed, true)) {
			wp_send_json_error(['message' => __('Invalid request.', 'unlock-addons-for-elementor')]);
		}
		if ($status === 'cancel' && trim($reason) === '') {
			wp_send_json_error(['message' => __('Please provide a reason for cancellation.', 'unlock-addons-for-elementor')]);
		}
		$updated = Table_Reservation_Handler::update_reservation_status($id, $status, $reason);
		if ($updated === false) {
			wp_send_json_error(['message' => __('Reservation not found or could not be updated.', 'unlock-addons-for-elementor')]);
		}
		$labels = ['pending' => __('Pending', 'unlock-addons-for-elementor'), 'complete' => __('Complete', 'unlock-addons-for-elementor'), 'cancel' => __('Cancelled', 'unlock-addons-for-elementor')];
		wp_send_json_success([
			'message' => __('Status updated. Customer has been notified by email.', 'unlock-addons-for-elementor'),
			'status'  => $updated['status'],
			'status_label' => isset($labels[$updated['status']]) ? $labels[$updated['status']] : $updated['status'],
			'reason'  => $updated['status_reason'] ?? '',
		]);
	}
}
