<?php

declare(strict_types=1);

/**
 * Reward Loyalty - Proprietary Software
 * Copyright (c) 2025 NowSquare. All rights reserved.
 * See LICENSE file for terms.
 */

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Models\Card;
use App\Models\Category;
use App\Models\Partner;
use App\Models\Page;
use App\Models\StampCard;
use App\Models\Voucher;
use App\Services\Card\CardService;
use App\Services\MarkdownService;
use App\Services\SettingsService;
use App\Services\TierService;
use Illuminate\Http\Request;

class PageController extends Controller
{
    /**
     * Handle the incoming request and display the home page.
     *
     * Homepage = Pure Discovery
     * Shows all publicly available programs to everyone (guests and logged-in members).
     * Sorted by urgency (ending soon) → freshness (newest) to maximize engagement.
     *
     * For personalized card management, members use the "My Cards" page.
     *
     * @return \Illuminate\View\View
     */
    public function index(string $locale, Request $request)
    {
        // ═════════════════════════════════════════════════════════════════════
        // LOYALTY CARDS
        // Discovery: Show all public, active, non-expired cards
        // Sort: Expiring soon → Newest → Evergreen
        // ═════════════════════════════════════════════════════════════════════

        $partners = \App\Models\Partner::where('is_active', true)->get();
		$member = auth()->guard('member')->user();
		if($member){
		$cards = \DB::table('cards')
        ->join('card_member', 'cards.id', '=', 'card_member.card_id')
        ->leftJoin('cards as parent_cards', 'cards.parent_card_id', '=', 'parent_cards.id')
        ->where('card_member.member_id', $member->id)
        ->select(
            'cards.*', 
            'parent_cards.name as master_card_name',
            'card_member.created_at as joined_at'
        )
        ->get();
		}

        // ═════════════════════════════════════════════════════════════════════
        // VOUCHERS
        // Discovery: Show all public, active, valid, non-batch vouchers
        // Sort: Expiring soon → Newest → Evergreen
        // ═════════════════════════════════════════════════════════════════════

        $vouchers = Voucher::where('is_active', true)
            ->where('is_visible_by_default', true)
            ->whereNull('batch_id') // Exclude batch-generated vouchers
            ->where(function ($query) {
                // Voucher must be valid (started, not future-dated)
                $query->whereNull('valid_from')
                    ->orWhere('valid_from', '<=', now());
            })
            ->where(function ($query) {
                // Voucher must not be expired (or no expiration set)
                $query->whereNull('valid_until')
                    ->orWhere('valid_until', '>', now());
            })
            ->whereHas('creator', function ($query) {
                $query->where('is_active', true)
                    ->where(function ($q) {
                        $q->whereNull('network_id')
                            ->orWhereHas('network', fn ($nq) => $nq->where('is_active', true));
                    });
            })
            ->with(['club'])
            ->orderByRaw('
                CASE 
                    WHEN valid_until IS NULL THEN 1 
                    ELSE 0 
                END ASC
            ') // Non-expiring vouchers last
            ->orderBy('valid_until', 'asc') // Expiring soon first (urgency)
            ->orderBy('created_at', 'desc') // Then newest (freshness)
            ->limit(100)
            ->get();

        // ═════════════════════════════════════════════════════════════════════
        // STAMP CARDS
        // Discovery: Show all public, active, valid stamp cards
        // Sort: Expiring soon → Newest → Evergreen
        // ═════════════════════════════════════════════════════════════════════

        $stampCards = StampCard::where('is_active', true)
            ->where('is_visible_by_default', true)
            ->where(function ($query) {
                // Stamp card must be valid (started, not future-dated)
                $query->whereNull('valid_from')
                    ->orWhere('valid_from', '<=', now());
            })
            ->where(function ($query) {
                // Stamp card must not be expired (or no expiration set)
                $query->whereNull('valid_until')
                    ->orWhere('valid_until', '>', now());
            })
            ->whereHas('partner', function ($query) {
                $query->where('is_active', true)
                    ->where(function ($q) {
                        $q->whereNull('network_id')
                            ->orWhereHas('network', fn ($nq) => $nq->where('is_active', true));
                    });
            })
            ->with(['club', 'partner'])
            ->orderByRaw('
                CASE 
                    WHEN valid_until IS NULL THEN 1 
                    ELSE 0 
                END ASC
            ') // Non-expiring cards last
            ->orderBy('valid_until', 'asc') // Expiring soon first (urgency)
            ->orderBy('created_at', 'desc') // Then newest (freshness)
            ->limit(100)
            ->get();

        // ═════════════════════════════════════════════════════════════════════
        // LAYOUT SELECTION
        // Check the configured homepage layout and return the appropriate view.
        // - 'directory': Full catalog of all programs (default)
        // - 'showcase': Editorial single-business presentation
        // - 'portal': Minimal authentication-focused landing
        // ═════════════════════════════════════════════════════════════════════

        $homepageLayout = config('default.homepage_layout', 'directory');

        // Check for database-stored setting (overrides config)
        $layoutSetting = \App\Models\Setting::where('key', 'homepage_layout')->first();
        if ($layoutSetting && $layoutSetting->value) {
            $homepageLayout = $layoutSetting->value;
        }
		$member = auth()->user();

        // Route to appropriate view based on layout
        switch ($homepageLayout) {
            case 'showcase':
                // Get showcase-specific settings
                $showHowItWorks = config('default.homepage_show_how_it_works', true);
                $showTiers = config('default.homepage_show_tiers', true);
                $showMemberCount = config('default.homepage_show_member_count', false);
                
                // Check database overrides
                $howItWorksSetting = \App\Models\Setting::where('key', 'homepage_show_how_it_works')->first();
                if ($howItWorksSetting !== null) {
                    $showHowItWorks = (bool) $howItWorksSetting->value;
                }
                $tiersSetting = \App\Models\Setting::where('key', 'homepage_show_tiers')->first();
                if ($tiersSetting !== null) {
                    $showTiers = (bool) $tiersSetting->value;
                }
                $memberCountSetting = \App\Models\Setting::where('key', 'homepage_show_member_count')->first();
                if ($memberCountSetting !== null) {
                    $showMemberCount = (bool) $memberCountSetting->value;
                }

                // Get hero background image if available
                $heroImageUrl = $layoutSetting?->getFirstMediaUrl('homepage_hero_image');

                // Get member count if enabled
                $memberCount = $showMemberCount ? \App\Models\Member::count() : 0;

                return view('member.home-showcase', compact(
                    'cards', 'vouchers', 'stampCards', 'partners',
                    'showHowItWorks', 'showTiers', 'showMemberCount',
                    'heroImageUrl', 'memberCount'
                ));

            case 'portal':
                return view('member.home-portal', compact('partners'));

            case 'directory':
            default:
                // Pass all programs to the view (original behavior)
                return view('member.home', compact('cards', 'vouchers', 'stampCards','member','partners'));
        }
    }

    /**
     * Handle the incoming request and display the unified My Cards page.
     *
     * Consolidates the old dashboard + wallet into one consumer-grade experience.
     * Provides sorting, filtering, and complete card management in one place.
     *
     * @return \Illuminate\Http\Response
     */
    public function dashboard(string $locale, Request $request, CardService $cardService, TierService $tierService, SettingsService $settingsService)
{
    // 1. Define allowed sort values
    $allowedSortValues = [
        'last_points_claimed_at,desc', 'last_points_claimed_at,asc',
        'total_amount_purchased,desc', 'total_amount_purchased,asc',
        'number_of_rewards_claimed,desc', 'number_of_rewards_claimed,asc',
        'last_reward_claimed_at,desc', 'last_reward_claimed_at,asc',
    ];

    // 2. Extract parameters
    $sort = $request->query('sort', $request->cookie('wallet_sort', 'last_points_claimed_at,desc'));
    $hide_expired = $request->query('hide_expired', $request->cookie('wallet_hide_expired', 'true'));

    if (!in_array($sort, $allowedSortValues)) $sort = 'last_points_claimed_at,desc';
    if (!in_array($hide_expired, ['true', 'false'])) $hide_expired = 'true';

    $memberTiers = collect();
    $cards = collect();

    if (auth('member')->check()) {
        $member = auth('member')->user();
        $memberId = $member->id;

        /**
         * English: We fetch cards directly from the DB to include BOTH 
         * active and pending cards (is_active = 0) created via applyForTier.
         */
        $cards = \App\Models\Card::whereHas('members', function($q) use ($memberId) {
                $q->where('member_id', $memberId);
            })
            ->with(['club', 'partner'])
            ->get();

        // 3. Pre-calculate balances for active cards
        $cardIds = $cards->pluck('id');
        $balances = \App\Models\Transaction::whereIn('card_id', $cardIds)
            ->where('member_id', $memberId)
            //->where('expires_at', '>', now())
            ->selectRaw('card_id, (SUM(points) - SUM(points_used)) as balance')
            ->groupBy('card_id')
            ->pluck('balance', 'card_id');
        // 4. Sort cards by balance
        $cards = $cards->sortByDesc(function ($card) use ($balances) {
            return $balances[$card->id] ?? 0;
			
        });
		foreach ($cards as $card) {
			// 2. ضيف خاصية جديدة اسمها points لكل كارت
			// بنجيب القيمة من مصفوفة الـ balances بناءً على ID الكارت
			$card->points = $balances[$card->id] ?? 0;
			$cardMember = \DB::table('card_member')->where('card_id', $card->id)->first();
			$card->tier = \App\Models\Tier::where('club_id', $card->club_id)->first();
			 if ($cardMember && $cardMember->tier_id) {
        // 3. نجيب التير الصح المربوط بالكارت ده بالملي
        $card->tier = \App\Models\Tier::find($cardMember->tier_id);
    
                $card->head = $card->tier->getTranslation('display_name', app()->getLocale());
			$card->color = $card->tier->color;}
		}

           
		
		

        // 5. Fetch Tier Data (Standard logic remains same)
        if ($settingsService->get('tiers.enabled', true)) {
            $clubIds = $cards->pluck('club_id')->unique();
            foreach ($clubIds as $clubId) {
                $club = \App\Models\Club::find($clubId);
                if ($club) {
                    $memberTier = $member->memberTiers()->forClub($club)->active()->with('tier')->first();
                    if ($memberTier) {
                        $qualifyingStats = $tierService->getQualifyingStats($member, $club);
                        $lifetimePoints = $qualifyingStats['lifetime_points'] ?? 0;

                        if ($lifetimePoints > 0) {
                            $nextTier = $memberTier->tier->getNextTier();
                            $progress = $nextTier ? [
                                'points' => [
                                    'current' => $lifetimePoints,
                                    'threshold' => $nextTier->points_threshold,
                                    'percentage' => $nextTier->points_threshold > 0 ? min(100, ($lifetimePoints / $nextTier->points_threshold) * 100) : 100,
                                ],
                            ] : [];

                            $primaryCard = $cards->where('club_id', $clubId)->first();
                            $memberTiers->push([
                                'memberTier' => $memberTier,
                                'club' => $club,
                                'card' => $primaryCard,
                                'progress' => $progress,
                            ]);
                        }
                    }
                }
            }
        }
    }

    // 6. Fetch Vouchers & Stamp Cards (Standard logic)
    $vouchers = collect();
    $stampCards = collect();
    if (auth('member')->check()) {
        $vouchers = $member->vouchers()->where('is_active', true)->with(['club'])->get();
        $stampCards = \App\Models\StampCard::where('is_active', true)
            ->whereHas('enrollments', fn($q) => $q->where('member_id', $memberId)->where('is_active', true))
            ->with(['club', 'partner', 'enrollments' => fn($q) => $q->where('member_id', $memberId)])
            ->get();
    }

    // 7. Dashboard Blocks & Greeting
    $dashboardBlocks = [
        ['link' => route('member.data.list', ['name' => 'account']), 'icon' => 'user-circle', 'title' => trans('common.account_settings'), 'desc' => trans('common.memberDashboardBlocks.account_settings')],
        ['link' => route('member.data.list', ['name' => 'request-links']), 'icon' => 'send', 'title' => trans('common.request_points'), 'desc' => trans('common.memberDashboardBlocks.request_points')],
        ['link' => route('member.code.enter'), 'icon' => 'hash', 'title' => trans('common.enter_code'), 'desc' => trans('common.memberDashboardBlocks.enter_code')],
        ['link' => route('member.referrals'), 'icon' => 'user-plus', 'title' => trans('common.referral.refer_friend'), 'desc' => trans('common.share_love')],
    ];

    $greeting = getGreeting($member?->time_zone);

    // 8. Return Response
    $view = view('member.my-cards', compact('cards', 'sort', 'hide_expired', 'vouchers', 'stampCards', 'dashboardBlocks', 'memberTiers', 'greeting'));
    
    return response($view)
        ->withCookie(cookie('wallet_sort', $sort, 43200))
        ->withCookie(cookie('wallet_hide_expired', $hide_expired, 43200));
}

    /**
     * Handle the incoming request and display a page.
     *
     * @param  string  $page  The markdown file to be displayed.
     * @return \Illuminate\View\View
     */
    private function displayPage(string $locale, Request $request, string $page, MarkdownService $markdownService)
    {
        $dbPage = Page::where('slug', $page)->first();
$cleanLocale = explode('-', $locale)[0];
    if ($dbPage) {
        // لو موجودة في الداتابيز (شغل الـ CKEditor الجديد)
        app()->setLocale($cleanLocale); // تظبيط اللغة
//dd($cleanLocale);
        // سحب العنوان والمحتوى بناءً على اللغة الحالية
        $title = $cleanLocale === 'en' && $dbPage->title_en ? $dbPage->title_en : $dbPage->title_ar;
        $content = $cleanLocale === 'en' && $dbPage->content_en ? $dbPage->content_en : $dbPage->content_ar;

        // تجهيز الـ meta عشان ملف الـ View القديم ميزعلش وميطلعش خطأ Variable undefined
        $meta = [
            'title' => $title,
            'description' => strip_tags(substr($content, 0, 150)) // وصف تلقائي سريع من المحتوى
        ];
    } else {
        // 2. خطة بديلة (Fallback): لو ملهاش داتا في الجدول، شغل السيرفيس القديم بتاعك عل طول
        $data = $markdownService->transWithMeta($page);
        $content = $data['content'];
        $meta = $data['meta'];
    }
	if($page=='contact'){
		return view("member.contact_us", compact('content', 'meta'));
	}elseif($page=='join-our-merchants'){
		return view("member.become_partner", compact('content', 'meta'));
	}else{
        return view("member.content.about", compact('content', 'meta'));
	}
    }

    public function about(string $locale, Request $request, MarkdownService $markdownService)
    {
		
        return $this->displayPage($locale, $request, 'about', $markdownService);
    }
	public function whoitworks(string $locale, Request $request, MarkdownService $markdownService)
    {
		
        return $this->displayPage($locale, $request, 'who-it-works', $markdownService);
    }
	public function getthecard(string $locale, Request $request, MarkdownService $markdownService)
    {
		
        return $this->displayPage($locale, $request, 'get-the-card', $markdownService);
    }
	public function deals(string $locale, Request $request, MarkdownService $markdownService)
    {
		
        return $this->displayPage($locale, $request, 'deals', $markdownService);
    }
	public function joinourmerchants(string $locale, Request $request, MarkdownService $markdownService)
    {
		
        return $this->displayPage($locale, $request, 'join-our-merchants', $markdownService);
    }

    public function contact(string $locale, Request $request, MarkdownService $markdownService)
    {
        return $this->displayPage($locale, $request, 'contact', $markdownService);
    }

    public function faq(string $locale, Request $request)
    {
        return view('member.content.faq');
    }

    public function terms(string $locale, Request $request, MarkdownService $markdownService)
    {
        return $this->displayPage($locale, $request, 'terms', $markdownService);
    }

    public function privacy(string $locale, Request $request, MarkdownService $markdownService)
    {
        return $this->displayPage($locale, $request, 'privacy', $markdownService);
    }
    public function showpartner(string $locale, $partnerId)
    {

		$partnerData = \App\Models\Partner::where('id', $partnerId)->first();

		return view('member.show_partner', compact('partnerData'));
    }
	public function allPartners(Request $request)
	{
		$categories = Category::where('is_active', 1)
        ->whereHas('partners') 
        ->get();

		$query = Partner::query();

		if ($request->filled('category')) {
			$query->where('category_id', $request->input('category'));
		}

		$partners = $query->latest()->paginate(12);

		return view('member.partners', compact('partners', 'categories'));
	}
}
