<?php
/**
 * نصب حسابداری EduBrain — سرفصل‌ها · قالب رویداد · پورتال
 * php run-education-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();

$chart = Acc_Portal_Accounting::ensure_chart( 'education' );

$tpl_ex = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT id FROM {$pre}ai_acc_event_templates WHERE event_type=%s AND version=1", 'EDU_SESSION_INVOICE'
) );
if ( ! $tpl_ex ) {
    $wpdb->insert( "{$pre}ai_acc_event_templates", [
        'event_type'    => 'EDU_SESSION_INVOICE',
        'version'       => 1,
        'template_name' => 'فاکتور جلسه آموزشی — بهای تمام‌شده',
        'mapping_logic' => wp_json_encode( [
            'note'  => 'از manual_entries.pairs در payload استفاده می‌شود',
            'pairs' => [],
        ], JSON_UNESCAPED_UNICODE ),
        'description'   => 'EduBrain — حق‌الزحمه · ایاب‌ذهاب · سربار · مواد',
        'is_active'     => 1,
    ] );
}

if ( ! get_option( 'education_portal_office' ) ) {
    update_option( 'education_portal_office', Acc_Portal_Accounting::portal_settings( 'education' ), false );
}

require_once ACC_PATH . 'includes/helpers/education-cost-accounting.php';
$cfg_t = Edu_Cost_Accounting::config_table();
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $cfg_t ) ) === $cfg_t ) {
    $cfg_ex = (int) $wpdb->get_var( "SELECT id FROM {$cfg_t} LIMIT 1" );
    if ( ! $cfg_ex ) {
        $wpdb->insert( $cfg_t, [
            'payload' => wp_json_encode( Edu_Cost_Accounting::default_config(), JSON_UNESCAPED_UNICODE ),
        ] );
    }
}

update_option( 'acc_education_accounting_version', '1.0' );

echo json_encode( [
    'success' => true,
    'version' => '1.0',
    'chart'   => $chart,
    'portal'  => Acc_Portal_Accounting::portal_settings( 'education' ),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
