<?php
/**
 * Melk_Advisory — جلسات مشاوره مالیاتی/حقوقی
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Melk_Advisory {

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

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

    public static function can_use( int $uid ): bool {
        return acl_user_is_super_admin( $uid )
            || acl_user_can( $uid, 'melk.advisory.use' )
            || acl_user_can( $uid, 'melk.manage' );
    }

    public static function create_session( int $user_id, array $data ): int {
        global $wpdb;
        $wpdb->insert( self::sessions_table(), [
            'user_id'    => $user_id,
            'topic'      => sanitize_key( $data['topic'] ?? 'both' ),
            'title'      => sanitize_text_field( $data['title'] ?? 'مشاوره جدید' ),
            'case_id'    => ! empty( $data['case_id'] ) ? (int) $data['case_id'] : null,
            'listing_id' => ! empty( $data['listing_id'] ) ? (int) $data['listing_id'] : null,
            'status'     => 'open',
            'created_at' => current_time( 'mysql' ),
        ] );
        return (int) $wpdb->insert_id;
    }

    public static function list_sessions( int $user_id, int $limit = 30 ): array {
        global $wpdb;
        return $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM " . self::sessions_table() . " WHERE user_id = %d ORDER BY updated_at DESC, id DESC LIMIT %d",
            $user_id, $limit
        ), ARRAY_A ) ?: [];
    }

    public static function get_session( int $id, int $user_id ): ?array {
        global $wpdb;
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM " . self::sessions_table() . " WHERE id = %d AND user_id = %d", $id, $user_id
        ), ARRAY_A );
        return $row ?: null;
    }

    public static function touch_session( int $session_id ): void {
        global $wpdb;
        $wpdb->update( self::sessions_table(), [
            'updated_at' => current_time( 'mysql' ),
        ], [ 'id' => $session_id ] );
    }

    public static function add_message( int $session_id, string $role, string $body, string $engine = 'user', ?string $model = null ): int {
        global $wpdb;
        $wpdb->insert( self::messages_table(), [
            'session_id' => $session_id,
            'role'       => sanitize_key( $role ),
            'body'       => $body,
            'engine'     => sanitize_key( $engine ),
            'model'      => $model ? sanitize_text_field( $model ) : null,
            'created_at' => current_time( 'mysql' ),
        ] );
        self::touch_session( $session_id );
        return (int) $wpdb->insert_id;
    }

    public static function list_messages( int $session_id, int $user_id ): array {
        global $wpdb;
        $session = self::get_session( $session_id, $user_id );
        if ( ! $session ) return [];
        return $wpdb->get_results( $wpdb->prepare(
            "SELECT id, role, body, engine, model, created_at FROM " . self::messages_table() . "
             WHERE session_id = %d ORDER BY id ASC",
            $session_id
        ), ARRAY_A ) ?: [];
    }

    public static function build_transaction_context( array $ctx ): string {
        global $wpdb;
        $lines = [];
        if ( ! empty( $ctx['deal_type'] ) ) {
            $lines[] = 'نوع معامله: ' . $ctx['deal_type'];
        }
        if ( ! empty( $ctx['property_type'] ) ) {
            $lines[] = 'نوع ملک: ' . $ctx['property_type'];
        }
        if ( ! empty( $ctx['district_id'] ) ) {
            $d = $wpdb->get_var( $wpdb->prepare(
                "SELECT name FROM {$wpdb->prefix}gis_districts WHERE id = %d", (int) $ctx['district_id']
            ) );
            $lines[] = 'منطقه: ' . ( $d ?: $ctx['district_id'] );
        }
        if ( ! empty( $ctx['area_sqm'] ) ) {
            $lines[] = 'متراژ: ' . $ctx['area_sqm'] . ' m²';
        }
        if ( ! empty( $ctx['price'] ) ) {
            $lines[] = 'قیمت/ارزش: ' . number_format( (float) $ctx['price'] ) . ' ریال';
        }
        if ( ! empty( $ctx['listing_id'] ) ) {
            $l = $wpdb->get_row( $wpdb->prepare(
                "SELECT title, deal_type, area_sqm, price, district_id FROM {$wpdb->prefix}melk_listings WHERE id = %d",
                (int) $ctx['listing_id']
            ), ARRAY_A );
            if ( $l ) {
                $lines[] = "آگهی #{$ctx['listing_id']}: {$l['title']} | {$l['deal_type']} | {$l['area_sqm']}m²";
            }
        }
        if ( ! empty( $ctx['case_id'] ) ) {
            $c = $wpdb->get_row( $wpdb->prepare(
                "SELECT title, status, district_id FROM {$wpdb->prefix}melk_cases WHERE id = %d",
                (int) $ctx['case_id']
            ), ARRAY_A );
            if ( $c ) {
                $lines[] = "پرونده #{$ctx['case_id']}: {$c['title']} ({$c['status']})";
            }
        }
        return $lines ? implode( "\n", $lines ) : '';
    }
}
