<?php
/**
 * نصب ماژول بازاریاب فروشگاه عرقیات
 * http://localhost/acc-engine/run-arag-marketer-install.php
 */
declare(strict_types=1);

if ( ! defined( 'ACC_BASE_PATH' ) ) {
    define( 'ACC_BASE_PATH', __DIR__ );
    require __DIR__ . '/standalone/bootstrap.php';
}

header( 'Content-Type: application/json; charset=utf-8' );
global $wpdb;
$pre     = $wpdb->prefix;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
$log     = [];

$ddl = [
    "CREATE TABLE IF NOT EXISTS {$pre}arag_marketer_accounts (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
        phone VARCHAR(20) NOT NULL,
        display_name VARCHAR(200) NOT NULL DEFAULT '',
        national_id VARCHAR(20) NULL,
        city VARCHAR(100) NULL,
        address VARCHAR(500) NULL,
        bank_sheba VARCHAR(34) NULL,
        bank_card VARCHAR(20) NULL,
        bank_name VARCHAR(120) NULL,
        marketer_code VARCHAR(16) NOT NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'pending',
        credit_balance DECIMAL(14,0) NOT NULL DEFAULT 0,
        credit_limit DECIMAL(14,0) NOT NULL DEFAULT 5000000,
        total_sales DECIMAL(14,0) NOT NULL DEFAULT 0,
        total_earned DECIMAL(14,0) NOT NULL DEFAULT 0,
        balance_pending DECIMAL(14,0) NOT NULL DEFAULT 0,
        balance_payable DECIMAL(14,0) NOT NULL DEFAULT 0,
        balance_paid DECIMAL(14,0) NOT NULL DEFAULT 0,
        shops_count INT NOT NULL DEFAULT 0,
        orders_count INT NOT NULL DEFAULT 0,
        admin_note VARCHAR(500) NULL,
        approved_at DATETIME NULL,
        approved_by BIGINT UNSIGNED NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY phone (phone),
        UNIQUE KEY marketer_code (marketer_code),
        KEY status (status),
        KEY user_id (user_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}arag_marketer_shops (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        marketer_id BIGINT UNSIGNED NOT NULL,
        shop_phone VARCHAR(20) NOT NULL,
        shop_name VARCHAR(200) NOT NULL DEFAULT '',
        owner_name VARCHAR(200) NOT NULL DEFAULT '',
        city VARCHAR(100) NULL,
        address VARCHAR(500) NULL,
        lat DECIMAL(10,7) NULL,
        lng DECIMAL(10,7) NULL,
        notes TEXT NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'active',
        total_orders INT NOT NULL DEFAULT 0,
        total_sales DECIMAL(14,0) NOT NULL DEFAULT 0,
        first_order_at DATETIME NULL,
        last_order_at DATETIME NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY shop_phone (shop_phone),
        KEY marketer_id (marketer_id),
        KEY status (status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}arag_marketer_commissions (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        marketer_id BIGINT UNSIGNED NULL,
        shop_id BIGINT UNSIGNED NULL,
        order_id BIGINT UNSIGNED NOT NULL,
        attribution VARCHAR(30) NOT NULL DEFAULT 'marketer',
        order_total DECIMAL(14,0) NOT NULL DEFAULT 0,
        marketer_pct DECIMAL(6,3) NOT NULL DEFAULT 0,
        site_pct DECIMAL(6,3) NOT NULL DEFAULT 0,
        marketer_amount DECIMAL(14,0) NOT NULL DEFAULT 0,
        site_amount DECIMAL(14,0) NOT NULL DEFAULT 0,
        status VARCHAR(20) NOT NULL DEFAULT 'pending',
        payment_mode VARCHAR(30) NULL,
        note VARCHAR(255) NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        earned_at DATETIME NULL,
        paid_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY order_id (order_id),
        KEY marketer_id (marketer_id),
        KEY shop_id (shop_id),
        KEY status (status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}arag_marketer_credit_ledger (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        marketer_id BIGINT UNSIGNED NOT NULL,
        entry_type VARCHAR(30) NOT NULL,
        amount DECIMAL(14,0) NOT NULL DEFAULT 0,
        balance_after DECIMAL(14,0) NOT NULL DEFAULT 0,
        order_id BIGINT UNSIGNED NULL,
        note VARCHAR(255) NULL,
        created_by BIGINT UNSIGNED NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY marketer_id (marketer_id),
        KEY entry_type (entry_type),
        KEY order_id (order_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}arag_marketer_payouts (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        marketer_id BIGINT UNSIGNED NOT NULL,
        amount DECIMAL(14,0) NOT NULL DEFAULT 0,
        status VARCHAR(20) NOT NULL DEFAULT 'requested',
        bank_snapshot JSON NULL,
        admin_note VARCHAR(255) NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        processed_at DATETIME NULL,
        processed_by BIGINT UNSIGNED NULL,
        PRIMARY KEY (id),
        KEY marketer_id (marketer_id),
        KEY status (status)
    ) {$charset}",
];

foreach ( $ddl as $sql ) {
    $ok = $wpdb->query( $sql );
    $log[] = [ 'ddl' => substr( $sql, 0, 60 ) . '…', 'ok' => $ok !== false ];
}

$order_cols = [
    'marketer_id'              => "BIGINT UNSIGNED NULL",
    'marketer_shop_id'         => "BIGINT UNSIGNED NULL",
    'attribution_type'         => "VARCHAR(30) NULL",
    'commission_marketer_pct'  => "DECIMAL(6,3) NOT NULL DEFAULT 0",
    'commission_site_pct'      => "DECIMAL(6,3) NOT NULL DEFAULT 0",
    'marketer_commission_amt'  => "DECIMAL(14,0) NOT NULL DEFAULT 0",
    'site_commission_amt'      => "DECIMAL(14,0) NOT NULL DEFAULT 0",
    'sold_by_marketer_id'      => "BIGINT UNSIGNED NULL",
];

foreach ( $order_cols as $col => $def ) {
    $exists = $wpdb->get_var( "SHOW COLUMNS FROM {$pre}arag_orders LIKE '{$col}'" );
    if ( ! $exists ) {
        $wpdb->query( "ALTER TABLE {$pre}arag_orders ADD COLUMN {$col} {$def}" );
        $log[] = "arag_orders.{$col}";
    }
}

if ( ! $wpdb->get_var( "SHOW INDEX FROM {$pre}arag_orders WHERE Key_name='marketer_id'" ) ) {
    $wpdb->query( "ALTER TABLE {$pre}arag_orders ADD KEY marketer_id (marketer_id)" );
}

/* ACL permission — schema: permission_key, label, module, resource, action */
$perm = 'shop.marketer';
if ( $wpdb->get_var( "SHOW TABLES LIKE '{$pre}acl_permissions'" ) ) {
    $has = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$pre}acl_permissions WHERE permission_key=%s", $perm
    ) );
    if ( ! $has ) {
        $wpdb->insert( "{$pre}acl_permissions", [
            'permission_key' => $perm,
            'label'          => 'مدیریت بازاریاب فروشگاه',
            'module'         => 'shop',
            'resource'       => 'marketer',
            'action'         => 'manage',
            'is_system'      => 0,
        ] );
        $log[] = 'acl_permission shop.marketer';
    }
}

echo json_encode( [
    'success' => true,
    'message' => 'ماژول بازاریاب فروشگاه نصب شد',
    'tables'  => [
        'arag_marketer_accounts'      => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}arag_marketer_accounts'" ),
        'arag_marketer_shops'         => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}arag_marketer_shops'" ),
        'arag_marketer_commissions'   => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}arag_marketer_commissions'" ),
        'arag_marketer_credit_ledger' => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}arag_marketer_credit_ledger'" ),
        'arag_marketer_payouts'       => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}arag_marketer_payouts'" ),
    ],
    'log' => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
