<?php

namespace App\Classes\Modules\Affiliate\Services;

use App\Models\Affiliate;
use App\Models\User;
use App\Models\UserAffiliate;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TracksAffiliateRegistration
{
    /**
     * Track when a user registers with an affiliate code
     * 
     * @param User $user
     * @return Affiliate|null
     */
    public function execute(User $user, ?string $code = null): ?Affiliate
    {
        // Log::info('TracksAffiliateRegistration::execute', ['user' => $user, 'code' => $code]);

        if (!$code || !$this->isValidCode($code)) {
            Log::info('Code is not valid', ['code' => $code]);
            return null;
        }

        $affiliate = Affiliate::where('code', $code)
            ->where('is_active', true)
            ->first();

        if (!$affiliate) {
            return null;
        }

        // Check if user is already linked to this affiliate
        $userAffiliate = UserAffiliate::where('user_id', $user->id)
            ->where('affiliate_id', $affiliate->id)
            ->first();

        if (!$userAffiliate) {
            // Create new link
            $userAffiliate = new UserAffiliate();
            $userAffiliate->user_id = $user->id;
            $userAffiliate->affiliate_id = $affiliate->id;
            $userAffiliate->clicked_at = now(); // Approximate, we don't track exact click time
            $userAffiliate->registered_at = now();
            $userAffiliate->save();

            // Increment registrations count
            $affiliate->increment('registrations_count');
        } else {
            // Update registration time if not set
            if (!$userAffiliate->registered_at) {
                $userAffiliate->registered_at = now();
                $userAffiliate->save();
                $affiliate->increment('registrations_count');
            }
        }

        // Clear the cookie after registration
        Cookie::queue(Cookie::forget(TracksAffiliateClick::COOKIE_NAME));

        return $affiliate;
    }

    /**
     * Validate affiliate code format
     * 
     * @param string $code
     * @return bool
     */
    private function isValidCode(string $code): bool
    {
        // Check length (max 255 chars based on database schema)
        if (strlen($code) > 255 || strlen($code) < 1) {
            return false;
        }

        // Only allow alphanumeric characters, hyphens, and underscores
        return (bool) preg_match('/^[a-zA-Z0-9_-]+$/', $code);
    }
}

