<?php
/**
 * ACC Shop Platform — فروش پلتفرم به فروشگاه‌های دیگر
 * پلن‌ها · وایت‌لیبل · API Key · Webhook
 */
if ( ! defined( 'ABSPATH' ) ) exit;

require_once ACC_PATH . 'includes/helpers/arag-shop.php';

class Acc_Shop_Platform {

    public const VERSION = '1.0';

    public static function plans(): array {
        return [
            'starter' => [
                'key'         => 'starter',
                'name'        => 'استارتر',
                'price_month' => 990000,
                'price_label' => '۹۹۰ هزار تومان / ماه',
                'tagline'     => 'فروش آنلاین سریع بدون کدنویسی',
                'color'       => '#2563eb',
                'features'    => [
                    'storefront', 'admin_panel', 'catalog', 'coupons', 'reviews',
                    'otp_auth', 'zarinpal', 'order_tracking', 'mobile_ui',
                ],
            ],
            'pro' => [
                'key'         => 'pro',
                'name'        => 'حرفه‌ای',
                'price_month' => 2490000,
                'price_label' => '۲.۴۹ میلیون / ماه',
                'tagline'     => 'ERP + حسابداری + CRM برای رشد فروش',
                'color'       => '#16a34a',
                'popular'     => true,
                'features'    => [
                    'storefront', 'admin_panel', 'catalog', 'coupons', 'reviews',
                    'otp_auth', 'zarinpal', 'order_tracking', 'mobile_ui',
                    'erp_panel', 'shop_accounting', 'crm', 'shipping', 'inventory',
                    'finance_graph', 'referral', 'mizaj_quiz', 'expense_tracking',
                ],
            ],
            'enterprise' => [
                'key'         => 'enterprise',
                'name'        => 'سازمانی',
                'price_month' => 4990000,
                'price_label' => '۴.۹۹ میلیون / ماه',
                'tagline'     => 'API · Webhook · AI · وایت‌لیبل کامل',
                'color'       => '#7c3aed',
                'features'    => [
                    'storefront', 'admin_panel', 'catalog', 'coupons', 'reviews',
                    'otp_auth', 'zarinpal', 'order_tracking', 'mobile_ui',
                    'erp_panel', 'shop_accounting', 'crm', 'shipping', 'inventory',
                    'finance_graph', 'referral', 'mizaj_quiz', 'expense_tracking',
                    'white_label', 'api_keys', 'webhooks', 'ai_chat', 'priority_support',
                ],
            ],
        ];
    }

    public static function feature_labels(): array {
        return [
            'storefront'       => 'فروشگاه آنلاین Premium',
            'admin_panel'      => 'پنل مدیریت محتوا و قیمت',
            'catalog'          => 'کاتالوگ چندسطحی (محصول/مدل/بسته)',
            'coupons'          => 'کوپن و تخفیف',
            'reviews'          => 'نظرات و امتیاز',
            'otp_auth'         => 'ورود OTP پیامکی',
            'zarinpal'         => 'درگاه زرین‌پال',
            'order_tracking'   => 'پیگیری سفارش',
            'mobile_ui'        => 'UI موبایل‌فرست',
            'erp_panel'        => 'ERP عملیاتی',
            'shop_accounting'  => 'حسابداری فروش (GL)',
            'crm'              => 'CRM مشتریان',
            'shipping'         => 'حمل‌ونقل و پیک',
            'inventory'        => 'انبار و موجودی',
            'finance_graph'    => 'گراف مالی',
            'referral'         => 'سیستم معرفی دوستان',
            'mizaj_quiz'       => 'تست مزاج + پیشنهاد محصول',
            'expense_tracking' => 'ثبت هزینه',
            'white_label'      => 'وایت‌لیبل (برند، رنگ، لوگو)',
            'api_keys'         => 'کلید API توسعه‌دهنده',
            'webhooks'         => 'Webhook رویدادها',
            'ai_chat'          => 'چت‌بات AI مشاور',
            'priority_support' => 'پشتیبانی اولویت‌دار',
        ];
    }

    public static function current_plan(): string {
        $s = Arag_Shop::get_settings();
        $plan = sanitize_key( $s['platform_plan'] ?? 'enterprise' );
        return isset( self::plans()[ $plan ] ) ? $plan : 'enterprise';
    }

    public static function has_feature( string $feature ): bool {
        $plan = self::plans()[ self::current_plan() ] ?? self::plans()['enterprise'];
        return in_array( $feature, $plan['features'] ?? [], true );
    }

    public static function plan_comparison(): array {
        $labels = self::feature_labels();
        $plans  = self::plans();
        $all    = array_keys( $labels );
        $matrix = [];
        foreach ( $all as $f ) {
            $row = [ 'key' => $f, 'label' => $labels[ $f ] ];
            foreach ( $plans as $pk => $p ) {
                $row[ $pk ] = in_array( $f, $p['features'], true );
            }
            $matrix[] = $row;
        }
        return [
            'plans'  => array_values( $plans ),
            'matrix' => $matrix,
            'labels' => $labels,
        ];
    }

    public static function showcase_stats(): array {
        global $wpdb;
        $pre = $wpdb->prefix;
        $orders = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$pre}arag_orders" );
        $paid   = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$pre}arag_orders WHERE payment_status IN ('paid','cod')" );
        $products = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$pre}arag_families WHERE is_active = 1" );
        $reviews  = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$pre}arag_reviews WHERE is_approved = 1" );
        return [
            'orders_total'   => $orders,
            'orders_paid'    => $paid,
            'products'       => $products,
            'reviews'        => $reviews,
            'modules_count'  => 12,
            'api_endpoints'  => 45,
            'platform_version' => self::VERSION,
        ];
    }

    /* ── API Keys ── */

    public static function keys_table(): string {
        global $wpdb;
        return $wpdb->prefix . 'acc_shop_api_keys';
    }

    public static function list_api_keys(): array {
        global $wpdb;
        $t = self::keys_table();
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t}'" ) !== $t ) {
            return [];
        }
        return $wpdb->get_results(
            "SELECT id, label, key_prefix, scopes_json, last_used_at, created_at, is_active
             FROM {$t} ORDER BY id DESC",
            ARRAY_A
        ) ?: [];
    }

    public static function create_api_key( string $label, array $scopes = [] ): array {
        global $wpdb;
        if ( ! self::has_feature( 'api_keys' ) ) {
            return [ 'success' => false, 'message' => 'پلن فعلی API Key ندارد — Enterprise لازم است' ];
        }
        $t = self::keys_table();
        $raw = 'acc_' . bin2hex( random_bytes( 24 ) );
        $hash = hash( 'sha256', $raw );
        $prefix = substr( $raw, 0, 12 );
        $wpdb->insert( $t, [
            'label'       => sanitize_text_field( $label ?: 'Default' ),
            'key_hash'    => $hash,
            'key_prefix'  => $prefix,
            'scopes_json' => wp_json_encode( $scopes ?: [ 'orders.read', 'products.read' ] ),
            'is_active'   => 1,
            'created_at'  => current_time( 'mysql' ),
        ] );
        return [
            'success'    => true,
            'id'         => (int) $wpdb->insert_id,
            'api_key'    => $raw,
            'key_prefix' => $prefix,
            'message'    => 'کلید فقط یک‌بار نمایش داده می‌شود — ذخیره کنید',
        ];
    }

    public static function revoke_api_key( int $id ): bool {
        global $wpdb;
        return (bool) $wpdb->update( self::keys_table(), [ 'is_active' => 0 ], [ 'id' => $id ] );
    }

    public static function validate_api_key( string $key ): ?array {
        global $wpdb;
        if ( $key === '' ) return null;
        $t = self::keys_table();
        $hash = hash( 'sha256', $key );
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$t} WHERE key_hash = %s AND is_active = 1 LIMIT 1", $hash
        ), ARRAY_A );
        if ( ! $row ) return null;
        $wpdb->update( $t, [ 'last_used_at' => current_time( 'mysql' ) ], [ 'id' => (int) $row['id'] ] );
        $row['scopes'] = json_decode( $row['scopes_json'] ?? '[]', true ) ?: [];
        return $row;
    }

    /* ── Webhooks ── */

    public static function webhooks_table(): string {
        global $wpdb;
        return $wpdb->prefix . 'acc_shop_webhooks';
    }

    public static function webhook_log_table(): string {
        global $wpdb;
        return $wpdb->prefix . 'acc_shop_webhook_log';
    }

    public static function webhook_events(): array {
        return [
            'order.created'  => 'سفارش جدید ثبت شد',
            'order.paid'     => 'پرداخت تأیید شد',
            'order.cancelled'=> 'سفارش لغو شد',
            'order.shipped'  => 'ارسال شد',
        ];
    }

    public static function list_webhooks(): array {
        global $wpdb;
        $t = self::webhooks_table();
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t}'" ) !== $t ) {
            return [];
        }
        return $wpdb->get_results( "SELECT * FROM {$t} WHERE is_active = 1 ORDER BY id DESC", ARRAY_A ) ?: [];
    }

    public static function create_webhook( array $data ): array {
        if ( ! self::has_feature( 'webhooks' ) ) {
            return [ 'success' => false, 'message' => 'Webhook فقط در پلن Enterprise فعال است' ];
        }
        global $wpdb;
        $url = esc_url_raw( $data['url'] ?? '' );
        $events = $data['events'] ?? [];
        if ( ! $url || ! is_array( $events ) || ! $events ) {
            return [ 'success' => false, 'message' => 'URL و حداقل یک رویداد الزامی است' ];
        }
        $secret = bin2hex( random_bytes( 16 ) );
        $wpdb->insert( self::webhooks_table(), [
            'url'         => $url,
            'events_json' => wp_json_encode( array_values( array_map( 'sanitize_key', $events ) ) ),
            'secret'      => $secret,
            'label'       => sanitize_text_field( $data['label'] ?? '' ),
            'is_active'   => 1,
            'created_at'  => current_time( 'mysql' ),
        ] );
        return [ 'success' => true, 'id' => (int) $wpdb->insert_id, 'secret' => $secret ];
    }

    public static function delete_webhook( int $id ): bool {
        global $wpdb;
        return (bool) $wpdb->update( self::webhooks_table(), [ 'is_active' => 0 ], [ 'id' => $id ] );
    }

    public static function dispatch_webhook( string $event, array $payload ): void {
        if ( ! self::has_feature( 'webhooks' ) ) {
            return;
        }
        global $wpdb;
        $t = self::webhooks_table();
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t}'" ) !== $t ) {
            return;
        }
        $hooks = $wpdb->get_results( "SELECT * FROM {$t} WHERE is_active = 1", ARRAY_A ) ?: [];
        foreach ( $hooks as $hook ) {
            $events = json_decode( $hook['events_json'] ?? '[]', true ) ?: [];
            if ( ! in_array( $event, $events, true ) ) {
                continue;
            }
            self::_deliver_webhook( (int) $hook['id'], $hook['url'], $hook['secret'], $event, $payload );
        }
    }

    private static function _deliver_webhook( int $hook_id, string $url, string $secret, string $event, array $payload ): void {
        global $wpdb;
        $body = wp_json_encode( [
            'event'     => $event,
            'timestamp' => gmdate( 'c' ),
            'data'      => $payload,
        ], JSON_UNESCAPED_UNICODE );
        $sig = hash_hmac( 'sha256', $body, $secret );
        $ctx = stream_context_create( [
            'http' => [
                'method'  => 'POST',
                'header'  => "Content-Type: application/json\r\nX-ACC-Event: {$event}\r\nX-ACC-Signature: sha256={$sig}\r\n",
                'content' => $body,
                'timeout' => 8,
                'ignore_errors' => true,
            ],
        ] );
        $resp = @file_get_contents( $url, false, $ctx );
        $status = 0;
        if ( isset( $http_response_header[0] ) && preg_match( '/\s(\d{3})\s/', $http_response_header[0], $m ) ) {
            $status = (int) $m[1];
        }
        $lt = self::webhook_log_table();
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$lt}'" ) === $lt ) {
            $wpdb->insert( $lt, [
                'webhook_id'   => $hook_id,
                'event'        => $event,
                'http_status'  => $status,
                'response_body'=> substr( (string) $resp, 0, 2000 ),
                'created_at'   => current_time( 'mysql' ),
            ] );
        }
    }

    public static function test_webhook( int $id ): array {
        $hooks = self::list_webhooks();
        $hook = null;
        foreach ( $hooks as $h ) {
            if ( (int) $h['id'] === $id ) { $hook = $h; break; }
        }
        if ( ! $hook ) {
            return [ 'success' => false, 'message' => 'Webhook یافت نشد' ];
        }
        self::_deliver_webhook( $id, $hook['url'], $hook['secret'], 'test.ping', [
            'message' => 'ACC Shop Platform webhook test',
            'shop'    => Arag_Shop::get_settings()['brand_name'] ?? 'Shop',
        ] );
        return [ 'success' => true, 'message' => 'درخواست تست ارسال شد — لاگ را بررسی کنید' ];
    }

    public static function webhook_log( int $limit = 30 ): array {
        global $wpdb;
        $lt = self::webhook_log_table();
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$lt}'" ) !== $lt ) {
            return [];
        }
        return $wpdb->get_results( $wpdb->prepare(
            "SELECT l.*, w.label AS webhook_label, w.url
             FROM {$lt} l
             LEFT JOIN " . self::webhooks_table() . " w ON w.id = l.webhook_id
             ORDER BY l.id DESC LIMIT %d", $limit
        ), ARRAY_A ) ?: [];
    }

    /* ── Demo leads ── */

    public static function leads_table(): string {
        global $wpdb;
        return $wpdb->prefix . 'acc_platform_leads';
    }

    public static function create_lead( array $data ): array {
        global $wpdb;
        $t = self::leads_table();
        $name  = sanitize_text_field( $data['name'] ?? '' );
        $phone = sanitize_text_field( $data['phone'] ?? '' );
        $shop  = sanitize_text_field( $data['shop_name'] ?? '' );
        if ( ! $name || ! $phone ) {
            return [ 'success' => false, 'message' => 'نام و موبایل الزامی است' ];
        }
        $wpdb->insert( $t, [
            'name'       => $name,
            'phone'      => $phone,
            'shop_name'  => $shop,
            'email'      => sanitize_email( $data['email'] ?? '' ),
            'plan_key'   => sanitize_key( $data['plan'] ?? 'pro' ),
            'message'    => sanitize_textarea_field( $data['message'] ?? '' ),
            'source'     => sanitize_text_field( $data['source'] ?? 'platform' ),
            'status'     => 'new',
            'created_at' => current_time( 'mysql' ),
        ] );
        return [ 'success' => true, 'id' => (int) $wpdb->insert_id, 'message' => 'درخواست دمو ثبت شد — به‌زودی تماس می‌گیریم' ];
    }

    public static function api_docs_index(): array {
        return [
            'base_url' => ( defined( 'ACC_URL' ) ? ACC_URL : '/acc-engine/' ) . 'api.php/acc/v1',
            'auth'     => [
                'public'    => 'بدون توکن — families, settings, orders/create',
                'jwt'       => 'Authorization: Bearer {token} — account, admin',
                'api_key'   => 'X-ACC-API-Key: {key} — Enterprise (orders.read, products.read)',
            ],
            'endpoints' => [
                [ 'GET',  '/public/arag/families', 'لیست محصولات' ],
                [ 'GET',  '/public/arag/shop/settings', 'تنظیمات فروشگاه' ],
                [ 'POST', '/public/arag/orders/create', 'ثبت سفارش' ],
                [ 'POST', '/public/arag/auth/send-otp', 'ارسال OTP' ],
                [ 'POST', '/public/arag/auth/verify-otp', 'تأیید OTP' ],
                [ 'GET',  '/public/arag/account/dashboard', 'داشبورد مشتری (JWT)' ],
                [ 'GET',  '/arag/admin/products', 'مدیریت محصولات (JWT+ACL)' ],
                [ 'GET',  '/arag/erp/dashboard', 'ERP فروشگاه (JWT)' ],
                [ 'GET',  '/arag/shop-acct/dashboard', 'حسابداری فروش (JWT)' ],
                [ 'GET',  '/public/platform/features', 'مقایسه پلن‌ها' ],
            ],
            'webhooks' => array_keys( self::webhook_events() ),
        ];
    }

    public static function order_payload( int $order_id ): ?array {
        global $wpdb;
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT id, order_number, subtotal, total, discount_amount, payment_status, order_status,
                    billing_name, billing_phone, payment_method, shipping_method, created_at
             FROM {$wpdb->prefix}arag_orders WHERE id = %d", $order_id
        ), ARRAY_A );
        return $row ?: null;
    }
}
