<?php

namespace MtcPharmacy\ReferAFriend\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
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.',
            ]);
        }

        // Set tracking cookie (90-day lifetime)
        $cookieLifetime = config('referrals.fraud.cookie_lifetime_days') * 24 * 60; // minutes
        $cookie = cookie(
            config('referrals.fraud.cookie_name'),
            $code,
            $cookieLifetime
        );

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

        // Log the link click
        \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($cookie);
    }
}
