<?php
/**
 * نصب حسابداری پورتال خدمات HVAC
 * php run-service-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;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}svc_acc_config (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    service_type VARCHAR(40) NULL COMMENT 'NULL = پیش‌فرض',
    payload JSON NOT NULL,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY service_type (service_type)
) {$charset}" );

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}svc_acc_splits (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    report_id BIGINT UNSIGNED NOT NULL,
    entity_type VARCHAR(20) NOT NULL,
    entity_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    entity_label VARCHAR(200) NOT NULL DEFAULT '',
    revenue_share DECIMAL(15,2) NOT NULL DEFAULT 0,
    cost_share DECIMAL(15,2) NOT NULL DEFAULT 0,
    fee_amount DECIMAL(15,2) NOT NULL DEFAULT 0,
    acc_event_id BIGINT UNSIGNED NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY report_id (report_id),
    KEY entity (entity_type, entity_id)
) {$charset}" );

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}svc_acc_journal (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    report_id BIGINT UNSIGNED NULL,
    event_type VARCHAR(60) NOT NULL,
    acc_event_id BIGINT UNSIGNED NOT NULL,
    amount DECIMAL(15,2) NOT NULL DEFAULT 0,
    status VARCHAR(20) NOT NULL DEFAULT 'posted',
    payload JSON NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY report_id (report_id),
    KEY acc_event_id (acc_event_id)
) {$charset}" );

$alters = [
    "ALTER TABLE {$pre}svc_reports ADD COLUMN acc_revenue_event_id BIGINT UNSIGNED NULL",
    "ALTER TABLE {$pre}svc_reports ADD COLUMN acc_splits_json JSON NULL",
];
foreach ( $alters as $sql ) {
    preg_match( '/ADD COLUMN (\w+)/', $sql, $m );
    $col = $m[1] ?? '';
    if ( $col && $wpdb->get_var( "SHOW COLUMNS FROM {$pre}svc_reports LIKE '{$col}'" ) ) continue;
    $wpdb->query( $sql );
}

require_once ACC_PATH . 'includes/helpers/svc-accounting.php';
$default = Svc_Accounting::default_config();
$exists = $wpdb->get_var( "SELECT id FROM {$pre}svc_acc_config WHERE service_type IS NULL OR service_type = '' LIMIT 1" );
if ( ! $exists ) {
    $wpdb->insert( "{$pre}svc_acc_config", [
        'service_type' => null,
        'payload'      => wp_json_encode( $default, JSON_UNESCAPED_UNICODE ),
    ] );
}

$service_types = [
    'repair' => [ 'tech_service_pct' => 18, 'senior_service_pct' => 6 ],
    'pm'     => [ 'tech_service_pct' => 12, 'senior_service_pct' => 4 ],
    'parts_supply' => [ 'tech_parts_pct' => 3, 'parts_cogs_pct' => 70 ],
    'install' => [ 'tech_service_pct' => 20, 'overhead_repair_pct' => 2.5 ],
];
foreach ( $service_types as $st => $over ) {
    $ex = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}svc_acc_config WHERE service_type=%s", $st ) );
    if ( $ex ) continue;
    $wpdb->insert( "{$pre}svc_acc_config", [
        'service_type' => $st,
        'payload'      => wp_json_encode( array_merge( $default, $over ), JSON_UNESCAPED_UNICODE ),
    ] );
}

$accounts = [
    [ 65, '5151', 'بهای تمام‌شده خدمات HVAC', 'expense', 60 ],
    [ 66, '5152', 'هزینه پاداش و تخفیف مشتری', 'expense', 60 ],
    [ 67, '5153', 'حق‌الزحمه کارشناس میدانی', 'expense', 60 ],
    [ 68, '5154', 'سهم کارشناس ارشد', 'expense', 60 ],
    [ 69, '5155', 'سربار انرژی و تعمیرگاه', 'expense', 60 ],
    [ 70, '2112', 'پرداختنی تأمین‌کنندگان خدمات', 'liability', 31 ],
];
foreach ( $accounts as [ $id, $code, $name, $type, $parent ] ) {
    $ex = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}ai_acc_accounts WHERE id=%d", $id ) );
    if ( $ex ) continue;
    $wpdb->insert( "{$pre}ai_acc_accounts", [
        'id' => $id, 'account_id' => $id, 'account_code' => $code,
        'account_name' => $name, 'account_type' => $type, 'parent_id' => $parent,
    ] );
}

$templates = [
    [ 'SERVICE_RECEIPT', 'دریافت وجه خدمات', json_encode( [
        'pairs' => [ [ 'dr_gl_id' => 14, 'cr_gl_id' => 21, 'source_field' => 'amount', 'desc' => 'دریافت وجه خدمات' ] ],
    ], JSON_UNESCAPED_UNICODE ) ],
    [ 'SERVICE_SUPPLIER_COST', 'هزینه تأمین‌کننده', json_encode( [
        'pairs' => [ [ 'dr_gl_id' => 65, 'cr_gl_id' => 70, 'source_field' => 'amount', 'desc' => 'بهای قطعه تأمین‌کننده' ] ],
    ], JSON_UNESCAPED_UNICODE ) ],
];
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'   => 'پورتال خدمات HVAC',
        'is_active'     => 1,
    ] );
}

$dim_groups = [
    [ 'SERVICE', 'خدمات HVAC', 'بُعد اختصاصی پورتال خدمات' ],
    [ 'PERSONNEL', 'پرسنل خدمات', 'کارشناس و کارشناس ارشد' ],
    [ 'COST_CENTER', 'مرکز هزینه پورتال', 'سربار انرژی و تعمیرگاه' ],
    [ 'BRANCH', 'شعبه خدمات', 'تفکیک دفاتر/شعب خدماتی' ],
];
foreach ( $dim_groups as [ $code, $name, $desc ] ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}ai_acc_dimension_groups WHERE group_code=%s", $code ) ) ) {
        $wpdb->insert( "{$pre}ai_acc_dimension_groups", [
            'group_code' => $code, 'group_name' => $name, 'description' => $desc, 'sort_order' => 50,
        ] );
    }
}

// حذف template خالی SERVICE_INVOICE (از payload دستی استفاده می‌شود)
$wpdb->query( $wpdb->prepare(
    "DELETE FROM {$pre}ai_acc_event_templates WHERE event_type=%s AND (mapping_logic='{}' OR mapping_logic='')",
    'SERVICE_INVOICE'
) );

if ( ! get_option( 'svc_portal_office' ) ) {
    update_option( 'svc_portal_office', Svc_Accounting::default_portal(), false );
}

// صدور توسط حسابدار — پیش‌فرض auto_post خاموش
$wpdb->query( "UPDATE {$pre}svc_acc_config SET payload = JSON_SET(payload, '$.auto_post', false) WHERE service_type IS NULL OR service_type = ''" );

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

update_option( 'acc_engine_db_version', '18.1' );

echo json_encode( [
    'success' => true,
    'db_version' => '18.1',
    'tables' => [ 'svc_acc_config', 'svc_acc_splits', 'svc_acc_journal' ],
    'gl_accounts' => [ 65, 66, 67, 68, 69, 70 ],
    'templates' => array_column( $templates, 0 ),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
