<?php
/**
 * election-personal-hq.php — ستاد شخصی + intel GIS/ERP (فقط مدیر)
 */
if ( ! defined( 'ABSPATH' ) ) exit;

trait Election_Personal_HQ {

    public static function hqs_table(): string {
        global $wpdb;
        return $wpdb->prefix . 'election_hqs';
    }

    public static function missions_table(): string {
        global $wpdb;
        return $wpdb->prefix . 'election_missions';
    }

    public static function has_hq( int $uid ): bool {
        return (bool) self::get_hq_by_user( $uid );
    }

    public static function get_hq_by_user( int $uid ): ?array {
        global $wpdb;
        $t = self::hqs_table();
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t}'" ) !== $t ) {
            return null;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$t} WHERE user_id = %d AND is_active = 1", $uid
        ), ARRAY_A );
        return $row ? self::fmt_hq( $row, false ) : null;
    }

    public static function fmt_hq( array $row, bool $include_intel = false ): array {
        $row['block_codes'] = json_decode( $row['block_codes_json'] ?? '[]', true ) ?: [];
        unset( $row['block_codes_json'] );
        $row['category_label'] = self::BRANCH_CATEGORIES[ $row['category'] ?? '' ] ?? ( $row['category'] ?? '' );
        $row['role_label'] = ( $row['role_type'] ?? '' ) === 'coordinator' ? 'ستاد هماهنگ‌کننده' : 'ستاد شخصی';
        if ( ! $include_intel ) {
            unset( $row['gis_intel_json'] );
        } else {
            $row['gis_intel'] = json_decode( $row['gis_intel_json'] ?? '{}', true ) ?: [];
            unset( $row['gis_intel_json'] );
        }
        return $row;
    }

    public static function list_hqs( bool $intel = false ): array {
        global $wpdb;
        $t = self::hqs_table();
        $rows = $wpdb->get_results(
            "SELECT * FROM {$t} WHERE is_active = 1 ORDER BY role_type DESC, performance_score DESC",
            ARRAY_A
        ) ?: [];
        return array_map( fn( $r ) => self::fmt_hq( $r, $intel ), $rows );
    }

    public static function list_missions( int $hq_id ): array {
        global $wpdb;
        $t = self::missions_table();
        return $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$t} WHERE hq_id = %d ORDER BY FIELD(status,'pending','in_progress','done','verified'), id DESC",
            $hq_id
        ), ARRAY_A ) ?: [];
    }

    public static function gis_tables_exist(): bool {
        global $wpdb;
        return $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}gis_neighborhoods'" ) === $wpdb->prefix . 'gis_neighborhoods';
    }

    /** intel خام GIS — فقط مدیر سامانه هوادران */
    public static function admin_gis_intel(): array {
        global $wpdb;
        if ( ! self::gis_tables_exist() ) {
            return [ 'available' => false, 'message' => 'جداول GIS نصب نشده', 'districts' => [], 'neighborhoods' => [], 'blocks' => [] ];
        }
        $pre = $wpdb->prefix;
        $districts = $wpdb->get_results(
            "SELECT d.id, d.name, d.code, d.city,
                (SELECT COUNT(*) FROM {$pre}gis_neighborhoods n WHERE n.district_id = d.id) AS neighborhood_count,
                (SELECT COUNT(*) FROM {$pre}gis_parcels p WHERE p.district_id = d.id) AS parcel_count
             FROM {$pre}gis_districts d ORDER BY d.id LIMIT 50",
            ARRAY_A
        ) ?: [];

        $neighborhoods = $wpdb->get_results(
            "SELECT n.id, n.name, n.district_id, d.name AS district_name, n.area_km2,
                (SELECT COUNT(*) FROM {$pre}gis_parcels p WHERE p.neighborhood_id = n.id) AS parcel_count,
                (SELECT COALESCE(SUM(p.apt_count),0) FROM {$pre}gis_parcels p WHERE p.neighborhood_id = n.id) AS unit_count
             FROM {$pre}gis_neighborhoods n
             LEFT JOIN {$pre}gis_districts d ON d.id = n.district_id
             ORDER BY parcel_count DESC LIMIT 150",
            ARRAY_A
        ) ?: [];

        $blocks = [];
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$pre}gis_block_stats'" ) === $pre . 'gis_block_stats' ) {
            $blocks = $wpdb->get_results(
                "SELECT bs.block_code, bs.neighborhood_id, bs.district_id,
                    n.name AS neighborhood_name, d.name AS district_name,
                    bs.total_parcels AS parcel_count, bs.cnt_building AS bld_count,
                    bs.cnt_apartment AS apt_count, bs.cnt_shop AS shop_count,
                    bs.center_lat, bs.center_lng
                 FROM {$pre}gis_block_stats bs
                 LEFT JOIN {$pre}gis_neighborhoods n ON n.id = bs.neighborhood_id
                 LEFT JOIN {$pre}gis_districts d ON d.id = bs.district_id
                 ORDER BY bs.total_parcels DESC LIMIT 120",
                ARRAY_A
            ) ?: [];
        }

        return [
            'available'     => true,
            'districts'     => $districts,
            'neighborhoods' => $neighborhoods,
            'blocks'        => $blocks,
            'synced_at'     => current_time( 'mysql' ),
        ];
    }

    /** خلاصه ERP — فقط مدیر */
    public static function admin_erp_intel(): array {
        global $wpdb;
        $pre = $wpdb->prefix;
        $out = [
            'users_total'    => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->users}" ),
            'gis_parcels'    => 0,
            'melk_cases'     => 0,
            'melk_open'      => 0,
            'active_hqs'     => (int) $wpdb->get_var( "SELECT COUNT(*) FROM " . self::hqs_table() . " WHERE is_active=1" ),
        ];
        if ( self::gis_tables_exist() ) {
            $out['gis_parcels'] = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$pre}gis_parcels" );
        }
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$pre}melk_cases'" ) === $pre . 'melk_cases' ) {
            $out['melk_cases'] = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$pre}melk_cases" );
            $out['melk_open']  = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$pre}melk_cases WHERE status NOT IN ('closed','archived')" );
        }
        return $out;
    }

    public static function assign_zone_to_hq( int $hq_id, array $data ): array {
        global $wpdb;
        if ( ! self::gis_tables_exist() ) {
            return [ 'success' => false, 'message' => 'GIS در دسترس نیست' ];
        }
        $hq = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . self::hqs_table() . " WHERE id = %d", $hq_id ), ARRAY_A );
        if ( ! $hq ) {
            return [ 'success' => false, 'message' => 'ستاد یافت نشد' ];
        }

        $pre = $wpdb->prefix;
        $nb_id = (int) ( $data['neighborhood_id'] ?? 0 );
        $block_codes = array_values( array_filter( (array) ( $data['block_codes'] ?? [] ) ) );

        $nb = $nb_id ? $wpdb->get_row( $wpdb->prepare(
            "SELECT n.*, d.name AS district_name FROM {$pre}gis_neighborhoods n
             LEFT JOIN {$pre}gis_districts d ON d.id = n.district_id WHERE n.id = %d", $nb_id
        ), ARRAY_A ) : null;

        $parcel_count = 0;
        $apt_count    = 0;
        $intel_blocks = [];

        if ( $block_codes ) {
            $ph = implode( ',', array_fill( 0, count( $block_codes ), '%s' ) );
            $rows = $wpdb->get_results( $wpdb->prepare(
                "SELECT * FROM {$pre}gis_block_stats WHERE block_code IN ($ph)", ...$block_codes
            ), ARRAY_A ) ?: [];
            foreach ( $rows as $b ) {
                $parcel_count += (int) ( $b['total_parcels'] ?? $b['parcel_count'] ?? 0 );
                $apt_count    += (int) ( $b['cnt_apartment'] ?? $b['apt_count'] ?? 0 );
                $intel_blocks[] = $b;
            }
        } elseif ( $nb ) {
            $parcel_count = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM {$pre}gis_parcels WHERE neighborhood_id = %d", $nb_id
            ) );
            $apt_count = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COALESCE(SUM(apt_count),0) FROM {$pre}gis_parcels WHERE neighborhood_id = %d", $nb_id
            ) );
        }

        $voter_est = (int) round( $apt_count * 2.8 );
        $household = max( $apt_count, (int) round( $parcel_count * 1.4 ) );

        $zone_label = $nb
            ? ( $nb['district_name'] ?? '' ) . ' — محله ' . ( $nb['name'] ?? '' )
            : ( $data['zone_label'] ?? 'محدوده اختصاصی' );

        if ( $block_codes ) {
            $zone_label .= ' (' . count( $block_codes ) . ' بلوک)';
        }

        $gis_intel = [
            'neighborhood_id'   => $nb_id,
            'neighborhood_name'=> $nb['name'] ?? '',
            'district_name'     => $nb['district_name'] ?? '',
            'block_codes'       => $block_codes,
            'blocks_detail'     => $intel_blocks,
            'parcel_count'      => $parcel_count,
            'assigned_at'       => current_time( 'mysql' ),
        ];

        $mission_brief = self::build_mission_brief( $zone_label, $household, $voter_est, $block_codes );

        $wpdb->update( self::hqs_table(), [
            'zone_label'          => $zone_label,
            'neighborhood_name'   => $nb['name'] ?? '',
            'district_name'       => $nb['district_name'] ?? '',
            'gis_neighborhood_id' => $nb_id ?: null,
            'block_codes_json'    => wp_json_encode( $block_codes, JSON_UNESCAPED_UNICODE ),
            'parcel_count'        => $parcel_count,
            'household_estimate'  => $household,
            'voter_estimate'      => $voter_est,
            'mission_brief'       => $mission_brief,
            'gis_intel_json'      => wp_json_encode( $gis_intel, JSON_UNESCAPED_UNICODE ),
            'updated_at'          => current_time( 'mysql' ),
        ], [ 'id' => $hq_id ] );

        self::seed_missions_for_hq( $hq_id, $zone_label, $household, $block_codes );

        return [ 'success' => true, 'hq_id' => $hq_id, 'zone_label' => $zone_label ];
    }

    public static function build_mission_brief( string $zone, int $households, int $voters, array $blocks ): string {
        $lines = [
            "🎯 **ستاد شخصی شما — {$zone}**",
            "شما نیازی به مراجعه به ستاد مرکزی ندارید. همه ابزار در همین سامانه است.",
            "",
            "📊 **برآورد منطقه (از نقشه هوشمند):**",
            "• خانوار تقریبی: **" . number_format( $households ) . "**",
            "• رأی‌دهنده تقریبی: **" . number_format( $voters ) . "**",
        ];
        if ( $blocks ) {
            $lines[] = "• بلوک‌های تحت پوشش: " . implode( '، ', array_slice( $blocks, 0, 5 ) );
        }
        $lines[] = "";
        $lines[] = "✅ ماموریت‌ها، بسته توزیع و گزارش — از تب‌های همین پورتال.";
        return implode( "\n", $lines );
    }

    public static function seed_missions_for_hq( int $hq_id, string $zone, int $households, array $blocks ): void {
        global $wpdb;
        $t = self::missions_table();
        $wpdb->query( $wpdb->prepare( "DELETE FROM {$t} WHERE hq_id = %d AND status = 'pending'", $hq_id ) );

        $missions = [
            [ 'آشنایی با محدوده ستاد', "محدوده «{$zone}» را روی نقشه ذهنی مرور کنید. نیازی به مراجعه حضوری نیست.", 'orientation', 1 ],
            [ 'توزیع بسته ۲۱ نفره', 'اولین بسته بارکددار را در محدوده خود توزیع کنید.', 'package_21', 21 ],
            [ 'گزارش روزانه ستاد', 'خلاصه فعالیت امروز را ثبت کنید — امتیاز عملکرد شماست.', 'report', 1 ],
        ];
        if ( $households > 100 ) {
            $missions[] = [ 'پوشش بلوک اول', 'بلوک ' . ( $blocks[0] ?? '—' ) . ' را اولویت دهید.', 'block', min( 31, $households ) ];
        }

        foreach ( $missions as [ $title, $body, $type, $target ] ) {
            $wpdb->insert( $t, [
                'hq_id'        => $hq_id,
                'title'        => $title,
                'body'         => $body,
                'mission_type' => $type,
                'target_count' => $target,
                'progress_count'=> 0,
                'status'       => 'pending',
                'created_at'   => current_time( 'mysql' ),
            ] );
        }
    }

    public static function complete_mission( int $uid, int $mission_id ): array {
        global $wpdb;
        $hq = self::get_hq_by_user( $uid );
        if ( ! $hq ) {
            return [ 'success' => false, 'message' => 'ستاد شخصی یافت نشد' ];
        }
        $t = self::missions_table();
        $m = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$t} WHERE id = %d AND hq_id = %d", $mission_id, (int) $hq['id']
        ), ARRAY_A );
        if ( ! $m ) {
            return [ 'success' => false, 'message' => 'ماموریت یافت نشد' ];
        }
        $wpdb->update( $t, [
            'status' => 'done',
            'progress_count' => (int) $m['target_count'],
        ], [ 'id' => $mission_id ] );
        $wpdb->query( $wpdb->prepare(
            "UPDATE " . self::hqs_table() . " SET performance_score = performance_score + 2, missions_done = missions_done + 1, tasks_done = tasks_done + 1 WHERE id = %d",
            (int) $hq['id']
        ) );
        return [ 'success' => true ];
    }

    public static function personal_hq_dashboard( int $uid ): array {
        $hq = self::get_hq_by_user( $uid );
        if ( ! $hq && ! self::can_manage( $uid ) ) {
            return [ 'role' => 'none', 'message' => 'ستاد شخصی برای شما تعریف نشده' ];
        }

        if ( self::can_manage( $uid ) && ! $hq ) {
            return [
                'role'       => 'admin',
                'tagline'    => 'مرکز اطلاعات GIS/ERP — تخصیص محدوده به ستادهای شخصی',
                'stats'      => self::stats(),
                'erp'        => self::admin_erp_intel(),
                'gis_available' => self::gis_tables_exist(),
                'hqs_count'  => count( self::list_hqs() ),
            ];
        }

        $missions = self::list_missions( (int) $hq['id'] );
        $pending  = count( array_filter( $missions, fn( $m ) => ( $m['status'] ?? '' ) === 'pending' ) );

        return [
            'role'            => ( $hq['role_type'] ?? '' ) === 'coordinator' ? 'coordinator' : 'personal',
            'tagline'         => 'ستاد شخصی — بدون نیاز به مراجعه حضوری',
            'hq'              => $hq,
            'missions'        => $missions,
            'missions_pending'=> $pending,
            'packages'        => self::list_packages( null ),
            'content'         => self::content_for_user( $uid ),
            'can_invite'      => ( $hq['role_type'] ?? '' ) === 'coordinator',
        ];
    }
}
