<?php

namespace SoftminalB2B\Http\Controllers;

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

use SoftminalB2B\Models\Group;
use SoftminalB2B\Models\PriceRule;
use SoftminalB2B\Registration\Applicant;
use SoftminalB2B\Registration\RegistrationForm;
use SoftminalB2B\Services\Scheduler;
use SoftminalB2B\Services\Settings;
use SoftminalB2B\Support\DashboardStats;
use SoftminalB2B\Support\ReviewPrompt;

/**
 * Dashboard status: the setup-wizard checklist and the background-jobs health
 * panel (FEATURES H5, ARCHITECTURE §4).
 */
class StatusController extends Controller
{
    public function index(\WP_REST_Request $request, $params = [])
    {
        return $this->success([
            'setup'  => $this->setup(),
            'health' => Scheduler::health(),
            'stats'  => $this->stats(),
            'review' => ReviewPrompt::payload(),
        ]);
    }

    /**
     * Dismiss the in-app review prompt for the current user (they either left a
     * review or chose "maybe later" — either way, don't ask again).
     */
    public function dismissReview(\WP_REST_Request $request, $params = [])
    {
        ReviewPrompt::dismiss();

        return $this->success(null, __('Thanks!', 'softminal-b2b-wholesale-for-woocommerce'));
    }

    /**
     * The revenue hero (headline B2B sales, trend, order/AOV deltas). Served on
     * its own endpoint so the order-scan it may run never blocks the dashboard
     * shell — the SPA paints the rest of the page, then streams this in.
     */
    public function revenue(\WP_REST_Request $request, $params = [])
    {
        return $this->success(['revenue' => DashboardStats::revenueStats()]);
    }

    /**
     * Daily B2B sales bars and top-spending customers for a date range — each
     * dashboard chart has its own range picker and calls this independently.
     */
    public function sales(\WP_REST_Request $request, $params = [])
    {
        $start = sanitize_text_field((string) $request->get_param('start'));
        $end   = sanitize_text_field((string) $request->get_param('end'));

        return $this->success(DashboardStats::salesRange($start, $end));
    }

    public function completeSetup(\WP_REST_Request $request, $params = [])
    {
        Settings::set('setup_complete', 'yes');

        return $this->success(null, __('Setup complete.', 'softminal-b2b-wholesale-for-woocommerce'));
    }

    /**
     * One-click registration page for the onboarding wizard (FLOWS §1, step
     * "generate registration page"). Idempotent: if a published page already
     * carries the shortcode or block, its link is returned instead of creating
     * a duplicate.
     */
    public function createRegistrationPage(\WP_REST_Request $request, $params = [])
    {
        $existing = $this->registrationPageId();

        if ($existing) {
            return $this->success([
                'page_id'  => $existing,
                'page_url' => (string) get_permalink($existing),
                'created'  => false,
            ]);
        }

        $pageId = wp_insert_post([
            'post_title'   => __('Wholesale Registration', 'softminal-b2b-wholesale-for-woocommerce'),
            'post_content' => '<!-- wp:shortcode -->[' . RegistrationForm::SHORTCODE . ']<!-- /wp:shortcode -->',
            'post_status'  => 'publish',
            'post_type'    => 'page',
        ], true);

        if (is_wp_error($pageId)) {
            return $this->error(__('The page could not be created. Add the [smb2b_registration] shortcode to a page yourself instead.', 'softminal-b2b-wholesale-for-woocommerce'), 500);
        }

        return $this->success([
            'page_id'  => $pageId,
            'page_url' => (string) get_permalink($pageId),
            'created'  => true,
        ], __('Registration page created and published.', 'softminal-b2b-wholesale-for-woocommerce'));
    }

    /**
     * The wizard steps and whether each is already satisfied, so the merchant
     * can be dropped back in exactly where they left off (H5, <10 min journey).
     *
     * @return array<string, mixed>
     */
    private function setup(): array
    {
        $hasGroup   = count(Group::all()) > 0;
        $hasRule    = PriceRule::query()->exists();
        $pageId     = $this->registrationPageId();

        $steps = [
            [
                'key'   => 'group',
                'label' => __('Create a customer group', 'softminal-b2b-wholesale-for-woocommerce'),
                'done'  => $hasGroup,
            ],
            [
                'key'   => 'pricing',
                'label' => __('Give the group a discount', 'softminal-b2b-wholesale-for-woocommerce'),
                'done'  => $hasRule,
            ],
            [
                'key'   => 'registration',
                'label' => __('Add a registration page', 'softminal-b2b-wholesale-for-woocommerce'),
                'done'  => $pageId !== null,
                'meta'  => ['page_url' => $pageId ? (string) get_permalink($pageId) : null],
            ],
            [
                'key'   => 'visibility',
                'label' => __('Choose who sees prices', 'softminal-b2b-wholesale-for-woocommerce'),
                // This step is a decision, not a thing to create, so it counts
                // as done once the merchant has saved settings at least once.
                'done'  => Settings::get('setup_complete') === 'yes',
            ],
        ];

        $done = count(array_filter($steps, static fn ($s) => $s['done']));

        return [
            'complete' => Settings::get('setup_complete') === 'yes',
            'steps'    => $steps,
            'done'     => $done,
            'total'    => count($steps),
        ];
    }

    /**
     * The id of any published page containing the registration shortcode or
     * block, so the wizard does not nag a merchant who has already added one
     * and the onboarding "create page" step knows not to duplicate it.
     */
    private function registrationPageId(): ?int
    {
        $query = new \WP_Query([
            'post_type'      => 'page',
            'post_status'    => 'publish',
            'posts_per_page' => 1,
            'fields'         => 'ids',
            's'              => 'smb2b_registration',
            'no_found_rows'  => true,
        ]);

        if (!empty($query->posts)) {
            return (int) $query->posts[0];
        }

        // Block markup search — the shortcode `s` above misses the block.
        $block = new \WP_Query([
            'post_type'      => 'page',
            'post_status'    => 'publish',
            'posts_per_page' => 1,
            'fields'         => 'ids',
            's'              => 'smb2b/registration-form',
            'no_found_rows'  => true,
        ]);

        return !empty($block->posts) ? (int) $block->posts[0] : null;
    }

    /**
     * @return array<string, mixed>
     */
    private function stats(): array
    {
        // One grouped query for all three status tallies, rather than four
        // separate WP_User_Query scans (pending was previously counted twice).
        $applications = Applicant::countByStatuses();

        return array_merge(
            [
                'groups'               => Group::query()->count(),
                'price_rules'          => PriceRule::query()->count(),
                'pending_applications' => $applications[Applicant::STATUS_PENDING] ?? 0,
                'applications'         => [
                    'pending'  => $applications[Applicant::STATUS_PENDING] ?? 0,
                    'approved' => $applications[Applicant::STATUS_APPROVED] ?? 0,
                    'rejected' => $applications[Applicant::STATUS_REJECTED] ?? 0,
                ],
            ],
            DashboardStats::all()
        );
    }
}
