<?php
/**
 * Volade Referral — Parrainage, liens tracking, récompenses
 *
 * @package Volade\SDK
 * @license GPL-2.0-or-later
 */

trait Volade_Referral {

    public function init_referral() {
        add_action( 'wp_ajax_volade_get_referral_link', array( $this, 'ajax_get_referral_link' ) );
        add_action( 'init', array( $this, 'handle_referral_click' ) );
    }

    public function get_referral_link( $user_id = 0 ) {
        if ( ! $user_id ) {
            $user = $this->get_current_user();
            if ( ! $user ) {
                return '';
            }
            $user_id = $user['id'];
        }

        global $wpdb;
        $code = $wpdb->get_var( $wpdb->prepare(
            "SELECT referral_code FROM {$wpdb->prefix}volade_users WHERE id = %d",
            $user_id
        ) );

        if ( ! $code ) {
            $code = $this->generate_referral_code();
            $wpdb->update(
                "{$wpdb->prefix}volade_users",
                array( 'referral_code' => $code ),
                array( 'id' => $user_id )
            );
        }

        return add_query_arg( 'volade_ref', $code, home_url() );
    }

    public function handle_referral_click() {
        if ( empty( $_GET['volade_ref'] ) ) {
            return;
        }

        $code = sanitize_text_field( $_GET['volade_ref'] );
        if ( strlen( $code ) > 20 ) {
            return;
        }

        global $wpdb;
        $referrer = $wpdb->get_row( $wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}volade_users WHERE referral_code = %s LIMIT 1",
            $code
        ) );

        if ( ! $referrer ) {
            return;
        }

        $ip = $_SERVER['REMOTE_ADDR'] ?? '';

        $existing = $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}volade_referrals 
             WHERE referral_code = %s AND ip_address = %s LIMIT 1",
            $code, $ip
        ) );

        if ( $existing ) {
            return;
        }

        $wpdb->insert(
            "{$wpdb->prefix}volade_referrals",
            array(
                'referrer_id'   => $referrer->id,
                'referral_code' => $code,
                'status'        => 'clicked',
                'ip_address'    => $ip,
                'clicked_at'    => current_time( 'mysql' ),
            )
        );

        setcookie( 'volade_ref_code', $code, time() + WEEK_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
    }

    public function convert_referral( $new_user_id ) {
        global $wpdb;

        $code = $_COOKIE['volade_ref_code'] ?? '';
        if ( empty( $code ) ) {
            return;
        }

        $referral = $wpdb->get_row( $wpdb->prepare(
            "SELECT id, referrer_id FROM {$wpdb->prefix}volade_referrals 
             WHERE referral_code = %s AND status = 'clicked' 
             ORDER BY clicked_at DESC LIMIT 1",
            $code
        ) );

        if ( ! $referral ) {
            return;
        }

        $wpdb->update(
            "{$wpdb->prefix}volade_referrals",
            array(
                'status'      => 'converted',
                'referred_id' => $new_user_id,
                'converted_at' => current_time( 'mysql' ),
            ),
            array( 'id' => $referral->id )
        );

        $wpdb->update(
            "{$wpdb->prefix}volade_users",
            array( 'referred_by' => $code ),
            array( 'id' => $new_user_id )
        );

        $this->add_xp( $referral->referrer_id, 'referral' );
        $this->add_xp( $new_user_id, 'referral' );

        $this->sync_referral_to_supabase( $referral->referrer_id, $new_user_id, $code );
    }

    public function get_referral_stats( $user_id ) {
        global $wpdb;

        $clicks = $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}volade_referrals WHERE referrer_id = %d",
            $user_id
        ) );

        $converted = $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}volade_referrals WHERE referrer_id = %d AND status = 'converted'",
            $user_id
        ) );

        $xp_earned = $converted * ( $this->xp_rules['referral'] ?? 100 );

        return array(
            'total_clicks'    => (int) $clicks,
            'total_converted' => (int) $converted,
            'conversion_rate' => $clicks > 0 ? round( ( $converted / $clicks ) * 100, 1 ) : 0,
            'xp_earned'       => $xp_earned,
        );
    }

    private function sync_referral_to_supabase( $referrer_id, $referred_id, $code ) {
        $api = Volade_API::get_instance();
        if ( ! $api ) {
            return;
        }
        $api->post( '/referral/convert', array(
            'referrer_id' => $referrer_id,
            'referred_id' => $referred_id,
            'code'        => $code,
        ) );
    }

    public function ajax_get_referral_link() {
        check_ajax_referer( 'volade_nonce', 'nonce' );
        $user = $this->get_current_user();
        if ( ! $user ) {
            wp_send_json_error( 'Not authenticated' );
        }
        $link = $this->get_referral_link( $user['id'] );
        $stats = $this->get_referral_stats( $user['id'] );
        wp_send_json_success( array(
            'link'  => $link,
            'stats' => $stats,
        ) );
    }

    public function rest_get_referral_link() {
        $user = $this->get_current_user();
        if ( ! $user ) {
            return new WP_REST_Response( array( 'error' => 'Not authenticated' ), 401 );
        }
        return new WP_REST_Response( array(
            'link'  => $this->get_referral_link( $user['id'] ),
            'stats' => $this->get_referral_stats( $user['id'] ),
        ), 200 );
    }
}
