<?php
/**
 * نصب پورتال رشدگاه / شبکه سفیران — جداول · نقش‌ها · دمو
 * php run-growth-portal-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';
$pass    = 'Growth1234';
$log     = [];

$ddl = [
    "CREATE TABLE IF NOT EXISTS {$pre}growth_services (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        slug VARCHAR(40) NOT NULL,
        title VARCHAR(200) NOT NULL DEFAULT '',
        tagline VARCHAR(255) NOT NULL DEFAULT '',
        form_type VARCHAR(30) NOT NULL DEFAULT 'package',
        packages_json JSON NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        sort_order INT NOT NULL DEFAULT 0,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY slug (slug)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}growth_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        order_code VARCHAR(24) NOT NULL,
        user_id BIGINT UNSIGNED NULL,
        service_slug VARCHAR(40) NOT NULL,
        package_code VARCHAR(40) NOT NULL DEFAULT '',
        customer_name VARCHAR(200) NOT NULL DEFAULT '',
        customer_phone VARCHAR(30) NOT NULL DEFAULT '',
        customer_email VARCHAR(200) NOT NULL DEFAULT '',
        amount DECIMAL(14,2) NOT NULL DEFAULT 0,
        status VARCHAR(30) NOT NULL DEFAULT 'submitted',
        invoice_status VARCHAR(30) NOT NULL DEFAULT 'stub',
        ambassador_id BIGINT UNSIGNED NULL,
        referral_code VARCHAR(24) NULL,
        payload_json JSON NULL,
        confirmed_at DATETIME NULL,
        confirmed_by BIGINT UNSIGNED NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY order_code (order_code),
        KEY status (status),
        KEY service_slug (service_slug),
        KEY ambassador_id (ambassador_id),
        KEY user_id (user_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}growth_ambassadors (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NULL,
        display_name VARCHAR(200) NOT NULL DEFAULT '',
        phone VARCHAR(30) NOT NULL,
        email VARCHAR(200) NOT NULL DEFAULT '',
        city VARCHAR(100) NOT NULL DEFAULT '',
        path VARCHAR(30) NOT NULL DEFAULT 'neighbor',
        tier VARCHAR(30) NOT NULL DEFAULT 'neighbor',
        referral_code VARCHAR(16) NOT NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'active',
        ethics_accepted TINYINT(1) NOT NULL DEFAULT 0,
        ethics_accepted_at DATETIME NULL,
        compliance_ack TINYINT(1) NOT NULL DEFAULT 0,
        commission_pct DECIMAL(6,3) NOT NULL DEFAULT 10.000,
        allow_subtree TINYINT(1) NOT NULL DEFAULT 0,
        total_leads INT NOT NULL DEFAULT 0,
        converted_leads INT NOT NULL DEFAULT 0,
        total_earned DECIMAL(14,2) NOT NULL DEFAULT 0,
        balance_pending DECIMAL(14,2) NOT NULL DEFAULT 0,
        balance_paid DECIMAL(14,2) NOT NULL DEFAULT 0,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY referral_code (referral_code),
        UNIQUE KEY phone (phone),
        KEY user_id (user_id),
        KEY path (path),
        KEY status (status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}growth_leads (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        ambassador_id BIGINT UNSIGNED NOT NULL,
        order_id BIGINT UNSIGNED NULL,
        customer_name VARCHAR(200) NOT NULL DEFAULT '',
        customer_phone VARCHAR(30) NOT NULL DEFAULT '',
        service_interest VARCHAR(40) NOT NULL DEFAULT 'website',
        notes TEXT NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'introduced',
        source VARCHAR(30) NOT NULL DEFAULT 'manual',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY ambassador_id (ambassador_id),
        KEY order_id (order_id),
        KEY status (status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}growth_commissions (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        ambassador_id BIGINT UNSIGNED NOT NULL,
        order_id BIGINT UNSIGNED NULL,
        level TINYINT UNSIGNED NOT NULL DEFAULT 1,
        order_amount DECIMAL(14,2) NOT NULL DEFAULT 0,
        commission_pct DECIMAL(6,3) NOT NULL DEFAULT 0,
        commission_amount DECIMAL(14,2) NOT NULL DEFAULT 0,
        status VARCHAR(20) NOT NULL DEFAULT 'pending',
        dedupe_key VARCHAR(80) NULL,
        note VARCHAR(255) NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        approved_at DATETIME NULL,
        paid_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY dedupe_key (dedupe_key),
        KEY ambassador_id (ambassador_id),
        KEY status (status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}growth_sessions (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        workshop_code VARCHAR(40) NOT NULL DEFAULT '',
        title VARCHAR(200) NOT NULL DEFAULT '',
        starts_at DATETIME NOT NULL,
        duration_min INT UNSIGNED NOT NULL DEFAULT 180,
        seats_total INT UNSIGNED NOT NULL DEFAULT 12,
        seats_taken INT UNSIGNED NOT NULL DEFAULT 0,
        price DECIMAL(14,2) NOT NULL DEFAULT 2500000,
        status VARCHAR(20) NOT NULL DEFAULT 'open',
        notes TEXT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        PRIMARY KEY (id),
        KEY starts_at (starts_at),
        KEY status (status)
    ) {$charset}",
];

foreach ( $ddl as $sql ) {
    $wpdb->query( $sql );
    $log[] = 'ddl:ok';
}

require_once ACC_PATH . 'includes/helpers/growth-platform.php';

/* سرویس‌ها */
foreach ( Growth_Platform::service_catalog() as $svc ) {
    $exists = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}growth_services WHERE slug=%s", $svc['slug']
    ) );
    $row = [
        'slug'          => $svc['slug'],
        'title'         => $svc['title'],
        'tagline'       => $svc['tagline'],
        'form_type'     => $svc['form'],
        'packages_json' => wp_json_encode( $svc['packages'], JSON_UNESCAPED_UNICODE ),
        'is_active'     => 1,
    ];
    if ( $exists ) {
        $wpdb->update( "{$pre}growth_services", $row, [ 'id' => $exists ] );
    } else {
        $wpdb->insert( "{$pre}growth_services", $row );
    }
    $log[] = 'service:' . $svc['slug'];
}

/* جلسات کارگاه */
$session_seeds = [
    [ 'invoice-basics', 'کارگاه فاکتور و دفتر', '+3 days 10:00', 12, 2500000 ],
    [ 'abc-lite',       'کارگاه ABC ساده',     '+5 days 16:00', 10, 2800000 ],
    [ 'read-balance',   'کارگاه خواندن تراز',  '+8 days 10:00', 12, 2600000 ],
    [ 'invoice-basics', 'کارگاه فاکتور — نوبت ۲', '+12 days 17:00', 8, 2500000 ],
];
foreach ( $session_seeds as $s ) {
    $starts = date( 'Y-m-d H:i:s', strtotime( $s[2] ) );
    $exists = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}growth_sessions WHERE workshop_code=%s AND starts_at=%s",
        $s[0], $starts
    ) );
    if ( ! $exists ) {
        $wpdb->insert( "{$pre}growth_sessions", [
            'workshop_code' => $s[0],
            'title'         => $s[1],
            'starts_at'     => $starts,
            'duration_min'  => 180,
            'seats_total'   => $s[3],
            'seats_taken'   => 0,
            'price'         => $s[4],
            'status'        => 'open',
        ] );
        $log[] = 'session:' . $s[0];
    }
}

/* ACL */
$roles = [
    [ 'growth_admin', 'مدیر رشدگاه', 'مدیر پورتال رشدگاه و سفیران' ],
    [ 'growth_ambassador', 'سفیر همسایه', 'سفیر ارجاع خدمات' ],
    [ 'growth_referral', 'معرف دستگاه', 'مسیر ارجاع تک‌سطحی کارکنان دستگاه' ],
    [ 'growth_customer', 'مشتری رشدگاه', 'سفارش‌دهنده خدمات' ],
];
foreach ( $roles as $r ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $r[0] ) ) ) {
        $wpdb->insert( "{$pre}acl_roles", [
            'slug' => $r[0], 'label' => $r[1], 'description' => $r[2],
            'is_system' => 0, 'priority' => 50,
        ] );
        $log[] = 'role:' . $r[0];
    }
}

$perms = [
    [ 'growth.view', 'مشاهده پورتال رشدگاه', 'growth', 'portal', 'view' ],
    [ 'growth.order', 'ثبت سفارش خدمت', 'growth', 'order', 'create' ],
    [ 'growth.ambassador', 'داشبورد سفیر', 'growth', 'ambassador', 'view' ],
    [ 'growth.admin', 'مدیریت رشدگاه', 'growth', 'admin', 'manage' ],
];
foreach ( $perms as $p ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_permissions WHERE permission_key=%s", $p[0] ) ) ) {
        $wpdb->insert( "{$pre}acl_permissions", [
            'permission_key' => $p[0], 'label' => $p[1],
            'module' => $p[2], 'resource' => $p[3], 'action' => $p[4], 'is_system' => 1,
        ] );
    }
}

$role_perms = [
    'growth_admin'      => [ 'growth.view', 'growth.order', 'growth.ambassador', 'growth.admin' ],
    'growth_ambassador' => [ 'growth.view', 'growth.order', 'growth.ambassador' ],
    'growth_referral'   => [ 'growth.view', 'growth.order', 'growth.ambassador' ],
    'growth_customer'   => [ 'growth.view', 'growth.order' ],
];
foreach ( $role_perms as $slug => $pks ) {
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $slug ) );
    if ( ! $rid ) {
        continue;
    }
    foreach ( $pks as $pk ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)",
            $rid, $pk
        ) );
    }
}

$super = (int) $wpdb->get_var( "SELECT id FROM {$pre}acl_roles WHERE slug='super_admin' LIMIT 1" );
if ( $super ) {
    foreach ( [ 'growth.view', 'growth.order', 'growth.ambassador', 'growth.admin' ] as $pk ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)",
            $super, $pk
        ) );
    }
}

function growth_install_user( string $login, string $name, string $role, string $pass ): int {
    global $wpdb, $pre, $log;
    $id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->users} WHERE user_login=%s", $login ) );
    if ( ! $id ) {
        if ( function_exists( 'wp_create_user' ) ) {
            $created = wp_create_user( $login, $pass, $login . '@growth.local' );
            if ( ! is_wp_error( $created ) ) {
                $id = (int) $created;
                $wpdb->update( $wpdb->users, [ 'display_name' => $name ], [ 'ID' => $id ] );
                $log[] = "user:created:{$login}";
            }
        }
        if ( ! $id ) {
            $id = (int) $wpdb->get_var( "SELECT COALESCE(MAX(ID),0) FROM {$wpdb->users}" ) + 1;
            $hash = function_exists( 'wp_hash_password' ) ? wp_hash_password( $pass ) : password_hash( $pass, PASSWORD_BCRYPT );
            $wpdb->insert( $wpdb->users, [
                'ID' => $id, 'user_login' => $login, 'user_pass' => $hash,
                'user_nicename' => sanitize_title( $login ), 'user_email' => $login . '@growth.local',
                'user_registered' => current_time( 'mysql' ), 'display_name' => $name, 'user_status' => 0,
            ] );
            $log[] = "user:inserted:{$login}";
        }
    } else {
        $hash = function_exists( 'wp_hash_password' ) ? wp_hash_password( $pass ) : password_hash( $pass, PASSWORD_BCRYPT );
        $wpdb->update( $wpdb->users, [ 'user_pass' => $hash, 'display_name' => $name ], [ 'ID' => $id ] );
        $log[] = "user:updated:{$login}";
    }
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $role ) );
    if ( $rid && $id ) {
        $has = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(*) FROM {$pre}acl_user_roles WHERE user_id=%d AND role_id=%d", $id, $rid
        ) );
        if ( ! $has ) {
            $ok = $wpdb->insert( "{$pre}acl_user_roles", [
                'user_id' => $id, 'role_id' => $rid, 'scope_type' => 'global',
            ] );
            if ( ! $ok ) {
                $wpdb->query( $wpdb->prepare(
                    "INSERT IGNORE INTO {$pre}acl_user_roles (user_id, role_id) VALUES (%d, %d)",
                    $id, $rid
                ) );
            }
            $log[] = "role_link:{$login}:{$role}";
        }
    }
    return $id;
}

$uid_admin  = growth_install_user( 'growth_admin', 'مدیر رشدگاه', 'growth_admin', $pass );
$uid_amb    = growth_install_user( 'growth_ambassador', 'زهرا سفیر — همسایه', 'growth_ambassador', $pass );
$uid_ref    = growth_install_user( 'growth_referral', 'علی معرف — دستگاه اجرایی', 'growth_referral', $pass );
$uid_cust   = growth_install_user( 'growth_customer', 'مریم مشتری', 'growth_customer', $pass );

/* لینک ostadowner به growth.admin در صورت وجود */
$ostad = (int) $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_login='ostadowner' LIMIT 1" );
if ( $ostad && $super ) {
    $has = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$pre}acl_user_roles WHERE user_id=%d AND role_id=%d", $ostad, $super
    ) );
    // already super — growth.admin via super role perms
    $log[] = 'ostadowner:linked_via_super_admin';
}
$rid_admin = (int) $wpdb->get_var( "SELECT id FROM {$pre}acl_roles WHERE slug='growth_admin'" );
if ( $ostad && $rid_admin ) {
    $has = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$pre}acl_user_roles WHERE user_id=%d AND role_id=%d", $ostad, $rid_admin
    ) );
    if ( ! $has ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_user_roles (user_id, role_id, scope_type) VALUES (%d, %d, 'global')",
            $ostad, $rid_admin
        ) );
        $log[] = 'ostadowner:growth_admin_role';
    }
}

/* سفیران دمو */
function growth_seed_amb( int $uid, array $d ): int {
    global $wpdb, $pre;
    $exists = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}growth_ambassadors WHERE user_id=%d OR phone=%s LIMIT 1",
        $uid, $d['phone']
    ) );
    $row = array_merge( [
        'user_id' => $uid, 'status' => 'active', 'ethics_accepted' => 1,
        'ethics_accepted_at' => current_time( 'mysql' ),
        'commission_pct' => 10, 'allow_subtree' => 0,
        'created_at' => current_time( 'mysql' ),
    ], $d );
    if ( $exists ) {
        unset( $row['created_at'] );
        $wpdb->update( "{$pre}growth_ambassadors", $row, [ 'id' => $exists ] );
        return $exists;
    }
    $wpdb->insert( "{$pre}growth_ambassadors", $row );
    return (int) $wpdb->insert_id;
}

$amb_id = growth_seed_amb( $uid_amb, [
    'display_name' => 'زهرا سفیر — همسایه',
    'phone' => '09171234501',
    'email' => 'growth_ambassador@growth.local',
    'city' => 'شیراز',
    'path' => 'neighbor',
    'tier' => 'neighbor',
    'referral_code' => 'SFDEMO1',
] );
$ref_id = growth_seed_amb( $uid_ref, [
    'display_name' => 'علی معرف — دستگاه اجرایی',
    'phone' => '09171234502',
    'email' => 'growth_referral@growth.local',
    'city' => 'شیراز',
    'path' => 'device_referral',
    'tier' => 'device_referral',
    'referral_code' => 'DVDEMO1',
    'compliance_ack' => 1,
] );

/* سفارش و لید نمونه */
$demo_order = (int) $wpdb->get_var( "SELECT id FROM {$pre}growth_orders WHERE order_code='GODEMO01'" );
if ( ! $demo_order ) {
    $wpdb->insert( "{$pre}growth_orders", [
        'order_code' => 'GODEMO01',
        'user_id' => $uid_cust,
        'service_slug' => 'website',
        'package_code' => 'starter',
        'customer_name' => 'مریم مشتری',
        'customer_phone' => '09171234503',
        'customer_email' => 'growth_customer@growth.local',
        'amount' => 18000000,
        'status' => 'submitted',
        'invoice_status' => 'stub',
        'ambassador_id' => $amb_id,
        'referral_code' => 'SFDEMO1',
        'payload_json' => wp_json_encode( [ 'notes' => 'سفارش دمو استارتر', 'city' => 'شیراز' ], JSON_UNESCAPED_UNICODE ),
        'created_at' => current_time( 'mysql' ),
    ] );
    $demo_order = (int) $wpdb->insert_id;
    $wpdb->insert( "{$pre}growth_leads", [
        'ambassador_id' => $amb_id,
        'order_id' => $demo_order,
        'customer_name' => 'مریم مشتری',
        'customer_phone' => '09171234503',
        'service_interest' => 'website',
        'status' => 'introduced',
        'source' => 'order_form',
        'created_at' => current_time( 'mysql' ),
    ] );
    $wpdb->update( "{$pre}growth_ambassadors", [ 'total_leads' => 1 ], [ 'id' => $amb_id ] );
    $log[] = 'demo_order:GODEMO01';
}

update_option( 'acc_growth_version', '1.0' );

echo json_encode( [
    'success' => true,
    'version' => '1.0',
    'portal'  => '/acc-engine/growth.php',
    'tables'  => [
        'growth_services'     => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}growth_services'" ),
        'growth_orders'       => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}growth_orders'" ),
        'growth_ambassadors'  => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}growth_ambassadors'" ),
        'growth_leads'        => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}growth_leads'" ),
        'growth_commissions'  => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}growth_commissions'" ),
        'growth_sessions'     => (bool) $wpdb->get_var( "SHOW TABLES LIKE '{$pre}growth_sessions'" ),
    ],
    'demo' => [
        'password'   => $pass,
        'admin'      => [ 'login' => 'growth_admin', 'password' => $pass ],
        'ostadowner' => [ 'login' => 'ostadowner', 'note' => 'نقش growth_admin اضافه شد در صورت وجود' ],
        'ambassador' => [ 'login' => 'growth_ambassador', 'password' => $pass, 'code' => 'SFDEMO1' ],
        'referral'   => [ 'login' => 'growth_referral', 'password' => $pass, 'code' => 'DVDEMO1' ],
        'customer'   => [ 'login' => 'growth_customer', 'password' => $pass ],
    ],
    'log' => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
