<?php
/**
 * نصب پورتال EduBrain — جداول · نقش‌ها · داده نمونه
 * php run-education-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';

$ddl = [
    "CREATE TABLE IF NOT EXISTS {$pre}edu_learners (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        grade_level VARCHAR(40) NOT NULL DEFAULT '',
        track VARCHAR(30) NOT NULL DEFAULT 'general',
        school_org_id BIGINT UNSIGNED NULL,
        profile_json JSON NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY user_id (user_id),
        KEY track (track)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_learner_academic_log (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        learner_id BIGINT UNSIGNED NOT NULL,
        category VARCHAR(40) NOT NULL DEFAULT '',
        title VARCHAR(200) NOT NULL DEFAULT '',
        payload_json JSON NULL,
        entry_date DATE NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY learner_id (learner_id),
        KEY entry_date (entry_date)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_learner_skill_log (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        learner_id BIGINT UNSIGNED NOT NULL,
        category VARCHAR(40) NOT NULL DEFAULT '',
        title VARCHAR(200) NOT NULL DEFAULT '',
        payload_json JSON NULL,
        entry_date DATE NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY learner_id (learner_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_educators (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        educator_type VARCHAR(20) NOT NULL DEFAULT 'mentor',
        verified_status VARCHAR(20) NOT NULL DEFAULT 'pending',
        hourly_rate DECIMAL(15,2) NOT NULL DEFAULT 800000,
        rating_avg DECIMAL(3,2) NOT NULL DEFAULT 4.5,
        profile_json JSON NULL,
        delivery_modes_json JSON NULL,
        venue_types_json JSON NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY user_id (user_id),
        KEY verified_status (verified_status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_organizations (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        org_type VARCHAR(30) NOT NULL DEFAULT 'school',
        name VARCHAR(200) NOT NULL DEFAULT '',
        city VARCHAR(80) NOT NULL DEFAULT '',
        address_text VARCHAR(500) NOT NULL DEFAULT '',
        profile_json JSON NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY org_type (org_type, is_active)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_org_resources (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        org_id BIGINT UNSIGNED NOT NULL,
        resource_type VARCHAR(40) NOT NULL DEFAULT 'classroom',
        name VARCHAR(200) NOT NULL DEFAULT '',
        capacity INT UNSIGNED NOT NULL DEFAULT 20,
        price_per_hour DECIMAL(15,2) NOT NULL DEFAULT 200000,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY org_id (org_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_org_schedule (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        org_id BIGINT UNSIGNED NOT NULL,
        resource_id BIGINT UNSIGNED NULL,
        slot_date DATE NOT NULL,
        start_time TIME NOT NULL,
        end_time TIME NOT NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'available',
        price_override DECIMAL(15,2) NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY org_date (org_id, slot_date)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_sessions (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        learner_id BIGINT UNSIGNED NOT NULL,
        educator_id BIGINT UNSIGNED NULL,
        session_type VARCHAR(20) NOT NULL DEFAULT 'academic',
        track VARCHAR(30) NOT NULL DEFAULT 'general',
        domain VARCHAR(40) NOT NULL DEFAULT 'math',
        delivery_mode VARCHAR(20) NOT NULL DEFAULT 'virtual',
        venue_type VARCHAR(20) NOT NULL DEFAULT 'online',
        org_id BIGINT UNSIGNED NULL,
        resource_id BIGINT UNSIGNED NULL,
        address_text TEXT NULL,
        distance_km DECIMAL(8,2) NOT NULL DEFAULT 0,
        scheduled_at DATETIME NULL,
        duration_min INT UNSIGNED NOT NULL DEFAULT 90,
        status VARCHAR(30) NOT NULL DEFAULT 'submitted',
        notes TEXT NULL,
        quote_json JSON NULL,
        cost_json JSON NULL,
        report_json JSON NULL,
        amount_total DECIMAL(15,2) NOT NULL DEFAULT 0,
        acc_event_id BIGINT UNSIGNED NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        completed_at DATETIME NULL,
        PRIMARY KEY (id),
        KEY learner_id (learner_id),
        KEY educator_id (educator_id),
        KEY status (status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_assessments (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        learner_id BIGINT UNSIGNED NOT NULL,
        assess_type VARCHAR(30) NOT NULL DEFAULT 'placement',
        track VARCHAR(30) NOT NULL DEFAULT 'general',
        results_json JSON NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY learner_id (learner_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_service_requests (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        learner_id BIGINT UNSIGNED NOT NULL,
        ref_code VARCHAR(24) NOT NULL DEFAULT '',
        session_type VARCHAR(20) NOT NULL DEFAULT 'academic',
        track VARCHAR(30) NOT NULL DEFAULT 'general',
        domain VARCHAR(40) NOT NULL DEFAULT 'math',
        grade_level VARCHAR(40) NOT NULL DEFAULT '',
        status VARCHAR(30) NOT NULL DEFAULT 'submitted',
        request_json JSON NULL,
        assessment_id BIGINT UNSIGNED NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY ref_code (ref_code),
        KEY learner_status (learner_id, status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_learning_plans (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        learner_id BIGINT UNSIGNED NOT NULL,
        track VARCHAR(30) NOT NULL DEFAULT 'general',
        plan_json JSON NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY learner_id (learner_id, is_active)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_acc_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}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_acc_splits (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        session_id BIGINT UNSIGNED NOT NULL,
        entity_type VARCHAR(30) NOT NULL DEFAULT '',
        entity_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
        amount DECIMAL(15,2) NOT NULL DEFAULT 0,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY session_id (session_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}edu_acc_journal (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        session_id BIGINT UNSIGNED NOT 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 'pending',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY session_id (session_id),
        KEY acc_event_id (acc_event_id)
    ) {$charset}",
];

foreach ( $ddl as $sql ) {
    $wpdb->query( $sql );
}

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

$orgs = [
    [ 'school', 'دبیرستان نمونه دولتی تهران', 'تهران', 'منطقه ۳' ],
    [ 'school', 'مدرسه غیرانتفاعی رشد', 'اصفهان', 'خیابان چهارباغ' ],
    [ 'institute', 'مؤسسه کنکور آلفا', 'تهران', 'ونک' ],
    [ 'institute', 'آموزشگاه زبان پلی‌گلوت', 'شیراز', 'معالی‌آباد' ],
    [ 'institute', 'آموزشگاه موسیقی هنر', 'تهران', 'جردن' ],
];
$org_ids = [];
foreach ( $orgs as [ $type, $name, $city, $addr ] ) {
    $ex = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}edu_organizations WHERE name = %s LIMIT 1", $name
    ) );
    if ( $ex ) {
        $org_ids[] = $ex;
        continue;
    }
    $wpdb->insert( "{$pre}edu_organizations", [
        'org_type'     => $type,
        'name'         => $name,
        'city'         => $city,
        'address_text' => $addr,
        'profile_json' => wp_json_encode( [ 'facilities' => [ 'کلاس', 'آزمایشگاه', 'سالن' ] ], JSON_UNESCAPED_UNICODE ),
    ] );
    $org_ids[] = (int) $wpdb->insert_id;
}

foreach ( $org_ids as $oid ) {
    $cnt = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$pre}edu_org_resources WHERE org_id = %d", $oid
    ) );
    if ( $cnt > 0 ) {
        continue;
    }
    $wpdb->insert( "{$pre}edu_org_resources", [
        'org_id' => $oid, 'resource_type' => 'classroom', 'name' => 'کلاس A', 'capacity' => 25, 'price_per_hour' => 250000,
    ] );
    $rid = (int) $wpdb->insert_id;
    $wpdb->insert( "{$pre}edu_org_schedule", [
        'org_id' => $oid, 'resource_id' => $rid,
        'slot_date' => date( 'Y-m-d', strtotime( '+2 days' ) ),
        'start_time' => '09:00:00', 'end_time' => '11:00:00', 'status' => 'available',
    ] );
}

$roles = [
    [ 'edu_learner', 'دانش‌آموز EduBrain', 'education' ],
    [ 'edu_mentor', 'مربی EduBrain', 'education' ],
    [ 'edu_teacher', 'معلم EduBrain', 'education' ],
    [ 'edu_org_admin', 'مدیر مؤسسه/مدرسه', 'education' ],
    [ 'edu_accountant', 'حسابدار آموزش', 'education' ],
    [ 'edu_parent', 'والد EduBrain', 'education' ],
];
foreach ( $roles as [ $slug, $label, $mod ] ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $slug ) ) ) {
        $wpdb->insert( "{$pre}acl_roles", [
            'slug' => $slug, 'label' => $label, 'module' => $mod, 'is_system' => 1,
        ] );
    }
}

$perm_keys = [
    'education.view'           => 'مشاهده پورتال آموزش',
    'education.manage'         => 'مدیریت جلسات آموزش',
    'education.mentor'         => 'نقش مربی/معلم',
    'education.org'            => 'مدیریت مؤسسه/مدرسه',
    'education.accounting'     => 'حسابداری آموزش',
    'education.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'         => 'education',
            'resource'       => explode( '.', $pk )[1] ?? 'general',
            'action'         => str_contains( $pk, '.post' ) ? 'post' : 'view',
            'is_system'      => 1,
        ] );
    }
}

$role_perms = [
    'edu_learner'    => [ 'education.view' ],
    'edu_mentor'     => [ 'education.view', 'education.manage', 'education.mentor' ],
    'edu_teacher'    => [ 'education.view', 'education.manage', 'education.mentor' ],
    'edu_org_admin'  => [ 'education.view', 'education.org', 'education.manage' ],
    'edu_accountant' => [ 'education.view', 'education.accounting', 'education.accounting.post' ],
    'edu_parent'     => [ 'education.view' ],
    'accountant'     => [ 'education.accounting', 'education.accounting.post' ],
];
foreach ( $role_perms as $slug => $perms ) {
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s LIMIT 1", $slug ) );
    if ( ! $rid ) {
        continue;
    }
    foreach ( $perms as $pk ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)",
            $rid, $pk
        ) );
    }
}

function edu_install_user( string $login, string $email, string $pass, string $display, string $role_slug ): int {
    global $wpdb;
    $uid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->users} WHERE user_login=%s", $login ) );
    if ( ! $uid && function_exists( 'wp_create_user' ) ) {
        $uid = (int) wp_create_user( $login, $pass, $email );
        if ( $uid && ! is_wp_error( $uid ) ) {
            $wpdb->update( $wpdb->users, [ 'display_name' => $display ], [ 'ID' => $uid ] );
        } else {
            $uid = 0;
        }
    }
    if ( $uid ) {
        $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}acl_roles WHERE slug=%s", $role_slug ) );
        if ( $rid ) {
            $wpdb->query( $wpdb->prepare(
                "INSERT IGNORE INTO {$wpdb->prefix}acl_user_roles (user_id, role_id) VALUES (%d, %d)",
                $uid, $rid
            ) );
        }
    }
    return $uid;
}

$users = [
    [ 'edu_student_01', 'student@edubrain.local', 'Education1234', 'علی دانش‌آموز', 'edu_learner' ],
    [ 'edu_mentor_01', 'mentor@edubrain.local', 'Education1234', 'دکتر رضایی — مربی', 'edu_mentor' ],
    [ 'edu_teacher_01', 'teacher@edubrain.local', 'Education1234', 'خانم احمدی — معلم', 'edu_teacher' ],
    [ 'edu_org_admin', 'org@edubrain.local', 'Education1234', 'مدیر مؤسسه آلفا', 'edu_org_admin' ],
    [ 'edu_accountant', 'accountant@edubrain.local', 'Education1234', 'حسابدار آموزش', 'edu_accountant' ],
];
$seed_users = [];
foreach ( $users as $u ) {
    $uid = edu_install_user( ...$u );
    if ( $uid ) {
        $seed_users[ $u[0] ] = $uid;
    }
}

require_once ACC_PATH . 'includes/helpers/education-platform.php';
if ( ! empty( $seed_users['edu_student_01'] ) ) {
    Education_Platform::update_learner( (int) $seed_users['edu_student_01'], [
        'grade_level' => 'یازدهم',
        'track'       => 'konkur',
        'profile'     => [ 'goals' => [ 'کنکور ریاضی' ], 'school' => 'نمونه دولتی' ],
    ] );
}
if ( ! empty( $seed_users['edu_mentor_01'] ) ) {
    Education_Platform::update_educator( (int) $seed_users['edu_mentor_01'], [
        'educator_type' => 'mentor',
        'hourly_rate'   => 950000,
        'profile'       => [
            'academic_cv' => [ [ 'degree' => 'دکتری فیزیک', 'years' => 12 ] ],
            'skill_cv'    => [ 'konkur', 'physics', 'math' ],
        ],
    ] );
    global $wpdb;
    $wpdb->update( Education_Platform::tbl( 'educators' ), [ 'verified_status' => 'verified' ], [
        'user_id' => (int) $seed_users['edu_mentor_01'],
    ] );
}

update_option( 'acc_education_version', '1.0' );

echo json_encode( [
    'success'    => true,
    'version'    => '1.0',
    'orgs'       => count( $org_ids ),
    'seed_users' => $seed_users,
    'demo'       => [
        'student'    => 'edu_student_konkur / Edu@1404',
        'mentor'     => 'edu_mentor_physics / Edu@1404',
        'accountant' => 'edu_accountant / Edu@1404',
        'seed'       => 'php run-education-seed.php',
        'portal'     => '/acc-engine/education.php',
    ],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
