<?php
/**
 * Pro-3: QR code generation for Google review requests
 *
 * Displays a QR code per store in the admin dashboard.
 * The QR code links directly to the Google review submission page.
 * Pro users can download each QR as a PNG.
 *
 * Requires: Freemius Pro license
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class TMNL_QR {

    /** @var TMNL_Adapter_Google */
    private $google_adapter;

    public function __construct( TMNL_Adapter_Google $google_adapter ) {
        $this->google_adapter = $google_adapter;

        if ( ! kw_is_pro() ) {
            return;
        }

        // Hook QR section into dashboard
        add_action( 'tmnl_dashboard_after_sections', array( $this, 'render_dashboard_section' ) );

        // AJAX handler for PNG download
        add_action( 'wp_ajax_tmnl_download_qr', array( $this, 'handle_download' ) );
    }

    /**
     * Build Google review request URL from Place ID.
     */
    public function get_review_url( $place_id ) {
        return 'https://search.google.com/local/writereview?placeid=' . rawurlencode( $place_id );
    }

    /**
     * Build QR image URL using QR Server API (free, no auth required).
     */
    public function get_qr_image_url( $place_id, $size = 250 ) {
        return add_query_arg( array(
            'size'  => $size . 'x' . $size,
            'data'  => rawurlencode( $this->get_review_url( $place_id ) ),
            'ecc'   => 'M',
            'color' => '000000',
            'bgcolor' => 'ffffff',
            'margin' => 2,
        ), 'https://api.qrserver.com/v1/create-qr-code/' );
    }

    /**
     * Render QR code section in the dashboard.
     */
    public function render_dashboard_section() {
        $stores = $this->google_adapter->get_stores();
        if ( empty( $stores ) ) return;

        // Check at least one store has a Place ID
        $has_place_id = false;
        foreach ( $stores as $store ) {
            if ( ! empty( $store['place_id'] ) ) { $has_place_id = true; break; }
        }
        if ( ! $has_place_id ) return;

        ?>
        <div class="tmnl-dashboard-section">
            <h2>
                <?php esc_html_e( 'QR Codes for Review Requests', 'kuchikomi-wall' ); ?>
                <span style="background:#0073aa;color:#fff;font-size:11px;padding:2px 8px;border-radius:3px;vertical-align:middle;margin-left:6px;">PRO</span>
            </h2>
            <p class="description">
                <?php esc_html_e( 'Show this QR code to customers to ask for a Google review. Scan leads directly to the review submission page.', 'kuchikomi-wall' ); ?>
            </p>

            <div style="display:flex;flex-wrap:wrap;gap:24px;margin-top:16px;">
            <?php foreach ( $stores as $store ) :
                $place_id = $store['place_id'] ?? '';
                if ( empty( $place_id ) ) continue;
                $store_name = $store['name'] ?? __( 'My Store', 'kuchikomi-wall' );
                $qr_url     = $this->get_qr_image_url( $place_id );
                $download_url = wp_nonce_url(
                    admin_url( 'admin-ajax.php?action=tmnl_download_qr&store_id=' . urlencode( $store['id'] ) ),
                    'tmnl_download_qr_' . $store['id'],
                    '_tmnl_nonce'
                );
            ?>
                <div style="text-align:center;background:#fff;border:1px solid #ddd;border-radius:4px;padding:16px;min-width:200px;">
                    <p style="font-weight:bold;margin:0 0 12px;"><?php echo esc_html( $store_name ); ?></p>
                    <img src="<?php echo esc_url( $qr_url ); ?>"
                         alt="<?php echo esc_attr( $store_name ); ?> QR"
                         width="200" height="200"
                         style="display:block;margin:0 auto 12px;">
                    <a href="<?php echo esc_url( $download_url ); ?>" class="button button-primary">
                        &#11015; <?php esc_html_e( 'Download PNG', 'kuchikomi-wall' ); ?>
                    </a>
                    <br><br>
                    <a href="<?php echo esc_url( $this->get_review_url( $place_id ) ); ?>"
                       target="_blank" rel="noopener" style="font-size:11px;color:#666;">
                        <?php esc_html_e( 'Preview link', 'kuchikomi-wall' ); ?> &#8599;
                    </a>
                </div>
            <?php endforeach; ?>
            </div>
        </div>
        <?php
    }

    /**
     * AJAX: proxy QR image from API and send as PNG download.
     */
    public function handle_download() {
        $store_id = sanitize_key( $_GET['store_id'] ?? '' );

        if ( ! check_ajax_referer( 'tmnl_download_qr_' . $store_id, '_tmnl_nonce', false ) ) {
            wp_die( esc_html__( 'Security check failed.', 'kuchikomi-wall' ), 403 );
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'kuchikomi-wall' ), 403 );
        }

        // Find the store
        $stores   = $this->google_adapter->get_stores();
        $place_id = '';
        $store_name = 'qrcode';
        foreach ( $stores as $store ) {
            if ( $store['id'] === $store_id ) {
                $place_id   = $store['place_id'] ?? '';
                $store_name = sanitize_file_name( $store['name'] ?? 'store' );
                break;
            }
        }

        if ( empty( $place_id ) ) {
            wp_die( esc_html__( 'Store not found.', 'kuchikomi-wall' ), 404 );
        }

        // Fetch QR image (600px for print quality)
        $qr_url   = $this->get_qr_image_url( $place_id, 600 );
        $response = wp_remote_get( $qr_url, array( 'timeout' => 15 ) );

        if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) {
            wp_die( esc_html__( 'Failed to generate QR code. Please try again.', 'kuchikomi-wall' ) );
        }

        $image_data = wp_remote_retrieve_body( $response );
        $filename   = 'kw-qr-' . $store_name . '.png';

        header( 'Content-Type: image/png' );
        header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
        header( 'Content-Length: ' . strlen( $image_data ) );
        header( 'Cache-Control: no-store, no-cache' );
        echo $image_data; // phpcs:ignore WordPress.Security.EscapeOutput
        exit;
    }
}
