<?php

namespace DaftPlug\Generatify\Admin;

use DaftPlug\Generatify\Helpers\Utils;
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class Notices {
    const INSTALL_TIME_OPTION = 'generatify_install_time';

    const REVIEW_DISMISS_OPTION = 'generatify_review_notice_dismissed';

    const UPGRADE_DISMISS_OPTION = 'generatify_upgrade_notice_dismissed';

    const REVIEW_DELAY = 7 * DAY_IN_SECONDS;

    const REVIEW_DISMISS_PERIOD = 3 * MONTH_IN_SECONDS;

    const UPGRADE_DELAY = DAY_IN_SECONDS;

    const UPGRADE_DISMISS_PERIOD = MONTH_IN_SECONDS;

    const REVIEW_URL = 'https://wordpress.org/support/plugin/generatify/reviews/?filter=5#new-post';

    public function __construct() {
        add_action( 'admin_init', [$this, 'recordInstallTime'] );
        add_action( 'admin_notices', [$this, 'renderNotices'] );
        add_action( 'wp_ajax_generatify_dismiss_notice', [$this, 'handleDismiss'] );
    }

    public function recordInstallTime() {
        if ( !get_option( self::INSTALL_TIME_OPTION ) ) {
            update_option( self::INSTALL_TIME_OPTION, time() );
        }
    }

    public function renderNotices() {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        $showReview = $this->shouldShow( self::REVIEW_DISMISS_OPTION, self::REVIEW_DELAY, self::REVIEW_DISMISS_PERIOD );
        $showUpgrade = $this->shouldShow( self::UPGRADE_DISMISS_OPTION, self::UPGRADE_DELAY, self::UPGRADE_DISMISS_PERIOD );
        if ( !$showReview && !$showUpgrade ) {
            return;
        }
        $this->renderStyles();
        $this->renderDismissScript();
        if ( $showReview ) {
            $this->renderReviewNotice();
        }
        if ( $showUpgrade ) {
            $this->renderUpgradeNotice();
        }
    }

    private function shouldShow( $dismissOption, $delay, $dismissPeriod ) {
        $installedAt = (int) get_option( self::INSTALL_TIME_OPTION, 0 );
        if ( !$installedAt || time() - $installedAt < $delay ) {
            return false;
        }
        $dismissedAt = (int) get_option( $dismissOption, 0 );
        if ( $dismissedAt && time() - $dismissedAt < $dismissPeriod ) {
            return false;
        }
        return true;
    }

    private function renderReviewNotice() {
        $nonce = wp_create_nonce( 'generatify_dismiss_notice' );
        $logoUrl = esc_url( plugins_url( 'assets/media/icons/logo.png', GENERATIFY_FILE ) );
        ?>
<div class="notice notice-info is-dismissible generatify-notice" data-generatify-notice="review" data-nonce="<?php 
        echo esc_attr( $nonce );
        ?>">
  <div class="generatify-notice-inner">
    <img class="generatify-notice-logo" src="<?php 
        echo $logoUrl;
        ?>" alt="Generatify" />
    <div class="generatify-notice-body">
      <h3 class="generatify-notice-title"><?php 
        esc_html_e( 'Enjoying Generatify?', 'generatify' );
        ?></h3>
      <p><?php 
        esc_html_e( 'If Generatify has been helpful, please take a moment to leave a 5-star review on WordPress.org. It takes less than a minute and helps a lot!', 'generatify' );
        ?></p>
      <p class="generatify-notice-actions">
        <a href="<?php 
        echo esc_url( self::REVIEW_URL );
        ?>" target="_blank" rel="noopener" class="button button-primary generatify-notice-action"><?php 
        esc_html_e( 'Leave a 5-star review ⭐', 'generatify' );
        ?></a>
        <button type="button" class="button button-secondary generatify-notice-dismiss"><?php 
        esc_html_e( 'Maybe later', 'generatify' );
        ?></button>
      </p>
    </div>
  </div>
</div>
<?php 
    }

    private function renderUpgradeNotice() {
        $nonce = wp_create_nonce( 'generatify_dismiss_notice' );
        $logoUrl = esc_url( plugins_url( 'assets/media/icons/logo.png', GENERATIFY_FILE ) );
        ?>
<div class="notice notice-info is-dismissible generatify-notice" data-generatify-notice="upgrade" data-nonce="<?php 
        echo esc_attr( $nonce );
        ?>">
  <div class="generatify-notice-inner">
    <img class="generatify-notice-logo" src="<?php 
        echo $logoUrl;
        ?>" alt="Generatify" />
    <div class="generatify-notice-body">
      <h3 class="generatify-notice-title"><?php 
        esc_html_e( 'Unlock the full power of Generatify', 'generatify' );
        ?></h3>
      <p><?php 
        esc_html_e( 'Upgrade to Generatify Pro to unlock advanced features, priority support and other All-in-One Pro plugins from us without extra cost.', 'generatify' );
        ?></p>
      <p class="generatify-notice-actions">
        <a href="<?php 
        echo esc_url( Utils::getUpgradeUrl() );
        ?>" class="button button-primary"><?php 
        esc_html_e( 'Upgrade to Pro 🚀', 'generatify' );
        ?></a>
        <button type="button" class="button button-secondary generatify-notice-dismiss"><?php 
        esc_html_e( 'Dismiss', 'generatify' );
        ?></button>
      </p>
    </div>
  </div>
</div>
<?php 
    }

    private function renderStyles() {
        static $printed = false;
        if ( $printed ) {
            return;
        }
        $printed = true;
        ?>
<style>
.generatify-notice {
  padding: 16px 38px 16px 16px;
}

.generatify-notice-inner {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.generatify-notice-logo {
  width: 56px;
  height: 56px;
  flex: 0 0 56px;
  border-radius: 8px;
  object-fit: contain;
}

.generatify-notice-body {
  flex: 1;
  min-width: 0;
}

.generatify-notice-title {
  margin: 0 0 6px;
  font-size: 18px;
  line-height: 1.3;
  font-weight: 600;
}

.generatify-notice-body p {
  margin: 0 0 10px;
  font-size: 14px;
}

.generatify-notice-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 0 !important;
}
</style>
<?php 
    }

    private function renderDismissScript() {
        static $printed = false;
        if ( $printed ) {
            return;
        }
        $printed = true;
        ?>
<script>
(function() {
  document.addEventListener('click', function(e) {
    const notice = e.target.closest('.generatify-notice');
    if (!notice) return;

    const isDismiss = e.target.matches('.notice-dismiss, .generatify-notice-dismiss');
    const isAction = e.target.closest('.generatify-notice-action');
    if (!isDismiss && !isAction) return;

    const key = notice.getAttribute('data-generatify-notice');
    const nonce = notice.getAttribute('data-nonce');
    if (!key || !nonce) return;

    const body = new URLSearchParams();
    body.append('action', 'generatify_dismiss_notice');
    body.append('notice', key);
    body.append('_wpnonce', nonce);

    fetch('<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>', {
      method: 'POST',
      credentials: 'same-origin',
      body: body,
    });

    if (e.target.matches('.generatify-notice-dismiss')) {
      notice.style.display = 'none';
    }
  });
})();
</script>
<?php 
    }

    public function handleDismiss() {
        check_ajax_referer( 'generatify_dismiss_notice' );
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error();
        }
        $notice = ( isset( $_POST['notice'] ) ? sanitize_key( wp_unslash( $_POST['notice'] ) ) : '' );
        $map = [
            'review'  => self::REVIEW_DISMISS_OPTION,
            'upgrade' => self::UPGRADE_DISMISS_OPTION,
        ];
        if ( !isset( $map[$notice] ) ) {
            wp_send_json_error();
        }
        update_option( $map[$notice], time() );
        wp_send_json_success();
    }

}
