<?php
/**
 * Education_Seed — داده تست جامع EduBrain
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Education_Seed {

    public const DEMO_PASS = 'Edu@1404';

    public static function demo_users(): array {
        return [
            [ 'edu_student_konkur', 'دانش‌آموز کنکور — سارا', 'edu_learner', 'konkur', 'دوازدهم' ],
            [ 'edu_student_tiz', 'دانش‌آموز تیزهوش — امیر', 'edu_learner', 'tizhooshan', 'هشتم' ],
            [ 'edu_student_skill', 'دانش‌آموز مهارت — نازنین', 'edu_learner', 'skill', 'دهم' ],
            [ 'edu_mentor_physics', 'دکتر کریمی — مربی فیزیک', 'edu_mentor', null, null ],
            [ 'edu_mentor_music', 'استاد موسوی — مربی موسیقی', 'edu_mentor', null, null ],
            [ 'edu_teacher_math', 'خانم نوری — معلم ریاضی', 'edu_teacher', null, null ],
            [ 'edu_org_alpha', 'مدیر مؤسسه آلفا', 'edu_org_admin', null, null ],
            [ 'edu_accountant', 'حسابدار EduBrain', 'edu_accountant', null, null ],
            [ 'edu_parent_konkur', 'والد — خانم رضایی', 'edu_parent', null, null ],
            [ 'edu_student_01', 'علی دانش‌آموز', 'edu_learner', 'konkur', 'یازدهم' ],
            [ 'edu_mentor_01', 'دکتر رضایی — مربی', 'edu_mentor', null, null ],
        ];
    }

    public static function ensure_schema(): void {
        global $wpdb;
        $pre = $wpdb->prefix;
        $alters = [
            "ALTER TABLE {$pre}edu_organizations ADD COLUMN lat DECIMAL(10,7) NULL",
            "ALTER TABLE {$pre}edu_organizations ADD COLUMN lng DECIMAL(10,7) NULL",
            "ALTER TABLE {$pre}edu_sessions ADD COLUMN learner_lat DECIMAL(10,7) NULL",
            "ALTER TABLE {$pre}edu_sessions ADD COLUMN learner_lng DECIMAL(10,7) NULL",
        ];
        foreach ( $alters as $sql ) {
            preg_match( '/ADD COLUMN (\w+)/', $sql, $m );
            $col = $m[1] ?? '';
            preg_match( '/ALTER TABLE (\S+)/', $sql, $tm );
            $table = str_replace( '`', '', $tm[1] ?? '' );
            if ( ! $col || ! $table ) {
                continue;
            }
            $ex = $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 ( ! $ex ) {
                $wpdb->query( $sql );
            }
        }
    }

    public static function ensure_user( string $login, string $name, string $role_slug, string $email = '' ): int {
        global $wpdb;
        $id = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT ID FROM {$wpdb->users} WHERE user_login = %s", $login
        ) );
        if ( ! $id ) {
            if ( function_exists( 'wp_create_user' ) ) {
                $id = (int) wp_create_user( $login, self::DEMO_PASS, $email ?: $login . '@edubrain.test' );
                if ( is_wp_error( $id ) ) {
                    $id = 0;
                }
            }
            if ( ! $id ) {
                $max = (int) $wpdb->get_var( "SELECT COALESCE(MAX(ID), 0) FROM {$wpdb->users}" );
                $id  = $max + 1;
                $wpdb->insert( $wpdb->users, [
                    'ID'              => $id,
                    'user_login'      => $login,
                    'user_pass'       => wp_hash_password( self::DEMO_PASS ),
                    'user_nicename'   => sanitize_title( $login ),
                    'user_email'      => $email ?: $login . '@edubrain.test',
                    'user_registered' => current_time( 'mysql' ),
                    'display_name'    => $name,
                    'user_status'     => 0,
                ] );
            }
            if ( $id ) {
                $wpdb->update( $wpdb->users, [ 'display_name' => $name ], [ 'ID' => $id ] );
            }
        } else {
            $wpdb->update( $wpdb->users, [
                'user_pass'    => wp_hash_password( self::DEMO_PASS ),
                'display_name' => $name,
            ], [ 'ID' => $id ] );
        }
        if ( $id && $role_slug ) {
            $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)",
                    $id, $rid
                ) );
            }
        }
        return $id;
    }

    public static function reset_data(): void {
        global $wpdb;
        $pre = $wpdb->prefix;
        foreach ( [
            'edu_acc_journal', 'edu_acc_splits', 'edu_learning_plans', 'edu_assessments',
            'edu_sessions', 'edu_org_schedule', 'edu_org_resources',
            'edu_learner_skill_log', 'edu_learner_academic_log', 'edu_learners', 'edu_educators',
        ] as $t ) {
            $wpdb->query( "DELETE FROM {$pre}{$t}" );
        }
    }

    /** @return array<string,mixed> */
    public static function run( bool $reset = false ): array {
        global $wpdb;
        require_once ACC_PATH . 'includes/helpers/education-platform.php';
        require_once ACC_PATH . 'includes/helpers/education-cost-accounting.php';
        require_once ACC_PATH . 'includes/helpers/education-gis.php';

        self::ensure_schema();
        if ( $reset ) {
            self::reset_data();
        }

        $log = [ 'users' => [], 'orgs' => [], 'sessions' => [], 'plans' => [], 'accounting' => [] ];

        $uids = [];
        foreach ( self::demo_users() as [ $login, $name, $role, $track, $grade ] ) {
            $uid = self::ensure_user( $login, $name, $role );
            $uids[ $login ] = $uid;
            $log['users'][ $login ] = [ 'id' => $uid, 'role' => $role, 'password' => self::DEMO_PASS ];
            if ( $role === 'edu_learner' && $uid ) {
                require_once ACC_PATH . 'includes/helpers/education-lifepath.php';
                $profile = Edu_LifePath::default_profile();
                $profile['identity']['full_name'] = $name;
                $profile['identity']['entry_grade'] = '7';
                $profile['family'] = [
                    'monthly_budget_rial' => $track === 'konkur' ? 6000000 : 4000000,
                    'budget_tier'         => $track === 'konkur' ? 'moderate' : 'economy',
                    'parent_name'         => 'والد نمونه',
                ];
                if ( $login === 'edu_student_konkur' ) {
                    $profile['career'] = [
                        'dream_jobs'     => [ 'medicine', 'science' ],
                        'skills_wanted'  => [ 'english', 'biology' ],
                        'university_targets' => [ 'شهید بهشتی', 'تهران' ],
                    ];
                    $profile['academic_history'] = [];
                    foreach ( [ '7' => 17.2, '8' => 17.8, '9' => 18.1, '10' => 18.5, '11' => 18.9, '12' => 19.1 ] as $g => $avg ) {
                        $profile['academic_history'][] = [
                            'grade' => $g, 'school_name' => 'دبیرستان نمونه', 'teacher_name' => 'خانم احمدی',
                            'year' => '139' . ( 8 + (int) $g ), 'report_avg' => $avg,
                        ];
                    }
                }
                if ( $login === 'edu_student_skill' ) {
                    $profile['career'] = [
                        'dream_jobs'    => [ 'music', 'arts' ],
                        'skills_wanted' => [ 'music', 'english' ],
                    ];
                }
                Education_Platform::update_learner( $uid, [
                    'grade_level' => $grade ?? '',
                    'track'       => $track ?? 'general',
                    'profile'     => array_merge( $profile, [
                        'home_lat' => 35.7000 + ( count( $uids ) * 0.008 ),
                        'home_lng' => 51.3800 + ( count( $uids ) * 0.006 ),
                        'goals'    => $track === 'konkur' ? [ 'کنکور تجربی' ] : ( $track === 'tizhooshan' ? [ 'سمپاد' ] : [ 'موسیقی' ] ),
                    ] ),
                ] );
            }
            if ( in_array( $role, [ 'edu_mentor', 'edu_teacher' ], true ) && $uid ) {
                Education_Platform::update_educator( $uid, [
                    'profile' => [
                        'academic_cv'  => [ [ 'degree' => 'دکتری فیزیک', 'institution' => 'دانشگاه تهران', 'years' => 8 ] ],
                        'work_history' => [ [ 'org' => 'مؤسسه آلفا', 'role' => 'مربی', 'years' => 5, 'subject' => 'physics' ] ],
                        'skill_cv'     => [ 'physics', 'math', 'konkur' ],
                        'bio'          => 'بیش از ۱۰ سال تدریس کنکور و المپیاد',
                    ],
                    'verified_status' => 'verified',
                    'hourly_rate'   => 900000,
                ] );
            }
        }

        $orgs_geo = [
            [ 'school', 'دبیرستان نمونه دولتی تهران', 'تهران', 'منطقه ۳ — خیابان ولیعصر', 35.7219000, 51.3347000 ],
            [ 'school', 'مدرسه غیرانتفاعی رشد', 'اصفهان', 'خیابان چهارباغ', 32.6539000, 51.6660000 ],
            [ 'institute', 'مؤسسه کنکور آلفا', 'تهران', 'ونک — ملاصدرا', 35.7575000, 51.4100000 ],
            [ 'institute', 'آموزشگاه زبان پلی‌گلوت', 'شیراز', 'معالی‌آباد', 29.5918000, 52.5837000 ],
            [ 'institute', 'آموزشگاه موسیقی هنر', 'تهران', 'جردن — ناهید', 35.7700000, 51.4200000 ],
        ];
        $org_map = [];
        $t = Education_Platform::tbl( 'organizations' );
        foreach ( $orgs_geo as [ $type, $name, $city, $addr, $lat, $lng ] ) {
            $id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$t} WHERE name = %s", $name ) );
            $row = [
                'org_type'     => $type,
                'name'         => $name,
                'city'         => $city,
                'address_text' => $addr,
                'lat'          => $lat,
                'lng'          => $lng,
                'profile_json' => wp_json_encode( [
                    'facilities' => [ 'کلاس', 'آزمایشگاه', 'سالن' ],
                    'osm'        => 'OpenStreetMap',
                ], JSON_UNESCAPED_UNICODE ),
                'is_active'    => 1,
            ];
            if ( $id ) {
                $wpdb->update( $t, $row, [ 'id' => $id ] );
            } else {
                $row['created_at'] = current_time( 'mysql' );
                $wpdb->insert( $t, $row );
                $id = (int) $wpdb->insert_id;
            }
            $org_map[ $name ] = $id;
            $log['orgs'][ $name ] = [ 'id' => $id, 'lat' => $lat, 'lng' => $lng ];

            $rc = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM " . Education_Platform::tbl( 'org_resources' ) . " WHERE org_id = %d", $id
            ) );
            if ( ! $rc ) {
                $wpdb->insert( Education_Platform::tbl( 'org_resources' ), [
                    'org_id' => $id, 'resource_type' => 'classroom', 'name' => 'کلاس A',
                    'capacity' => 25, 'price_per_hour' => 280000,
                ] );
                $rid = (int) $wpdb->insert_id;
                for ( $d = 1; $d <= 5; $d++ ) {
                    $wpdb->insert( Education_Platform::tbl( 'org_schedule' ), [
                        'org_id' => $id, 'resource_id' => $rid,
                        'slot_date' => date( 'Y-m-d', strtotime( "+{$d} days" ) ),
                        'start_time' => '09:00:00', 'end_time' => '11:00:00', 'status' => 'available',
                    ] );
                }
            }
        }

        $alpha_org = $org_map['مؤسسه کنکور آلفا'] ?? 0;
        if ( ! empty( $uids['edu_org_alpha'] ) && $alpha_org ) {
            Education_Platform::update_learner( (int) $uids['edu_org_alpha'], [] );
        }

        foreach ( [
            'edu_mentor_physics' => [ 'mentor', 980000, [ 'physics', 'math', 'konkur' ] ],
            'edu_mentor_music'     => [ 'mentor', 750000, [ 'music', 'skill' ] ],
            'edu_teacher_math'     => [ 'teacher', 850000, [ 'math', 'konkur' ] ],
            'edu_mentor_01'        => [ 'mentor', 950000, [ 'physics', 'konkur' ] ],
        ] as $login => [ $etype, $rate, $skills ] ) {
            if ( empty( $uids[ $login ] ) ) {
                continue;
            }
            Education_Platform::update_educator( (int) $uids[ $login ], [
                'educator_type'  => $etype,
                'hourly_rate'    => $rate,
                'delivery_modes' => [ 'virtual', 'in_person' ],
                'venue_types'    => [ 'school', 'institute', 'home', 'online' ],
                'profile'        => [
                    'academic_cv' => [ [ 'degree' => 'فوق‌لیسانس/دکتری', 'years' => 10 ] ],
                    'skill_cv'    => $skills,
                ],
            ] );
            $wpdb->update( Education_Platform::tbl( 'educators' ), [ 'verified_status' => 'verified' ], [
                'user_id' => (int) $uids[ $login ],
            ] );
        }

        $placement_answers = [
            'edu_student_konkur' => [ 'math' => 45, 'physics' => 52, 'chemistry' => 61, 'biology' => 70, 'english' => 55 ],
            'edu_student_tiz'    => [ 'math' => 78, 'physics' => 82, 'chemistry' => 75, 'biology' => 80, 'english' => 72 ],
            'edu_student_skill'  => [ 'music' => 40, 'english' => 65, 'math' => 58 ],
        ];
        foreach ( $placement_answers as $login => $ans ) {
            if ( empty( $uids[ $login ] ) ) {
                continue;
            }
            $r = Education_Platform::run_placement( (int) $uids[ $login ], $ans );
            $log['plans'][ $login ] = [ 'weaknesses' => count( $r['weaknesses'] ?? [] ), 'weeks' => count( $r['plan']['weeks'] ?? [] ) ];
            Education_Platform::add_learner_log( (int) $uids[ $login ], 'academic', 'math', [
                'title' => 'کارنامه Mock', 'score' => 62, 'entry_date' => date( 'Y-m-d', strtotime( '-14 days' ) ),
            ] );
        }

        $student_konkur = (int) ( $uids['edu_student_konkur'] ?? 0 );
        $student_skill  = (int) ( $uids['edu_student_skill'] ?? 0 );
        $mentor_phys    = (int) ( $uids['edu_mentor_physics'] ?? 0 );
        $mentor_music   = (int) ( $uids['edu_mentor_music'] ?? 0 );

        if ( $student_konkur ) {
            $learner = Education_Platform::get_or_create_learner( $student_konkur );
            $home_lat = (float) ( $learner['profile']['home_lat'] ?? 35.7000 );
            $home_lng = (float) ( $learner['profile']['home_lng'] ?? 51.3800 );

            $s1 = Education_Platform::create_session_request( $student_konkur, [
                'session_type' => 'academic', 'domain' => 'physics', 'track' => 'konkur',
                'delivery_mode' => 'in_person', 'venue_type' => 'home',
                'distance_km' => Edu_GIS::haversine_km( $home_lat, $home_lng, 35.7219, 51.3347 ),
                'duration_min' => 90, 'org_id' => $org_map['دبیرستان نمونه دولتی تهران'] ?? 0,
            ] );
            $log['sessions']['submitted'] = $s1['session_id'] ?? 0;

            $s2 = Education_Platform::create_session_request( $student_konkur, [
                'session_type' => 'academic', 'domain' => 'math', 'track' => 'konkur',
                'delivery_mode' => 'virtual', 'venue_type' => 'online', 'duration_min' => 60,
            ] );
            if ( ! empty( $s2['session_id'] ) && $mentor_phys ) {
                Education_Platform::assign_session( (int) $s2['session_id'], $mentor_phys );
                $log['sessions']['assigned'] = $s2['session_id'];
            }

            $s3 = Education_Platform::create_session_request( $student_konkur, [
                'session_type' => 'academic', 'domain' => 'chemistry', 'track' => 'konkur',
                'delivery_mode' => 'in_person', 'venue_type' => 'institute',
                'org_id' => $alpha_org, 'resource_id' => (int) $wpdb->get_var( $wpdb->prepare(
                    "SELECT id FROM " . Education_Platform::tbl( 'org_resources' ) . " WHERE org_id = %d LIMIT 1", $alpha_org
                ) ),
                'duration_min' => 120,
            ] );
            if ( ! empty( $s3['session_id'] ) && $mentor_phys ) {
                Education_Platform::assign_session( (int) $s3['session_id'], $mentor_phys );
                $acc = Education_Platform::complete_session( (int) $s3['session_id'], $mentor_phys, [
                    'summary' => 'جلسه کنکور شیمی — CDM remedial',
                    'topics'  => [ 'استوichiometry', 'اسید و باز' ],
                ] );
                $log['sessions']['completed'] = $s3['session_id'];
                $log['accounting']['pending_event'] = $acc['accounting']['event_id'] ?? null;
            }
        }

        if ( $student_skill && $mentor_music ) {
            $s4 = Education_Platform::create_session_request( $student_skill, [
                'session_type' => 'skill', 'domain' => 'music', 'track' => 'skill',
                'delivery_mode' => 'in_person', 'venue_type' => 'institute',
                'org_id' => $org_map['آموزشگاه موسیقی هنر'] ?? 0,
                'duration_min' => 90,
            ] );
            if ( ! empty( $s4['session_id'] ) ) {
                Education_Platform::assign_session( (int) $s4['session_id'], $mentor_music );
                Education_Platform::complete_session( (int) $s4['session_id'], $mentor_music, [
                    'summary' => 'جلسه پیانو — مبتدی',
                ] );
                $log['sessions']['skill_completed'] = $s4['session_id'];
            }
            Education_Platform::add_learner_log( $student_skill, 'skill', 'music', [
                'title' => 'اجرای قطعه ساده', 'entry_date' => date( 'Y-m-d', strtotime( '-3 days' ) ),
            ] );
        }

        update_option( 'acc_education_seed_version', '1.2' );
        update_option( 'acc_education_demo_password', self::DEMO_PASS );

        require_once ACC_PATH . 'includes/helpers/education-companion-extras.php';
        $parent_uid = (int) ( $uids['edu_parent_konkur'] ?? 0 );
        $student_konkur_uid = (int) ( $uids['edu_student_konkur'] ?? 0 );
        if ( $parent_uid && $student_konkur_uid ) {
            Edu_Companion_Extras::set_parent_link( $parent_uid, $student_konkur_uid, 'سارا — دانش‌آموز کنکور' );
            $log['parent_link'] = [ 'parent' => $parent_uid, 'learner' => $student_konkur_uid ];
        }

        return [
            'success'  => true,
            'version'  => '1.2',
            'password' => self::DEMO_PASS,
            'log'      => $log,
            'gis'      => Education_GIS::map_payload(),
            'demo'     => array_map( fn( $u ) => $u['id'] ?? 0, $log['users'] ),
        ];
    }
}
