<?php
/**
 * svc-supplier.php — تأمین‌کننده خدمات HVAC (پروفایل، کاتالوگ، تطبیق سفارش)
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Svc_Supplier {

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

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

    public static function item_types(): array {
        return [
            'part'      => 'قطعه / کالا',
            'service'   => 'خدمات',
            'equipment' => 'تجهیزات',
        ];
    }

    public static function is_supplier( int $user_id ): bool {
        if ( $user_id <= 0 ) return false;
        if ( function_exists( 'acl_user_can' ) && acl_user_can( $user_id, 'service.supplier.panel' ) ) {
            return true;
        }
        if ( self::_has_role( $user_id, 'service_supplier' ) ) {
            return true;
        }
        global $wpdb;
        return (bool) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}svc_reward_accounts
             WHERE user_id = %d AND actor_type = 'supplier'",
            $user_id
        ) );
    }

    public static function can_manage_catalog( int $user_id ): bool {
        if ( $user_id <= 0 ) return false;
        if ( function_exists( 'acl_user_is_super_admin' ) && acl_user_is_super_admin( $user_id ) ) {
            return true;
        }
        return self::is_supplier( $user_id );
    }

    private static function _has_role( int $user_id, string $slug ): bool {
        global $wpdb;
        return (bool) $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 = %s",
            $user_id, $slug
        ) );
    }

    public static function get_profile( int $user_id ): ?array {
        global $wpdb;
        $t = self::profile_table();
        if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
            return null;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$t} WHERE user_id = %d", $user_id
        ), ARRAY_A );
        return $row ?: null;
    }

    public static function ensure_profile( int $user_id ): array {
        $existing = self::get_profile( $user_id );
        if ( $existing ) return $existing;

        global $wpdb;
        $name = (string) $wpdb->get_var( $wpdb->prepare(
            "SELECT display_name FROM {$wpdb->users} WHERE ID = %d", $user_id
        ) );
        $wpdb->insert( self::profile_table(), [
            'user_id'      => $user_id,
            'company_name' => $name ?: 'تأمین‌کننده',
            'is_active'    => 1,
        ] );
        return self::get_profile( $user_id ) ?: [
            'user_id' => $user_id, 'company_name' => $name, 'is_active' => 1,
        ];
    }

    /**
     * بهترین تطبیق کاتالوگ برای شماره قطعه
     */
    public static function match_catalog_all( string $part_number, int $qty = 1 ): array {
        global $wpdb;
        $part_number = trim( $part_number );
        if ( $part_number === '' ) return [];

        $t = self::catalog_table();
        if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
            return [];
        }

        $like = '%' . $wpdb->esc_like( $part_number ) . '%';
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT c.*, p.company_name, p.phone AS supplier_phone, p.city AS supplier_city
             FROM {$t} c
             INNER JOIN " . self::profile_table() . " p ON p.user_id = c.supplier_user_id AND p.is_active = 1
             WHERE c.is_active = 1 AND c.item_type IN ('part','equipment')
               AND (c.sku = %s OR c.sku LIKE %s OR c.name LIKE %s)
             ORDER BY c.in_stock DESC, c.price ASC, c.id ASC
             LIMIT 20",
            $part_number, $like, $like
        ), ARRAY_A ) ?: [];

        $out = [];
        foreach ( $rows as $row ) {
            $stock = (int) ( $row['stock_qty'] ?? 0 );
            if ( ! empty( $row['in_stock'] ) && $stock > 0 && $stock < $qty ) {
                continue;
            }
            // rating دمو از ترکیب قیمت/موجودی (بدون ستون جدا)
            $row['rating'] = round( min( 5, 3.8 + ( ! empty( $row['in_stock'] ) ? 0.6 : 0.2 )
                + max( 0, ( 5 - (int) ( $row['lead_days'] ?? 5 ) ) * 0.08 ) ), 1 );
            $row['warranty_months'] = (int) ( $row['warranty_months'] ?? 0 );
            if ( $row['warranty_months'] <= 0 ) {
                $row['warranty_months'] = max( 3, 12 - (int) ( $row['lead_days'] ?? 5 ) );
            }
            $out[] = $row;
        }
        return $out;
    }

    public static function match_catalog( string $part_number, int $qty = 1 ): ?array {
        $rows = self::match_catalog_all( $part_number, $qty );
        return $rows[0] ?? null;
    }

    public static function catalog_stats( int $user_id ): array {
        global $wpdb;
        $t = self::catalog_table();
        if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
            return [ 'total' => 0, 'parts' => 0, 'services' => 0, 'equipment' => 0, 'active' => 0 ];
        }
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT item_type, COUNT(*) AS cnt, SUM(is_active) AS active_cnt
             FROM {$t} WHERE supplier_user_id = %d GROUP BY item_type",
            $user_id
        ), ARRAY_A ) ?: [];
        $out = [ 'total' => 0, 'parts' => 0, 'services' => 0, 'equipment' => 0, 'active' => 0 ];
        foreach ( $rows as $r ) {
            $out['total']   += (int) $r['cnt'];
            $out['active']  += (int) $r['active_cnt'];
            $key = $r['item_type'] === 'part' ? 'parts' : ( $r['item_type'] === 'service' ? 'services' : 'equipment' );
            $out[ $key ] = (int) $r['cnt'];
        }
        return $out;
    }
}
