<?php

namespace MtcPharmacy\ReferAFriend\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;
use Mtc\Modules\Members\Classes\Auth;
use MtcPharmacy\ReferAFriend\Models\Referral;

class ReferralLandingController extends Controller
{
    public function index(Request $request)
    {
        $member = Auth::getLoggedInMember();
        if ($member && $member->id) {
            return redirect('/members/referrals');
        }

        return template('referrals/landing.twig', [
            'page_meta' => ['page_title' => 'Refer a Friend'],
        ]);
    }

    public function handleCode(Request $request, string $code)
    {
        $referral = Referral::where('referral_code', $code)
            ->where('status', 'pending')
            ->first();

        if (!$referral) {
            return template('referrals/landing.twig', [
                'page_meta' => ['page_title' => 'Refer a Friend'],
                'error'     => 'This referral link is no longer valid.',
            ]);
        }

        // Check if expired
        if ($referral->expires_at && $referral->expires_at->isPast()) {
            return template('referrals/landing.twig', [
                'page_meta' => ['page_title' => 'Refer a Friend'],
                'error'     => 'This referral link has expired. You can still browse our site and create an account.',
            ]);
        }

        // Block the referrer following their own link (closes the
        // logout-then-register self-referral path).
        $loggedInMember = Auth::getLoggedInMember();
        if ($loggedInMember && $loggedInMember->id === $referral->referrer_id) {
            return template('referrals/landing.twig', [
                'page_meta' => ['page_title' => 'Refer a Friend'],
                'error'     => "You can't follow your own referral link.",
            ]);
        }

        $cookieLifetime = config('referrals.fraud.cookie_lifetime_days') * 24 * 60; // minutes
        $refCookie = cookie(
            config('referrals.fraud.cookie_name'),
            $code,
            $cookieLifetime
        );

        // Per-device token, separate from the shareable referral code, so
        // checkCookieReuse only flags the same device signing up repeatedly.
        $deviceCookieName = config('referrals.fraud.device_cookie_name');
        $deviceToken = $request->cookie($deviceCookieName) ?: (string) Str::uuid();
        $deviceCookie = cookie($deviceCookieName, $deviceToken, $cookieLifetime);

        session(['referral_code' => $code]);

        \MtcPharmacy\ReferAFriend\Models\ReferralActivityLog::create([
            'referral_id' => $referral->id,
            'member_id'   => null,
            'action'      => 'link_clicked',
            'ip_address'  => $request->ip(),
            'created_at'  => now(),
        ]);

        return redirect('/members/register?redirect=/members/referrals')
            ->withCookie($refCookie)
            ->withCookie($deviceCookie);
    }
}
