<?php
/**
 * Edu_GIS — موقعیت مؤسسات · فاصله ایاب‌ذهاب · کاشی آفلاین محلی
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Edu_GIS {

    /** قالب کاشی محلی — همان الگوی نقشه هوشمند (tiles_esri) */
    public const OSM_TILE = '/acc-engine/assets/vendor/leaflet/tiles_esri/{z}/{x}/{y}.png';
    public const OSM_ATTR = '© Esri (local offline)';

    public static function haversine_km( float $lat1, float $lng1, float $lat2, float $lng2 ): float {
        $r = 6371.0;
        $dLat = deg2rad( $lat2 - $lat1 );
        $dLng = deg2rad( $lng2 - $lng1 );
        $a = sin( $dLat / 2 ) ** 2 + cos( deg2rad( $lat1 ) ) * cos( deg2rad( $lat2 ) ) * sin( $dLng / 2 ) ** 2;
        return round( $r * 2 * atan2( sqrt( $a ), sqrt( 1 - $a ) ), 2 );
    }

    public static function org_markers(): array {
        global $wpdb;
        require_once ACC_PATH . 'includes/helpers/education-platform.php';
        $t = Education_Platform::tbl( 'organizations' );
        $rows = $wpdb->get_results(
            "SELECT id, name, org_type, city, address_text, lat, lng FROM {$t}
             WHERE is_active = 1 AND lat IS NOT NULL AND lng IS NOT NULL",
            ARRAY_A
        ) ?: [];
        $markers = [];
        foreach ( $rows as $r ) {
            $markers[] = [
                'id'    => (int) $r['id'],
                'type'  => $r['org_type'] ?? 'school',
                'title' => $r['name'],
                'meta'  => ( $r['city'] ?? '' ) . ' — ' . ( $r['address_text'] ?? '' ),
                'lat'   => (float) $r['lat'],
                'lng'   => (float) $r['lng'],
            ];
        }
        return $markers;
    }

    public static function session_markers(): array {
        global $wpdb;
        require_once ACC_PATH . 'includes/helpers/education-platform.php';
        $st = Education_Platform::tbl( 'sessions' );
        $rows = $wpdb->get_results(
            "SELECT s.id, s.status, s.venue_type, s.delivery_mode, s.domain, s.distance_km,
                    s.learner_lat, s.learner_lng, l.user_id
             FROM {$st} s
             INNER JOIN " . Education_Platform::tbl( 'learners' ) . " l ON l.id = s.learner_id
             WHERE s.venue_type = 'home' AND s.learner_lat IS NOT NULL
             ORDER BY s.id DESC LIMIT 30",
            ARRAY_A
        ) ?: [];
        $out = [];
        foreach ( $rows as $r ) {
            $out[] = [
                'id'    => (int) $r['id'],
                'type'  => 'home_session',
                'title' => 'جلسه منزل #' . $r['id'],
                'meta'  => ( $r['domain'] ?? '' ) . ' · ' . ( $r['distance_km'] ?? 0 ) . ' km',
                'lat'   => (float) $r['learner_lat'],
                'lng'   => (float) $r['learner_lng'],
            ];
        }
        return $out;
    }

    public static function map_payload(): array {
        $markers = array_merge( self::org_markers(), self::session_markers() );
        $center  = [ 'lat' => 35.6892, 'lng' => 51.3890, 'zoom' => 11 ];
        if ( $markers ) {
            $center['lat'] = array_sum( array_column( $markers, 'lat' ) ) / count( $markers );
            $center['lng'] = array_sum( array_column( $markers, 'lng' ) ) / count( $markers );
        }
        return [
            'center'     => $center,
            'markers'    => $markers,
            'tile_url'   => self::OSM_TILE,
            'attribution'=> self::OSM_ATTR,
            'legend'     => [
                'school'       => 'مدرسه',
                'institute'    => 'مؤسسه',
                'home_session' => 'جلسه منزل',
            ],
        ];
    }

    public static function distance_for_session( array $learner_profile, int $org_id ): float {
        global $wpdb;
        $lat1 = (float) ( $learner_profile['home_lat'] ?? 0 );
        $lng1 = (float) ( $learner_profile['home_lng'] ?? 0 );
        if ( ! $org_id || ! $lat1 ) {
            return 0.0;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT lat, lng FROM " . $wpdb->prefix . "edu_organizations WHERE id = %d", $org_id
        ), ARRAY_A );
        if ( ! $row || ! $row['lat'] ) {
            return 0.0;
        }
        return self::haversine_km( $lat1, $lng1, (float) $row['lat'], (float) $row['lng'] );
    }
}

// Alias for backward compat in seed file
class_alias( Edu_GIS::class, 'Education_GIS' );
