<?php
/**
 * Edu_Companion_Extras — فاز ۲: والدین · کارنامه · Matching · Graph-RAG · نمودار
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Edu_Companion_Extras {

    public static function uploads_dir(): string {
        $dir = ACC_PATH . 'uploads/edu-reports';
        if ( ! is_dir( $dir ) ) {
            wp_mkdir_p( $dir );
        }
        return $dir;
    }

    public static function uploads_url(): string {
        return ACC_URL . 'uploads/edu-reports/';
    }

    /** داده نمودار روند معدل پایه‌به‌پایه */
    public static function grade_trend_chart( array $profile ): array {
        require_once ACC_PATH . 'includes/helpers/education-lifepath.php';
        $history = $profile['academic_history'] ?? [];
        $labels  = [];
        $values  = [];
        $order   = array_keys( Edu_LifePath::GRADES );
        usort( $history, fn( $a, $b ) => array_search( $a['grade'] ?? '', $order, true ) <=> array_search( $b['grade'] ?? '', $order, true ) );
        foreach ( $history as $row ) {
            $g = $row['grade'] ?? '';
            if ( ! isset( Edu_LifePath::GRADES[ $g ] ) ) {
                continue;
            }
            $labels[] = Edu_LifePath::GRADES[ $g ];
            $values[] = isset( $row['report_avg'] ) ? (float) $row['report_avg'] : null;
        }
        return [
            'labels'   => $labels,
            'values'   => $values,
            'max'      => 20,
            'trend'    => Edu_LifePath::analyze_academic_trend( $history )['trend'] ?? 'unknown',
        ];
    }

    /** Import کارنامه — فایل + متادیتا (OCR-ready stub) */
    public static function import_report_card( int $user_id, array $file, array $meta = [], bool $trusted_tmp = false ): array {
        require_once ACC_PATH . 'includes/helpers/education-platform.php';
        require_once ACC_PATH . 'includes/helpers/education-lifepath.php';

        if ( empty( $file['tmp_name'] ) || ( ! $trusted_tmp && ! is_uploaded_file( $file['tmp_name'] ) ) ) {
            return [ 'success' => false, 'message' => 'فایل نامعتبر' ];
        }
        $allowed = [ 'image/jpeg', 'image/png', 'image/webp', 'application/pdf' ];
        $mime    = mime_content_type( $file['tmp_name'] ) ?: ( $file['type'] ?? '' );
        if ( ! in_array( $mime, $allowed, true ) ) {
            return [ 'success' => false, 'message' => 'فرمت مجاز: JPG, PNG, PDF' ];
        }
        $ext      = pathinfo( $file['name'] ?? 'report', PATHINFO_EXTENSION ) ?: 'jpg';
        $safe     = 'rc_' . $user_id . '_' . time() . '.' . preg_replace( '/[^a-z0-9]/i', '', $ext );
        $dest     = self::uploads_dir() . '/' . $safe;
        if ( $trusted_tmp ) {
            if ( ! copy( $file['tmp_name'], $dest ) ) {
                return [ 'success' => false, 'message' => 'خطا در ذخیره فایل' ];
            }
        } elseif ( ! move_uploaded_file( $file['tmp_name'], $dest ) ) {
            return [ 'success' => false, 'message' => 'خطا در ذخیره فایل' ];
        }

        $grade = sanitize_key( $meta['grade'] ?? '' );
        $year  = sanitize_text_field( $meta['year'] ?? '' );
        $avg   = isset( $meta['report_avg'] ) ? (float) $meta['report_avg'] : self::stub_parse_avg( $file['name'] ?? '', $meta );

        $learner = Education_Platform::get_or_create_learner( $user_id );
        $profile = array_replace_recursive( Edu_LifePath::default_profile(), $learner['profile'] ?? [] );
        $entry   = [
            'id'          => 'rc_' . time(),
            'grade'       => $grade,
            'year'        => $year,
            'filename'    => $safe,
            'url'         => self::uploads_url() . $safe,
            'mime'        => $mime,
            'uploaded_at' => current_time( 'mysql' ),
            'parsed_avg'  => $avg,
            'status'      => $avg ? 'parsed' : 'pending_review',
            'notes'       => sanitize_textarea_field( $meta['notes'] ?? '' ),
        ];
        $profile['report_cards'] = array_merge( $profile['report_cards'] ?? [], [ $entry ] );

        if ( $grade && $avg ) {
            $found = false;
            foreach ( $profile['academic_history'] as &$h ) {
                if ( ( $h['grade'] ?? '' ) === $grade ) {
                    $h['report_avg'] = $avg;
                    $h['year']       = $year ?: ( $h['year'] ?? '' );
                    $h['source']     = 'report_import';
                    $found = true;
                    break;
                }
            }
            unset( $h );
            if ( ! $found ) {
                $profile['academic_history'][] = [
                    'grade'       => $grade,
                    'year'        => $year,
                    'school_name' => sanitize_text_field( $meta['school_name'] ?? '' ),
                    'teacher_name'=> sanitize_text_field( $meta['teacher_name'] ?? '' ),
                    'report_avg'  => $avg,
                    'source'      => 'report_import',
                ];
            }
        }

        Education_Platform::update_learner( $user_id, [ 'profile' => $profile ] );
        if ( $grade ) {
            Education_Platform::add_learner_log( $user_id, 'academic', $grade, [
                'title'      => 'کارنامه import — پایه ' . ( Edu_LifePath::GRADES[ $grade ] ?? $grade ),
                'report_avg' => $avg,
                'file'       => $safe,
            ] );
        }

        return [ 'success' => true, 'report' => $entry, 'merged_grade' => $grade ];
    }

    /** Stub OCR — استخراج عدد از نام فایل یا meta */
    private static function stub_parse_avg( string $filename, array $meta ): ?float {
        if ( preg_match( '/(\d{1,2}[\.]\d)/', $filename, $m ) ) {
            $v = (float) $m[1];
            return $v <= 20 ? $v : null;
        }
        return null;
    }

    /** تأیید بودجه توسط والد */
    public static function approve_budget( int $parent_user_id, int $learner_user_id, array $data = [] ): array {
        require_once ACC_PATH . 'includes/helpers/education-platform.php';
        $link = self::parent_link( $parent_user_id );
        global $wpdb;
        $is_parent = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}acl_user_roles ur
             INNER JOIN {$wpdb->prefix}acl_roles r ON r.id = ur.role_id
             WHERE ur.user_id = %d AND r.slug = 'edu_parent'", $parent_user_id
        ) );
        if ( $is_parent && $link ) {
            $learner_user_id = (int) $link['learner_user_id'];
        }
        if ( $is_parent && $link && (int) $link['learner_user_id'] !== $learner_user_id ) {
            return [ 'success' => false, 'message' => 'دسترسی والدین ندارید' ];
        }
        $learner = Education_Platform::get_or_create_learner( $learner_user_id );
        $profile = $learner['profile'] ?? [];
        $family  = $profile['family'] ?? [];
        if ( isset( $data['monthly_budget_rial'] ) ) {
            $family['monthly_budget_rial'] = max( 0, (int) $data['monthly_budget_rial'] );
        }
        if ( isset( $data['budget_tier'] ) ) {
            $family['budget_tier'] = sanitize_key( $data['budget_tier'] );
        }
        $family['budget_approved']    = true;
        $family['budget_approved_at'] = current_time( 'mysql' );
        $family['parent_notes']       = sanitize_textarea_field( $data['parent_notes'] ?? '' );
        $family['approved_by']        = $parent_user_id;
        $profile['family']            = $family;
        Education_Platform::update_learner( $learner_user_id, [ 'profile' => $profile ] );
        return [ 'success' => true, 'family' => $family ];
    }

    public static function parent_link( int $parent_user_id ): ?array {
        $raw = get_user_meta( $parent_user_id, 'edu_parent_link', true );
        if ( is_string( $raw ) ) {
            $raw = json_decode( $raw, true );
        }
        return is_array( $raw ) ? $raw : null;
    }

    public static function set_parent_link( int $parent_user_id, int $learner_user_id, string $student_name = '' ): void {
        update_user_meta( $parent_user_id, 'edu_parent_link', wp_json_encode( [
            'learner_user_id' => $learner_user_id,
            'student_name'    => $student_name,
            'linked_at'       => current_time( 'mysql' ),
        ], JSON_UNESCAPED_UNICODE ) );
    }

    public static function is_parent_of( int $parent_user_id, int $learner_user_id ): bool {
        $link = self::parent_link( $parent_user_id );
        return $link && (int) ( $link['learner_user_id'] ?? 0 ) === $learner_user_id;
    }

    /** داشبورد والد */
    public static function parent_dashboard( int $parent_user_id ): array {
        require_once ACC_PATH . 'includes/helpers/education-lifepath.php';
        $link = self::parent_link( $parent_user_id );
        if ( ! $link || empty( $link['learner_user_id'] ) ) {
            return [ 'success' => false, 'message' => 'فرزند متصل نیست' ];
        }
        $lid = (int) $link['learner_user_id'];
        $state = Edu_LifePath::companion_state( $lid );
        $chart = self::grade_trend_chart( $state['profile'] ?? [] );
        $match = self::match_recommendations( $lid );
        return [
            'success'       => true,
            'student_name'  => $link['student_name'] ?? '',
            'learner_user_id' => $lid,
            'companion'     => $state,
            'chart'         => $chart,
            'matching'      => $match,
        ];
    }

    /** Matching مدرسه/مربی بر اساس بودجه + امکانات + حوزه */
    public static function match_recommendations( int $user_id, ?string $domain = null ): array {
        require_once ACC_PATH . 'includes/helpers/education-platform.php';
        require_once ACC_PATH . 'includes/helpers/education-lifepath.php';

        $learner = Education_Platform::get_or_create_learner( $user_id );
        $profile = array_replace_recursive( Edu_LifePath::default_profile(), $learner['profile'] ?? [] );
        $path    = Edu_LifePath::generate_path( $learner, Education_Platform::active_plan( $user_id ) );
        $budget  = (int) ( $profile['family']['monthly_budget_rial'] ?? 0 );
        $tier    = $profile['family']['budget_tier'] ?? 'moderate';
        $skills  = $profile['career']['skills_wanted'] ?? [];
        $domain  = $domain ?: ( $skills[0] ?? 'math' );

        $orgs = Education_Platform::list_orgs();
        $org_scores = [];
        foreach ( $orgs as $o ) {
            $score = 50;
            $fac   = $o['profile']['facilities'] ?? [];
            if ( in_array( $domain, [ 'music' ], true ) && in_array( 'music_room', $fac, true ) ) {
                $score += 20;
            }
            if ( in_array( $domain, [ 'sport' ], true ) && in_array( 'sports_hall', $fac, true ) ) {
                $score += 20;
            }
            if ( in_array( 'lab_science', $fac, true ) && in_array( $domain, [ 'physics', 'chemistry', 'biology' ], true ) ) {
                $score += 15;
            }
            $resources = Education_Platform::org_resources( (int) $o['id'] );
            $min_price = PHP_INT_MAX;
            foreach ( $resources as $r ) {
                $min_price = min( $min_price, (float) ( $r['price_per_hour'] ?? 0 ) );
            }
            if ( $min_price < PHP_INT_MAX ) {
                $monthly_est = $min_price * ( $path['budget']['suggested_sessions_per_month'] ?? 4 );
                if ( $budget > 0 && $monthly_est <= $budget ) {
                    $score += 25;
                } elseif ( $tier === 'premium' ) {
                    $score += 10;
                }
            }
            $org_scores[] = [
                'org'    => $o,
                'score'  => min( 100, $score ),
                'reason' => self::org_match_reason( $o, $domain, $budget, $tier ),
            ];
        }
        usort( $org_scores, fn( $a, $b ) => $b['score'] <=> $a['score'] );

        $educators = Education_Platform::list_educators( [ 'verified' => true ] );
        $edu_scores = [];
        foreach ( $educators as $e ) {
            $score = 40;
            $cv    = $e['profile']['skill_cv'] ?? [];
            if ( in_array( $domain, $cv, true ) ) {
                $score += 35;
            }
            $rate = (float) ( $e['hourly_rate'] ?? 0 );
            $session_cost = $rate * 1.5;
            $monthly = $session_cost * ( $path['budget']['suggested_sessions_per_month'] ?? 4 );
            if ( $budget > 0 && $monthly <= $budget ) {
                $score += 25;
            } elseif ( $rate <= 700000 && $tier === 'economy' ) {
                $score += 15;
            }
            if ( ( $e['verified_status'] ?? '' ) === 'verified' ) {
                $score += 10;
            }
            $edu_scores[] = [
                'educator' => $e,
                'score'    => min( 100, $score ),
                'reason'   => self::edu_match_reason( $e, $domain, $budget ),
            ];
        }
        usort( $edu_scores, fn( $a, $b ) => $b['score'] <=> $a['score'] );

        return [
            'domain'     => $domain,
            'budget'     => $path['budget'] ?? [],
            'orgs'       => array_slice( $org_scores, 0, 5 ),
            'educators'  => array_slice( $edu_scores, 0, 5 ),
        ];
    }

    private static function org_match_reason( array $org, string $domain, int $budget, string $tier ): string {
        $parts = [ $org['city'] ?? '' ];
        $fac   = count( $org['profile']['facilities'] ?? [] );
        if ( $fac ) {
            $parts[] = $fac . ' امکانات';
        }
        if ( $budget > 0 ) {
            $parts[] = 'متناسب بودجه ' . number_format( $budget );
        }
        return implode( ' · ', array_filter( $parts ) );
    }

    private static function edu_match_reason( array $ed, string $domain, int $budget ): string {
        $parts = [];
        if ( in_array( $domain, $ed['profile']['skill_cv'] ?? [], true ) ) {
            $parts[] = 'تخصص ' . $domain;
        }
        $parts[] = number_format( (float) ( $ed['hourly_rate'] ?? 0 ) ) . '/ساعت';
        if ( $budget > 0 ) {
            $parts[] = 'در محدوده بودجه';
        }
        return implode( ' · ', $parts );
    }

    /** Graph-RAG lite — بافت ساخت‌یافته برای AI */
    public static function graph_rag_context( int $user_id ): array {
        require_once ACC_PATH . 'includes/helpers/education-lifepath.php';
        require_once ACC_PATH . 'includes/helpers/education-platform.php';

        $state    = Edu_LifePath::companion_state( $user_id );
        $profile  = $state['profile'] ?? [];
        $nodes    = [];
        $edges    = [];

        $nodes[] = [ 'type' => 'learner', 'id' => 'learner', 'label' => $profile['identity']['full_name'] ?? 'دانش‌آموز', 'grade' => $state['learner']['grade_level'] ?? '' ];

        foreach ( $profile['academic_history'] ?? [] as $i => $h ) {
            $nid = 'grade_' . ( $h['grade'] ?? $i );
            $nodes[] = [ 'type' => 'grade_record', 'id' => $nid, 'grade' => $h['grade'] ?? '', 'avg' => $h['report_avg'] ?? null, 'school' => $h['school_name'] ?? '' ];
            $edges[] = [ 'from' => 'learner', 'to' => $nid, 'rel' => 'studied' ];
        }
        foreach ( $profile['career']['dream_jobs'] ?? [] as $j ) {
            $nid = 'career_' . $j;
            $nodes[] = [ 'type' => 'career_goal', 'id' => $nid, 'job' => $j ];
            $edges[] = [ 'from' => 'learner', 'to' => $nid, 'rel' => 'aspires' ];
        }
        foreach ( $state['timeline']['academic'] ?? [] as $log ) {
            $nodes[] = [ 'type' => 'event', 'id' => 'ev_' . $log['id'], 'title' => $log['title'] ?? '' ];
            $edges[] = [ 'from' => 'learner', 'to' => 'ev_' . $log['id'], 'rel' => 'timeline' ];
        }
        if ( ! empty( $state['plan']['plan']['weeks'] ) ) {
            $nodes[] = [ 'type' => 'plan', 'id' => 'active_plan', 'weeks' => count( $state['plan']['plan']['weeks'] ) ];
            $edges[] = [ 'from' => 'learner', 'to' => 'active_plan', 'rel' => 'follows' ];
        }
        $nodes[] = [ 'type' => 'budget', 'id' => 'family_budget', 'tier' => $profile['family']['budget_tier'] ?? '', 'amount' => $profile['family']['monthly_budget_rial'] ?? 0, 'approved' => ! empty( $profile['family']['budget_approved'] ) ];

        $text_blocks = [];
        $text_blocks[] = '=== Learner Graph ===';
        foreach ( $nodes as $n ) {
            $text_blocks[] = wp_json_encode( $n, JSON_UNESCAPED_UNICODE );
        }
        $text_blocks[] = '=== Relations ===';
        foreach ( $edges as $e ) {
            $text_blocks[] = $e['from'] . ' -[' . $e['rel'] . ']-> ' . $e['to'];
        }
        if ( ! empty( $state['life_path']['phases'] ) ) {
            $text_blocks[] = '=== Life Path ===';
            foreach ( $state['life_path']['phases'] as $ph ) {
                $text_blocks[] = $ph['label'] . ': ' . implode( '; ', $ph['items'] ?? [] );
            }
        }

        return [
            'nodes'       => $nodes,
            'edges'       => $edges,
            'text'        => implode( "\n", $text_blocks ),
            'node_count'  => count( $nodes ),
            'edge_count'  => count( $edges ),
        ];
    }
}
