<?php
/**
 * Arag_Referral — معرفی دوستان فروشگاه عرقیات
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Arag_Referral {

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

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

    public static function generate_code( string $seed = '' ): string {
        $base = strtoupper( preg_replace( '/[^A-Z0-9]/', '', $seed ) );
        if ( strlen( $base ) < 4 ) {
            $base = strtoupper( substr( md5( $seed . microtime() ), 0, 6 ) );
        }
        return 'REF' . substr( $base, 0, 6 );
    }

    public static function get_or_create( int $user_id = 0, string $phone = '' ): array {
        global $wpdb;
        $t = self::table();
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t}'" ) !== $t ) {
            return [ 'success' => false, 'message' => 'ماژول معرفی نصب نشده' ];
        }
        $phone = preg_replace( '/\D/', '', $phone );
        if ( $user_id > 0 ) {
            $row = $wpdb->get_row( $wpdb->prepare(
                "SELECT * FROM {$t} WHERE user_id = %d LIMIT 1", $user_id
            ), ARRAY_A );
            if ( $row ) {
                return [ 'success' => true, 'data' => self::format_row( $row ) ];
            }
        }
        if ( $phone ) {
            $row = $wpdb->get_row( $wpdb->prepare(
                "SELECT * FROM {$t} WHERE phone = %s LIMIT 1", $phone
            ), ARRAY_A );
            if ( $row ) {
                return [ 'success' => true, 'data' => self::format_row( $row ) ];
            }
        }
        $code = self::generate_code( $phone ?: (string) $user_id );
        for ( $i = 0; $i < 5; $i++ ) {
            $exists = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT id FROM {$t} WHERE code = %s", $code
            ) );
            if ( ! $exists ) break;
            $code = self::generate_code( $code . $i );
        }
        $wpdb->insert( $t, [
            'user_id' => $user_id,
            'phone'   => $phone,
            'code'    => $code,
        ] );
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$t} WHERE id = %d", (int) $wpdb->insert_id
        ), ARRAY_A );
        return [ 'success' => true, 'data' => self::format_row( $row ) ];
    }

    public static function format_row( array $row ): array {
        $site = rtrim( defined( 'ACC_URL' ) ? ACC_URL : '/acc-engine/', '/' );
        return [
            'code'        => $row['code'],
            'uses_count'  => (int) ( $row['uses_count'] ?? 0 ),
            'reward_total'=> (float) ( $row['reward_total'] ?? 0 ),
            'share_url'   => $site . '/shop.php?ref=' . rawurlencode( $row['code'] ),
            'share_text'  => "با کد {$row['code']} از فروشگاه عرقیات ۱۰٪ تخفیف بگیر: {$site}/shop.php?ref={$row['code']}",
        ];
    }

    public static function validate_code( string $code ): ?array {
        global $wpdb;
        $code = strtoupper( sanitize_text_field( $code ) );
        if ( ! preg_match( '/^REF[A-Z0-9]{3,8}$/', $code ) ) {
            return null;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM " . self::table() . " WHERE code = %s LIMIT 1", $code
        ), ARRAY_A );
        return $row ?: null;
    }

    public static function record_use( string $code, int $order_id, string $buyer_phone, float $discount ): void {
        global $wpdb;
        $ref = self::validate_code( $code );
        if ( ! $ref ) return;
        $wpdb->insert( self::uses_table(), [
            'referral_id'     => (int) $ref['id'],
            'order_id'        => $order_id,
            'buyer_phone'     => sanitize_text_field( $buyer_phone ),
            'discount_amount' => $discount,
        ] );
        $wpdb->query( $wpdb->prepare(
            "UPDATE " . self::table() . " SET uses_count = uses_count + 1, reward_total = reward_total + %f WHERE id = %d",
            $discount * 0.1, (int) $ref['id']
        ) );
    }
}
