<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Services\Card\AnalyticsService;
use App\Services\Card\CardService;
use App\Services\Card\RewardService;
use App\Services\TierService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

/**
 * Class CardController
 *
 * Controller for handling member card-related actions.
 */
class CardController extends Controller
{
    /**
     * Display the card index view.
     *
     * @param  string  $locale  The locale code
     * @param  string  $card_id  The card ID
     * @param  Request  $request  The HTTP request instance
     * @param  CardService  $cardService  The card service instance
     * @return \Illuminate\View\View
     */
/* public function showCard(string $locale, string $card_id, Request $request, CardService $cardService, AnalyticsService $analyticsService, TierService $tierService)
{
// 1. هات الكارت
    $card = $cardService->findActiveCard($card_id);

    // لو الكارت مش موجود أصلاً في الداتابيز أو مش Active
    if (!$card) {
        return view('member.card.card-404');
    }

    // 2. تحميل الجوائز
    if (!empty($card->parent_card_id)) {
        $parentCard = \App\Models\Card::find($card->parent_card_id);
        if ($parentCard) {
            $rewards = $parentCard->activeRewards()->where('is_active', true)->get();
            $card->setRelation('activeRewards', $rewards);
        }
    } else {
        $card->load(['activeRewards' => function ($query) {
            $query->where('is_active', true);
        }]);
    }

    // 3. زيادة المشاهدات (حطيناها داخل try-catch عشان لو ضربت متبوظش الصفحة)
    try {
        if ($card->club && $card->partner) {
            $analyticsService->incrementViews($card);
        }
    } catch (\Exception $e) {
        // لو حصل مشكلة في الإحصائيات، كمل عادي وافتح الصفحة
        \Log::error("Analytics failed: " . $e->getMessage());
    }

    $memberTierData = null;
    if (auth('member')->check()) {
        $member = auth('member')->user();
        
        // تأكد إن الكارت مربوط بنادي
        if ($card->club) {
            $club = $card->club;
            $memberTier = $member->memberTiers()->forClub($club)->active()->with('tier')->first();

            // اشتراك تلقائي لو مش عضو
            if (!$memberTier) {
                $defaultTier = $club->tiers()->orderBy('points_threshold', 'asc')->first();
                if ($defaultTier) {
                    $memberTier = $member->memberTiers()->create([
                        'club_id'   => $club->id,
                        'tier_id'   => $defaultTier->id,
                        'is_active' => true,
                    ]);
                    $memberTier->load('tier');
                }
            }

            if ($memberTier) {
                $qualifyingStats = $tierService->getQualifyingStats($member, $club);
                $lifetimePoints = $qualifyingStats['lifetime_points'] ?? 0;
                $nextTier = $memberTier->tier->getNextTier();
                
                $memberTierData = [
                    'memberTier' => $memberTier,
                    'club' => $club,
                    'card' => $card,
                    'progress' => [
                        'points' => [
                            'current' => $lifetimePoints,
                            'threshold' => $nextTier ? $nextTier->points_threshold : 0,
                            'percentage' => ($nextTier && $nextTier->points_threshold > 0) 
                                ? min(100, ($lifetimePoints / $nextTier->points_threshold) * 100) 
                                : 0,
                        ],
                    ],
                ];
            }
        }
    }

    return view('member.card.index', compact('card', 'memberTierData'));
} */
public function showCard(string $locale, string $card_id, Request $request, CardService $cardService, AnalyticsService $analyticsService, TierService $tierService)
{
    $card = $cardService->findActiveCard($card_id);

    if (!$card) {
        return view('member.card.card-404');
    }

    $parentCardId = $card->parent_card_id ?? $card->parent_id ?? $card->id;

// هنجيب المكافآت عن طريق الـ Join المباشر مع جدول الربط الوسيط باستخدام آي دي الأب
$myRewards = \App\Models\Reward::join('card_reward', 'rewards.id', '=', 'card_reward.reward_id')
    ->where('card_reward.card_id', $parentCardId)
    ->where('rewards.is_active', true)
    ->select('rewards.*')
    ->get();

// احقنها في الكارت عشان الـ Blade ينطق
$card->setRelation('activeRewards', $myRewards);

    try {
        if ($card->club_id && $card->partner_id) {
            $analyticsService->incrementViews($card);
        }
    } catch (\Exception $e) {
        \Log::error("Analytics failed: " . $e->getMessage());
    }

    $memberTierData = null;
    $member = auth('member')->user();

    if ($member) {
        $memberCardPivot = \DB::table('card_member')
            ->where('card_id', $card->id)
            ->where('member_id', $member->id)
            ->first();

        if ($memberCardPivot) {
            $tier = \App\Models\Tier::find($memberCardPivot->tier_id);

            if ($tier) {
                $card->head = $tier->getTranslation('display_name', app()->getLocale());
                $card->color = $tier->color;

                $qualifyingStats = $tierService->getQualifyingStats($member, $card->club);
                $lifetimePoints = $qualifyingStats['lifetime_points'] ?? 0;
                $card->points = $lifetimePoints;
				$currentBalance = \DB::table('transactions')
					->where('member_id', $member->id)
					->where('card_id', $card->id)
					->whereNull('deleted_at')
					->selectRaw('SUM(points) - SUM(points_used) as balance')
					->first()
					->balance ?? 0;

				// نمرر القيمة للكارت عشان تظهر عند BALANCE
				$card->points = (int) $currentBalance;

                $nextTier = \App\Models\Tier::where('club_id', $card->club_id)
                    ->where('points_threshold', '>', $tier->points_threshold)
                    ->orderBy('points_threshold', 'asc')
                    ->first();

                $fakeMemberTier = new \stdClass();
                $fakeMemberTier->tier = $tier;

                $memberTierData = [
                    'memberTier' => $fakeMemberTier,
                    'club'       => $card->club,
                    'card'       => $card,
                    'progress'   => [
                        'points' => [
                            'current'    => $lifetimePoints,
                            'threshold'  => $nextTier ? $nextTier->points_threshold : 0,
                            'percentage' => ($nextTier && $nextTier->points_threshold > 0) 
                                            ? min(100, ($lifetimePoints / $nextTier->points_threshold) * 100) 
                                            : 0,
                        ],
                    ],
                ];
            }
        }
    }
//dd($card);
    return view('member.card.index', [
    'card' => $card,
    'memberTierData' => $memberTierData,
    // جبر الـ Component يقرأ البيانات الجديدة
    'contentHead' => $tier->getTranslation('display_name', app()->getLocale()),
    'bgColor' => $tier->color,
    'balance' => $lifetimePoints,
    'textColor' => '#ffffff' // أو أي لون نصوص تحبه
]);
}

    /**
     * Display the card reward view.
     *
     * @param  string  $locale  The locale code
     * @param  string  $card_id  The card ID
     * @param  string  $reward_id  The reward ID
     * @param  Request  $request  The HTTP request instance
     * @param  CardService  $cardService  The card service instance
     * @return \Illuminate\View\View
     */
    public function showReward(string $locale, string $card_id, string $reward_id, Request $request, CardService $cardService, RewardService $rewardService, AnalyticsService $analyticsService, TierService $tierService)
    {
        // Card
        $card = $cardService->findActiveCard($card_id);
        if ($card) {
            $card->load('activeRewards');
        }

        if ($card) {
            $cardViewsIncremented = $analyticsService->incrementViews($card);
        }

        // Reward
        $reward = $rewardService->findActiveReward($reward_id);

        if ($reward) {
            $rewardViewsIncremented = $analyticsService->incrementViews($reward, $card);
        }

        // Balance
        $balance = ($card && $reward && auth('member')->check()) ? $card->getMemberBalance(null) : null;

        // Fetch tier data for this card's club (same as showCard)
        $memberTierData = null;
        if ($card && auth('member')->check()) {
            $member = auth('member')->user();
            $club = $card->club;

            if ($club) {
                $memberTier = $member->memberTiers()
                    ->forClub($club)
                    ->active()
                    ->with('tier')
                    ->first();

                // Only show tier if member has actually earned points in this club
                if ($memberTier) {
                    // Get qualifying stats to check if member has earned anything
                    $qualifyingStats = $tierService->getQualifyingStats($member, $club);
                    $lifetimePoints = $qualifyingStats['lifetime_points'] ?? 0;

                    // Only show tier if member has earned points (not just default tier assignment)
                    if ($lifetimePoints > 0) {
                        $nextTier = $memberTier->tier->getNextTier();
                        $progress = [];

                        // If there's a next tier, calculate progress toward it
                        if ($nextTier) {
                            $progress = [
                                'points' => [
                                    'current' => $lifetimePoints,
                                    'threshold' => $nextTier->points_threshold,
                                    'percentage' => $nextTier->points_threshold > 0
                                        ? min(100, ($lifetimePoints / $nextTier->points_threshold) * 100)
                                        : 100,
                                ],
                            ];
                        }

                        $memberTierData = [
                            'memberTier' => $memberTier,
                            'club' => $club,
                            'card' => $card,
                            'progress' => $progress,
                        ];
                    }
                }
            }
        }

        return ($card && $reward) ? view('member.card.reward', compact('card', 'reward', 'balance', 'memberTierData')) : view('member.card.reward-404');
    }

    /**
     * Display the claim reward view.
     *
     * @param  string  $locale  The locale code
     * @param  string  $card_id  The card ID
     * @param  string  $reward_id  The reward ID
     * @param  Request  $request  The HTTP request instance
     * @param  CardService  $cardService  The card service instance
     * @return \Illuminate\View\View
     */
    public function showClaimReward(string $locale, string $card_id, string $reward_id, Request $request, CardService $cardService, RewardService $rewardService, AnalyticsService $analyticsService)
    {
        // Card
        $card = $cardService->findActiveCard($card_id);
        if ($card) {
            $card->load('activeRewards');
        }

        if ($card) {
            $cardViewsIncremented = $analyticsService->incrementViews($card);
        }

        // Reward
        $reward = $rewardService->findActiveReward($reward_id);

        if ($reward) {
            $rewardViewsIncremented = $analyticsService->incrementViews($reward, $card);
        }

        // Balance
        $balance = ($card && $reward && auth('member')->check()) ? $card->getMemberBalance(null) : null;

        // Claim reward URL
        $claimRewardUrl = ($card && $reward && auth('member')->check()) ? URL::signedRoute('staff.claim.reward', ['card_id' => $card->id, 'reward_id' => $reward->id, 'member_identifier' => auth('member')->user()->unique_identifier], $expiration = now()->addMinutes((int) config('default.reward_claim_qr_valid_minutes'))) : null;

        return ($card && $reward) ? view('member.card.reward-claim', compact('card', 'reward', 'balance', 'claimRewardUrl')) : view('member.card.reward-404');
    }

    /**
     * Associate the authenticated member with a specified card.
     *
     * @param  string  $locale  The locale code
     * @param  string  $card_id  The ID of the card to be followed
     * @param  Request  $request  The current HTTP request instance
     * @param  CardService  $cardService  The service handling card operations
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function follow(string $locale, string $card_id, Request $request, CardService $cardService)
    {
        // If the member is not authenticated, store pending action and redirect to login
        if (! auth('member')->check()) {
            // Store pending action - will be executed after login
            $pendingActionService = resolve(\App\Services\Member\PendingCardActionService::class);
            $pendingActionService->store('card', $card_id);

            // Set redirect target to My Cards (action will add the card automatically)
            session()->put('from.member', route('member.cards'));

            return redirect()->route('member.login');
        }

        // Retrieve the active card with the given id
        $card = $cardService->findActiveCard($card_id);

        // If the card does not exist or is not active, show a 404 page
        if ($card === null) {
            return view('member.card.card-404');
        }

        // Follow the card and redirect to My Cards page with a success toast
        $cardService->followCard($card);

        return redirect()
            ->route('member.cards')
            ->with('toast', [
                'type' => 'success',
                'text' => trans('common.card_added'),
            ]);
    }

    /**
     * Disassociate the authenticated member from a specified card.
     *
     * @param  string  $locale  The locale code
     * @param  string  $card_id  The ID of the card to be unfollowed
     * @param  Request  $request  The current HTTP request instance
     * @param  CardService  $cardService  The service handling card operations
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function unfollow(string $locale, string $card_id, Request $request, CardService $cardService)
    {
        // If the member is not authenticated, store the current URL and redirect to the login page
        if (! auth('member')->check()) {
            session()->put('from.member', url()->current());

            return redirect()->route('member.login');
        }

        // Retrieve the active card with the given id
        $card = $cardService->findActiveCard($card_id);

        // If the card does not exist or is not active, show a 404 page
        if ($card === null) {
            return view('member.card.card-404');
        }

        // Unfollow the card and redirect to the card page with a success toast
        $cardService->unfollowCard($card);

        return redirect()
            ->route('member.card', ['card_id' => $card->id])
            ->with('toast', [
                'type' => 'success',
                'text' => trans('common.card_removed'),
            ]);
    }
	
	/**
	 * English comment: Show all available tiers for a specific club so the member can choose.
	 */
	public function browseTiers(string $locale, string $club_id)
	{
		$club = \App\Models\Club::findOrFail($club_id);
		$tiers = \App\Models\Tier::where('club_id', $club->id)
								 ->where('is_active', true)
								 ->orderBy('level', 'asc')
								 ->get();

		return view('member.tiers.browse', compact('club', 'tiers'));
	}

	/**
	 * English comment: Show all available clubs/cards in the system for the member to explore.
	 */
	public function exploreClubs()
	{
		$tiers = \App\Models\Tier::where('is_active', true)
        ->with('club')
        ->orderBy('points_threshold', 'asc')
        ->get();

    return view('member.clubs.explore', compact('tiers'));
	}
	
	/**
	 * Handle the membership tier application.
	 * English comments only as requested.
	 */
	public function applyForTier(Request $request)
	{
		$tier_id = $request->route('tier_id');
		$member = auth('member')->user();

		// 1. هات الـ Tier والـ Master Card
		$tier = \DB::table('tiers')->where('id', $tier_id)->first();
		if (!$tier) return redirect()->back()->with('error', 'Tier not found.');

		$masterCard = \DB::table('cards')
			->where('club_id', $tier->club_id)
			->whereNull('parent_card_id') // نضمن إنه الكارت الأصلي
			->first();

		if (!$masterCard) {
			return redirect()->back()->with('error', 'Master card not found.');
		}

		try {
			\DB::beginTransaction();
			$newCardUuid = (string) \Str::uuid();

			// 2. إنشاء نسخة العضو وربطها بالـ parent_card_id
			\DB::table('cards')->insert([
				'id' => $newCardUuid,
				'name' => $tier->name,
				'club_id' => $tier->club_id,
				'parent_card_id' => $masterCard->id, // <--- التخزين هنا
				'unique_identifier' => strtoupper(uniqid('CRD-')),
				'is_active' => false,
				'created_at' => now(),
				'updated_at' => now(),
			]);

			// 3. الربط في جدول card_member
			\DB::table('card_member')->insert([
				'card_id'    => $newCardUuid,
				'member_id'  => $member->id,
				'tier_id'  => $tier_id,
				'club_id' => $tier->club_id,
				'created_at' => now(),
				'updated_at' => now(),
			]);

			\DB::commit();
			// English: Redirect to dashboard with a clear success message.
			$this->showCheckout($tier_id);
		   // return redirect()->route('member.dashboard')
			 //   ->with('success', 'Application sent! Waiting for approval.');

		} catch (\Exception $e) {
			\DB::rollback();
			\Log::error("Final Link Error: " . $e->getMessage());
			return redirect()->back()->with('error', 'Database error: ' . $e->getMessage());
		}
	}

public function showCheckout($tierId) 
{
    // 1. جلب بيانات الميمبر الحالي
    $member = auth()->user();

    // 2. جلب بيانات التير (الكارت) اللي العميل اختاره
    $tier = DB::table('tiers')->where('id', $tierId)->first();

    if ($tier) {
        // 3. جلب بيانات البنك (نفس طريقتك القديمة)
        $bankDetails = $this->getBankDetailsByMethod('bank_transfer');

        // 4. تحديد اللغة والعملة (من الداتابيز أو الكونفيج)
        $locale = str_replace('_', '-', strtolower(app()->getLocale()));
        
        $viewData = [
            'member_name'      => $member->name,
            'card_title'       => $tier->name ?? 'Premium Card',
            'amount'           => $tier->price ?? 0, // الـ 700 جنيه
            'currency'         => $tier->currency ?? 'EGP',
            'payment_method'   => 'bank_transfer',
            'bank_details'     => $bankDetails,
            'admin_note'       => 'Please upload the payment receipt to proceed.',
            'confirmation_url' => url($locale . '/confirm/' . $tierId),
            'request_id'       => substr($tier->id, 0, 8),
            'tier_id'          => $tier->id,
            'data'             => $member 
        ];
		
die(view('member.payment_request', $viewData)->render());
    }

    return back()->with('error', 'عفواً، لم يتم العثور على بيانات الكارت');
}
/**
 * Helper to return instructions based on payment method
 */
private function getBankDetailsByMethod($method) 
{
	$methods = [
		'bank_transfer' => 'IBAN: 6433172158202001013 ',
		'cash'          => 'Visit our main branch for cash payment',
		'online'        => 'Follow the link below for credit card payment',
	];
	
	return $methods[$method] ?? 'Please contact administration for payment info';
}
/**
 * Fetch payment proof details for the admin review modal.
 */
}
