<?php
/**
 * نصب ERP فروشگاه عرقیات — حسابداری · CRM · حمل‌ونقل
 * php run-arag-erp-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     = [];

/* ── CRM tables ── */
$crm_sql = file_get_contents( ACC_PATH . 'includes/sql/crm_schema.sql' );
if ( $crm_sql ) {
    $crm_sql = str_replace( 'wp_', $pre, $crm_sql );
    foreach ( array_filter( array_map( 'trim', explode( ';', $crm_sql ) ) ) as $stmt ) {
        if ( stripos( $stmt, 'CREATE TABLE' ) !== false ) {
            $wpdb->query( $stmt );
        }
    }
    $log[] = 'crm_tables';
}

$crm_cols = [
    'arag_order_id' => "INT NULL COMMENT 'سفارش فروشگاه'",
    'lead_channel'  => "VARCHAR(20) NULL DEFAULT NULL COMMENT 'shop|service|...'",
];
foreach ( $crm_cols as $col => $def ) {
    if ( ! $wpdb->get_var( "SHOW COLUMNS FROM {$pre}crm_leads LIKE '{$col}'" ) ) {
        $wpdb->query( "ALTER TABLE {$pre}crm_leads ADD COLUMN {$col} {$def}" );
        $log[] = "crm_leads.{$col}";
    }
}

/* ── Arag ERP config / journal ── */
$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_erp_config (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    payload JSON NOT NULL,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) {$charset}" );

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_erp_journal (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    order_id BIGINT UNSIGNED NOT NULL,
    event_type VARCHAR(40) NOT NULL,
    acc_event_id BIGINT UNSIGNED NOT NULL,
    amount DECIMAL(15,2) NOT NULL DEFAULT 0,
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    posted_by BIGINT UNSIGNED NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY order_id (order_id),
    KEY acc_event_id (acc_event_id)
) {$charset}" );

$order_cols = [
    'crm_lead_id'       => 'BIGINT UNSIGNED NULL',
    'ship_shipment_id'  => 'INT NULL',
    'acc_event_id'      => 'BIGINT UNSIGNED NULL',
    'inv_voucher_id'    => 'INT NULL',
    'erp_synced_at'     => 'DATETIME NULL',
];
foreach ( $order_cols as $col => $def ) {
    if ( ! $wpdb->get_var( "SHOW COLUMNS FROM {$pre}arag_orders LIKE '{$col}'" ) ) {
        $wpdb->query( "ALTER TABLE {$pre}arag_orders ADD COLUMN {$col} {$def}" );
        $log[] = "arag_orders.{$col}";
    }
}

require_once ACC_PATH . 'includes/helpers/arag-erp.php';
$cfg_exists = $wpdb->get_var( "SELECT id FROM {$pre}arag_erp_config LIMIT 1" );
if ( ! $cfg_exists ) {
    $wpdb->insert( "{$pre}arag_erp_config", [
        'payload' => wp_json_encode( Arag_Erp::get_config(), JSON_UNESCAPED_UNICODE ),
    ] );
    $log[] = 'default_config';
}

/* ── SHOP_SALE event template ── */
$tpl = $wpdb->get_var( $wpdb->prepare(
    "SELECT id FROM {$pre}ai_acc_event_templates WHERE event_type = %s AND version = 1", 'SHOP_SALE'
) );
if ( ! $tpl ) {
    $wpdb->insert( "{$pre}ai_acc_event_templates", [
        'event_type'    => 'SHOP_SALE',
        'version'       => 1,
        'template_name' => 'فروش فروشگاه عرقیات',
        'mapping_logic' => wp_json_encode( [
            'pairs' => [
                [ 'dr_gl_id' => 14, 'cr_gl_id' => 51, 'source_field' => 'total_amount', 'desc' => 'فروش عرقیات' ],
            ],
        ], JSON_UNESCAPED_UNICODE ),
        'description'   => 'فروشگاه آنلاین عرقیات',
        'is_active'     => 1,
    ] );
    $log[] = 'SHOP_SALE_template';
}

/* ── Ship methods for shop ── */
if ( $wpdb->get_var( "SHOW TABLES LIKE '{$pre}ship_methods'" ) === "{$pre}ship_methods" ) {
    $methods = [
        [ 'post', 'پست پیشتاز', '📮', 3 ],
        [ 'tipax', 'تیپاکس', '🚚', 2 ],
        [ 'pickup', 'تحویل حضوری', '🏪', 0 ],
    ];
    foreach ( $methods as [ $code, $name, $icon, $days ] ) {
        $ex = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}ship_methods WHERE code = %s", $code ) );
        if ( $ex ) continue;
        $wpdb->insert( "{$pre}ship_methods", [
            'code' => $code, 'name' => $name, 'icon' => $icon,
            'avg_days' => $days, 'is_active' => 1,
        ] );
        $log[] = "ship_method:{$code}";
    }
}

/* ── ACL permissions ── */
$perms = [
    [ 'shop.manage',          'مدیریت فروشگاه',       'shop', 'shop', 'manage' ],
    [ 'shop.erp',             'ERP فروشگاه',          'shop', 'shop', 'erp' ],
    [ 'shop.accounting',      'حسابداری فروشگاه',    'shop', 'shop', 'accounting' ],
    [ 'shop.accounting.post', 'صدور سند فروشگاه',    'shop', 'shop', 'accounting_post' ],
    [ 'ship.view',            'مشاهده حمل‌ونقل',     'ship', 'ship', 'view' ],
    [ 'ship.manage',          'مدیریت حمل‌ونقل',     'ship', 'ship', 'manage' ],
];
foreach ( $perms as [ $key, $label, $mod, $res, $act ] ) {
    $ex = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_permissions WHERE perm_key = %s", $key ) );
    if ( $ex ) continue;
    $wpdb->insert( "{$pre}acl_permissions", [
        'perm_key' => $key, 'label' => $label, 'module' => $mod, 'resource' => $res, 'action' => $act,
    ] );
    $log[] = "perm:{$key}";
}

$role_perms = [
    'accountant' => [ 'shop.erp', 'shop.accounting', 'shop.accounting.post', 'ship.view', 'ship.manage' ],
    'manager'    => [ 'shop.manage', 'shop.erp', 'shop.accounting', 'ship.view' ],
];
foreach ( $role_perms as $role_slug => $keys ) {
    $role_id = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}acl_roles WHERE slug = %s", $role_slug
    ) );
    if ( ! $role_id ) continue;
    foreach ( $keys as $pk ) {
        $pid = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$pre}acl_permissions WHERE perm_key = %s", $pk
        ) );
        if ( ! $pid ) continue;
        $ex = $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$pre}acl_role_permissions WHERE role_id = %d AND permission_id = %d", $role_id, $pid
        ) );
        if ( $ex ) continue;
        $wpdb->insert( "{$pre}acl_role_permissions", [ 'role_id' => $role_id, 'permission_id' => $pid ] );
        $log[] = "role:{$role_slug}:{$pk}";
    }
}

/* ── Demo accountant user for shop ── */
$demo_user = 'arag_accountant';
$demo_pass = 'Demo@2026';
$uid = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT ID FROM {$wpdb->users} WHERE user_login = %s AND ID > 0", $demo_user
) );
if ( ! $uid ) {
    $new_id = (int) $wpdb->get_var( "SELECT COALESCE( MAX( ID ), 0 ) + 1 FROM {$wpdb->users}" );
    $wpdb->insert( $wpdb->users, [
        'ID'              => $new_id,
        'user_login'      => $demo_user,
        'user_pass'       => password_hash( $demo_pass, PASSWORD_BCRYPT ),
        'user_nicename'   => 'arag-accountant',
        'user_email'      => 'arag.accountant@acc.local',
        'user_registered' => current_time( 'mysql' ),
        'display_name'    => 'حسابدار فروشگاه',
    ] );
    $uid = $new_id;
    $log[] = 'user:arag_accountant';
}
$acc_role = (int) $wpdb->get_var( "SELECT id FROM {$pre}acl_roles WHERE slug = 'accountant'" );
if ( $uid && $acc_role ) {
    $ex = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}acl_user_roles WHERE user_id = %d AND role_id = %d", $uid, $acc_role
    ) );
    if ( ! $ex ) {
        $wpdb->insert( "{$pre}acl_user_roles", [ 'user_id' => $uid, 'role_id' => $acc_role ] );
        $log[] = 'role_assigned:arag_accountant';
    }
}

echo wp_json_encode( [
    'success' => true,
    'message' => 'نصب ERP فروشگاه تکمیل شد',
    'changes' => $log,
    'demo_user' => [
        'login'    => 'arag_accountant',
        'password' => 'Demo@2026',
        'panel'    => '/acc-engine/shop-erp.php',
    ],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
