<?php
/**
 * نصب حسابداری مجزا per-portal — سرفصل‌های خودکار
 * php run-portal-accounting-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;

require_once ACC_PATH . 'includes/helpers/acc-schema.php';
require_once ACC_PATH . 'includes/helpers/acc-portal-accounting.php';
Acc_Schema::ensure_core_tables();

$alters = [
    "ALTER TABLE {$pre}ai_acc_accounts ADD COLUMN source_module VARCHAR(40) NULL COMMENT 'پورتال مالک سرفصل'",
    "ALTER TABLE {$pre}election_transactions ADD COLUMN acc_event_id BIGINT UNSIGNED NULL",
];
foreach ( $alters as $sql ) {
    preg_match( '/ALTER TABLE \S+ ADD COLUMN (\w+)/', $sql, $m );
    $col = $m[1] ?? '';
    preg_match( '/ALTER TABLE (\S+)/', $sql, $tm );
    $table = str_replace( '`', '', $tm[1] ?? '' );
    if ( ! $col || ! $table ) {
        continue;
    }
    $exists = $wpdb->get_var( $wpdb->prepare(
        'SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = %s',
        $table, $col
    ) );
    if ( $exists ) {
        continue;
    }
    $wpdb->query( $sql );
}

$charts = Acc_Portal_Accounting::ensure_all_charts();

$templates = [
    [ 'ELECTION_RECEIPT', 'دریافت مالی کمپین', json_encode( [
        'pairs' => [ [ 'dr_gl_id' => 3113, 'cr_gl_id' => 3141, 'source_field' => 'amount', 'desc' => 'دریافت کمک مالی' ] ],
    ], JSON_UNESCAPED_UNICODE ) ],
    [ 'ELECTION_EXPENSE', 'هزینه کمپین', json_encode( [
        'pairs' => [ [ 'dr_gl_id' => 3159, 'cr_gl_id' => 3113, 'source_field' => 'amount', 'desc' => 'هزینه کمپین' ] ],
    ], JSON_UNESCAPED_UNICODE ) ],
];
$tpl_created = 0;
foreach ( $templates as [ $type, $name, $logic ] ) {
    $ex = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}ai_acc_event_templates WHERE event_type=%s AND version=1", $type
    ) );
    if ( $ex ) {
        continue;
    }
    $wpdb->insert( "{$pre}ai_acc_event_templates", [
        'event_type'    => $type,
        'version'       => 1,
        'template_name' => $name,
        'mapping_logic' => $logic,
        'description'   => 'پورتال هواداران — حسابداری مجزا',
        'is_active'     => 1,
    ] );
    $tpl_created++;
}

if ( ! get_option( 'election_portal_office' ) ) {
    update_option( 'election_portal_office', Acc_Portal_Accounting::portal_settings( 'election' ), false );
}

$perm_keys = [
    'election.accounting'      => 'مشاهده حسابداری کمپین',
    'election.accounting.post' => 'صدور سند حسابداری کمپین',
];
foreach ( $perm_keys as $pk => $label ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_permissions WHERE permission_key=%s", $pk ) ) ) {
        $wpdb->insert( "{$pre}acl_permissions", [
            'permission_key' => $pk,
            'label'          => $label,
            'module'         => 'election',
            'resource'       => 'accounting',
            'action'         => strpos( $pk, '.post' ) ? 'post' : 'view',
            'is_system'      => 1,
        ] );
    }
}
$roles = [ 'election_dept_financial', 'election_admin', 'accountant' ];
foreach ( $roles as $slug ) {
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s LIMIT 1", $slug ) );
    if ( ! $rid ) {
        continue;
    }
    foreach ( array_keys( $perm_keys ) as $pk ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)",
            $rid, $pk
        ) );
    }
}

update_option( 'acc_portal_accounting_version', '20.0' );

echo json_encode( [
    'success'  => true,
    'version'  => '20.0',
    'charts'   => $charts,
    'templates_created' => $tpl_created,
    'portals'  => Acc_Portal_Accounting::list_portals(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
