<?php
namespace Bookaro\Controller\Admin;

defined( 'ABSPATH' ) || exit;

use Bookaro\Repository\BookingRepository;
use Bookaro\Utils\ReviewPrompt;

/**
 * Shows site owners a single, easy-to-dismiss prompt to review MyBookaro on
 * WordPress.org once they have completed a few bookings (i.e. the plugin has
 * actually delivered value).
 *
 * Built to comply with the WordPress.org review guidelines:
 *  - Shown only to the site's own admins — real, independent users (never the
 *    plugin author reviewing their own plugin).
 *  - Never incentivised: it only asks, it offers nothing in return.
 *  - Permanently dismissible per-user; "No thanks" / "I already did" set a
 *    user-meta flag so we never nag again.
 *  - Scoped to MyBookaro admin screens so it never spams the rest of wp-admin.
 *  - Routes unhappy owners to System Status first, so problems get fixed
 *    rather than turned into a 1-star review.
 */
class ReviewNudgeController
{
    private BookingRepository $db;

    public function __construct( BookingRepository $db )
    {
        $this->db = $db;
    }

    public function register_hooks(): void
    {
        add_action( 'admin_notices', [ $this, 'maybe_render_notice' ] );
        add_action( 'admin_post_bookaro_review_nudge', [ $this, 'handle_action' ] );
    }

    private function can_manage(): bool
    {
        if ( function_exists( 'bookaro_current_user_can_manage_admin' ) ) {
            return (bool) bookaro_current_user_can_manage_admin();
        }
        return current_user_can( 'manage_options' );
    }

    private function is_dismissed(): bool
    {
        $user_id = get_current_user_id();
        if ( $user_id < 1 ) {
            // No user context: treat as dismissed so nothing renders.
            return true;
        }
        return '' !== (string) get_user_meta( $user_id, ReviewPrompt::DISMISSED_META_KEY, true );
    }

    private function on_bookaro_screen(): bool
    {
        if ( ! function_exists( 'get_current_screen' ) ) {
            return false;
        }
        $screen = get_current_screen();
        return $screen && ! empty( $screen->id ) && strpos( (string) $screen->id, 'bookaro' ) !== false;
    }

    private function threshold(): int
    {
        $threshold = (int) apply_filters( 'bookaro_review_nudge_threshold', ReviewPrompt::DEFAULT_THRESHOLD );
        return $threshold > 0 ? $threshold : ReviewPrompt::DEFAULT_THRESHOLD;
    }

    public function maybe_render_notice(): void
    {
        if ( ! $this->can_manage() || ! $this->on_bookaro_screen() || $this->is_dismissed() ) {
            return;
        }

        $threshold = $this->threshold();
        $completed = $this->db->count_by_status( 'completed' );

        if ( ! ReviewPrompt::should_display( true, false, $completed, $threshold ) ) {
            return;
        }

        $this->render_notice( $completed );
    }

    private function render_notice( int $completed ): void
    {
        $action_base = admin_url( 'admin-post.php' );
        $review_url = wp_nonce_url(
            add_query_arg(
                [ 'action' => 'bookaro_review_nudge', 'do' => 'review' ],
                $action_base
            ),
            'bookaro_review_nudge'
        );
        $hide_url = wp_nonce_url(
            add_query_arg(
                [ 'action' => 'bookaro_review_nudge', 'do' => 'hide' ],
                $action_base
            ),
            'bookaro_review_nudge'
        );
        $support_url = admin_url( 'admin.php?page=bookaro-system-status' );

        // Brand teal (matches the MyBookaro mark / WP.org banner palette).
        $teal = '#0F766E';

        echo '<div class="notice notice-info bookaro-review-nudge" style="border-left-color:' . esc_attr( $teal ) . ';">';

        echo '<p style="margin-bottom:.4em;">';
        echo '<strong style="color:' . esc_attr( $teal ) . ';">' . esc_html__( 'Enjoying MyBookaro?', 'mybookaro' ) . '</strong> ';
        echo esc_html(
            sprintf(
                /* translators: %s: number of completed bookings on this site. */
                _n(
                    'You have completed %s booking with it. If it has been useful, a quick rating on WordPress.org helps other site owners find it.',
                    'You have completed %s bookings with it. If it has been useful, a quick rating on WordPress.org helps other site owners find it.',
                    $completed,
                    'mybookaro'
                ),
                number_format_i18n( $completed )
            )
        );
        echo '</p>';

        echo '<p>';
        echo '<a href="' . esc_url( $review_url ) . '" class="button button-primary" style="background:' . esc_attr( $teal ) . ';border-color:' . esc_attr( $teal ) . ';" target="_blank" rel="noopener noreferrer">'
            . esc_html__( 'Leave a review', 'mybookaro' ) . '</a> ';
        echo '<a href="' . esc_url( $hide_url ) . '" class="button" style="margin-left:.4em;">'
            . esc_html__( 'I already did', 'mybookaro' ) . '</a> ';
        echo '<a href="' . esc_url( $hide_url ) . '" style="margin-left:.6em;">'
            . esc_html__( 'No thanks', 'mybookaro' ) . '</a>';
        echo '<span style="margin-left:1em;color:#646970;">'
            . esc_html__( 'Something not working right?', 'mybookaro' ) . ' '
            . '<a href="' . esc_url( $support_url ) . '">' . esc_html__( 'Open System Status', 'mybookaro' ) . '</a></span>';
        echo '</p>';

        echo '</div>';
    }

    public function handle_action(): void
    {
        if ( ! $this->can_manage() ) {
            wp_die( esc_html__( 'You are not allowed to do this.', 'mybookaro' ) );
        }
        check_admin_referer( 'bookaro_review_nudge' );

        $user_id = get_current_user_id();
        if ( $user_id > 0 ) {
            update_user_meta( $user_id, ReviewPrompt::DISMISSED_META_KEY, '1' );
        }

        $do = isset( $_GET['do'] ) ? sanitize_key( wp_unslash( $_GET['do'] ) ) : '';

        if ( 'review' === $do ) {
            // Destination is a hard-coded plugin constant, not user input, so an
            // external redirect here is safe (not an open redirect). wp_safe_redirect
            // cannot be used because it would block this off-host WordPress.org URL.
            wp_redirect( ReviewPrompt::REVIEW_URL ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- external destination is a fixed plugin constant.
            exit;
        }

        $back = wp_get_referer();
        wp_safe_redirect( $back ? $back : admin_url( 'admin.php?page=bookaro-bookings' ) );
        exit;
    }
}
