<?php

namespace App\Http\Controllers;

use App\Models\News;
use App\Models\NewsCategory;
use App\Models\Event;
use App\Models\Referee;
use App\Models\Coach;
use App\Models\Album;
use App\Models\GalleryItem;
use App\Models\Achievement;
use App\Models\Document;
use App\Models\District;
use App\Models\Club;
use App\Models\Member;
use App\Models\ActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FrontendController extends Controller
{
    public function home()
    {
        $featuredNews = News::where('status', 'published')
            ->where('is_featured', true)
            ->latest()
            ->take(3)
            ->get();

        $latestNews = News::where('status', 'published')
            ->where('is_featured', false)
            ->latest()
            ->take(3)
            ->get();

        $upcomingEvents = Event::where('start_date', '>=', now())
            ->orderBy('start_date', 'asc')
            ->take(3)
            ->get();

        $referees = Referee::where('status', 'active')->take(4)->get();
        $coaches = Coach::where('status', 'active')->take(4)->get();
        
        $recentPhotos = GalleryItem::where('type', 'image')
            ->latest()
            ->take(8)
            ->get();

        $districts = District::all();

        // Counters (DB counts + Admin settings offsets)
        $membersOffset = (int) (\App\Models\Setting::where('key', 'stats_members_offset')->value('value') ?? 140);
        $clubsOffset = (int) (\App\Models\Setting::where('key', 'stats_clubs_offset')->value('value') ?? 0);
        $coachesOffset = (int) (\App\Models\Setting::where('key', 'stats_coaches_offset')->value('value') ?? 0);
        $refereesOffset = (int) (\App\Models\Setting::where('key', 'stats_referees_offset')->value('value') ?? 0);
        $goldOffset = (int) (\App\Models\Setting::where('key', 'stats_gold_offset')->value('value') ?? 12);
        $silverOffset = (int) (\App\Models\Setting::where('key', 'stats_silver_offset')->value('value') ?? 18);
        $bronzeOffset = (int) (\App\Models\Setting::where('key', 'stats_bronze_offset')->value('value') ?? 25);
        $districtsOffset = (int) (\App\Models\Setting::where('key', 'stats_districts_offset')->value('value') ?? 0);

        $counters = [
            'members'   => Member::where('status', 'active')->count() + $membersOffset,
            'clubs'     => Club::count() + $clubsOffset,
            'coaches'   => Coach::where('status', 'active')->count() + $coachesOffset,
            'referees'  => Referee::where('status', 'active')->count() + $refereesOffset,
            'gold'      => Achievement::where('medal_type', 'gold')->count() + $goldOffset,
            'silver'    => Achievement::where('medal_type', 'silver')->count() + $silverOffset,
            'bronze'    => Achievement::where('medal_type', 'bronze')->count() + $bronzeOffset,
            'districts' => District::count() + $districtsOffset,
        ];

        return view('home', compact('featuredNews', 'latestNews', 'upcomingEvents', 'referees', 'coaches', 'recentPhotos', 'counters', 'districts'));
    }

    public function about()
    {
        // Static Executive Committee list for high-fidelity rendering
        $committee = [
            ['role' => 'President', 'name' => 'Milan Shrestha', 'dan' => '5th Dan Black Belt', 'photo' => null],
            ['role' => 'Vice President', 'name' => 'Devendra Bahadur Singh', 'dan' => '4th Dan Black Belt', 'photo' => null],
            ['role' => 'Secretary', 'name' => 'Ramesh Bhandari', 'dan' => '3rd Dan Black Belt', 'photo' => null],
            ['role' => 'Treasurer', 'name' => 'Rina Thapa', 'dan' => '3rd Dan Black Belt', 'photo' => null],
            ['role' => 'Executive Member', 'name' => 'Kabita Rana', 'dan' => '3rd Dan Black Belt', 'photo' => null],
            ['role' => 'Executive Member', 'name' => 'Janak Oli', 'dan' => '3rd Dan Black Belt', 'photo' => null],
        ];

        return view('about', compact('committee'));
    }

    public function news(Request $request)
    {
        $query = News::where('status', 'published');

        if ($request->has('search') && !empty($request->search)) {
            $query->where('title', 'like', '%' . $request->search . '%')
                  ->orWhere('content', 'like', '%' . $request->search . '%');
        }

        if ($request->has('category') && !empty($request->category)) {
            $category = NewsCategory::where('slug', $request->category)->first();
            if ($category) {
                $query->where('category_id', $category->id);
            }
        }

        $newsList = $query->latest()->paginate(6);
        $categories = NewsCategory::withCount('news')->get();

        return view('news.index', compact('newsList', 'categories'));
    }

    public function newsShow($slug)
    {
        $news = News::where('slug', $slug)->firstOrFail();
        $news->increment('views');

        $relatedNews = News::where('status', 'published')
            ->where('category_id', $news->category_id)
            ->where('id', '!=', $news->id)
            ->latest()
            ->take(3)
            ->get();

        return view('news.show', compact('news', 'relatedNews'));
    }

    public function referees()
    {
        $referees = Referee::where('status', 'active')->get();
        return view('referees', compact('referees'));
    }

    public function coaches()
    {
        $coaches = Coach::with('club')->where('status', 'active')->get();
        return view('coaches', compact('coaches'));
    }

    public function events()
    {
        $upcomingEvents = Event::where('start_date', '>=', now())
            ->orderBy('start_date', 'asc')
            ->get();

        $pastEvents = Event::where('start_date', '<', now())
            ->orderBy('start_date', 'desc')
            ->get();

        return view('events', compact('upcomingEvents', 'pastEvents'));
    }

    public function gallery()
    {
        $albums = Album::with('items')->latest()->get();
        return view('gallery', compact('albums'));
    }

    public function achievements()
    {
        $achievements = Achievement::orderBy('achievement_date', 'desc')->get();
        
        $counts = [
            'gold' => Achievement::where('medal_type', 'gold')->count(),
            'silver' => Achievement::where('medal_type', 'silver')->count(),
            'bronze' => Achievement::where('medal_type', 'bronze')->count(),
        ];

        return view('achievements', compact('achievements', 'counts'));
    }

    public function achievementShow(Achievement $achievement)
    {
        $related = Achievement::where('id', '!=', $achievement->id)
            ->where(function($q) use ($achievement) {
                $q->where('player_name', $achievement->player_name)
                  ->orWhere('type', $achievement->type);
            })
            ->orderBy('achievement_date', 'desc')
            ->take(3)
            ->get();

        return view('achievement-detail', compact('achievement', 'related'));
    }

    public function downloads()
    {
        $documents = Document::latest()->get();
        return view('downloads', compact('documents'));
    }

    public function contact()
    {
        return view('contact');
    }

    public function contactSubmit(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email',
            'subject' => 'required|string|max:255',
            'message' => 'required|string|max:1000',
        ]);

        // Save contact message details to activity logs as guest contact
        ActivityLog::create([
            'user_id' => null,
            'action' => 'contact_message',
            'details' => "Message from: {$request->name} ({$request->email}). Subject: {$request->subject}. Content: {$request->message}",
            'ip_address' => $request->ip()
        ]);

        if ($request->ajax()) {
            return response()->json(['success' => 'Thank you! Your message has been sent successfully. We will get back to you soon.']);
        }

        return back()->with('success', 'Thank you! Your message has been sent successfully.');
    }

    public function verifyMember($member_id)
    {
        $member = Member::with(['district', 'club'])->where('member_id', $member_id)->first();
        return view('verify', compact('member', 'member_id'));
    }

    public function tree()
    {
        // Fetch hierarchical data
        $districts = District::with(['clubs.coaches', 'clubs.members' => function($q) {
            $q->where('status', 'active');
        }])->get();

        return view('tree', compact('districts'));
    }

    public function searchTree(Request $request)
    {
        $query = $request->get('query');
        if (empty($query)) {
            return response()->json([]);
        }

        $members = Member::with(['district', 'club'])
            ->where('status', 'active')
            ->where(function($q) use ($query) {
                $q->where('first_name', 'like', "%{$query}%")
                  ->orWhere('last_name', 'like', "%{$query}%")
                  ->orWhere('member_id', 'like', "%{$query}%")
                  ->orWhere('belt_rank', 'like', "%{$query}%");
            })
            ->take(10)
            ->get()
            ->map(function($m) {
                return [
                    'id' => $m->id,
                    'member_id' => $m->member_id,
                    'name' => $m->full_name,
                    'belt' => $m->belt_rank,
                    'district' => $m->district->name,
                    'club' => $m->club ? $m->club->name : 'N/A',
                    'photo' => $m->photo ? asset($m->photo) : asset('images/default-avatar.png')
                ];
            });

        return response()->json($members);
    }
}
