<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use App\Models\Poster;
use App\Models\Video;
use App\Models\QuizQuestion;

class PublicController extends Controller
{
    public function home()
    {
        $latestArticles = Article::latest()->take(3)->get();
        $latestPosters = Poster::latest()->take(3)->get();
        $latestVideos = Video::latest()->take(3)->get();

        return view('home', compact('latestArticles', 'latestPosters', 'latestVideos'));
    }

    public function jenisSampah()
    {
        return view('jenis-sampah');
    }

    public function caraMemilah()
    {
        return view('cara-memilah');
    }

    public function konsep3R()
    {
        return view('konsep-3r');
    }

    public function jadwalLokasi()
    {
        // Realistic weekly pickup schedule for Desa Lengkong Subang
        $jadwal = [
            [
                'hari' => 'Senin',
                'waktu' => 'Pagi',
                'wilayah' => 'Pinggir Jalan Raya (Arah Timur)',
                'icon' => '🌅'
            ],
            [
                'hari' => 'Senin',
                'waktu' => 'Sore',
                'wilayah' => 'Pinggir Jalan Raya (Arah Barat)',
                'icon' => '🌇'
            ],
            [
                'hari' => 'Selasa',
                'waktu' => 'Pagi',
                'wilayah' => 'Lingkungan RW 05',
                'icon' => '🌅'
            ],
            [
                'hari' => 'Selasa',
                'waktu' => 'Sore',
                'wilayah' => 'Lingkungan RW 01',
                'icon' => '🌇'
            ],
            [
                'hari' => 'Rabu',
                'waktu' => 'Pagi',
                'wilayah' => 'Lingkungan RW 04',
                'icon' => '🌅'
            ],
            [
                'hari' => 'Rabu',
                'waktu' => 'Sore',
                'wilayah' => 'Lingkungan RW 02',
                'icon' => '🌇'
            ],
            [
                'hari' => 'Kamis',
                'waktu' => 'Sapu Bersih',
                'wilayah' => 'Sapu bersih mengambil sampah yang belum terangkut sebelumnya karena keburu penuh',
                'icon' => '🧹'
            ]
        ];

        $tps = [
            'nama' => 'TPS Dusun Cijoged',
            'alamat' => 'Dusun Cijoged RT 02 RW 01, Desa Lengkong, Kec. Cipeundeuy, Kab. Subang, Jawa Barat 41272',
            'jam' => '07.00 - 17.00 WIB',
            'keterangan' => 'Tempat pembuangan sampah sementara warga Desa Lengkong. Dikelola secara rutin.',
            'google_maps_url' => 'https://www.google.com/maps/search/?api=1&query=Dusun+cijoged+Rt+02+Rw+01+Desa+lengkong+Kec+Cipeundeuy+Kab+Subang+41272'
        ];
        
        return view('jadwal-lokasi', compact('jadwal', 'tps'));
    }

    public function articles()
    {
        $articles = Article::latest()->paginate(6);
        return view('articles.index', compact('articles'));
    }

    public function showArticle($slug)
    {
        $article = Article::where('slug', $slug)->firstOrFail();
        $relatedArticles = Article::where('id', '!=', $article->id)->take(3)->get();
        return view('articles.show', compact('article', 'relatedArticles'));
    }

    public function posters()
    {
        $posters = Poster::latest()->paginate(6);
        return view('posters.index', compact('posters'));
    }

    public function downloadPoster($id)
    {
        $poster = Poster::findOrFail($id);
        $poster->increment('download_count');
        
        $imageUrl = $poster->preview_image;

        if (empty($imageUrl)) {
            $imageUrl = 'https://images.unsplash.com/photo-1530587191325-3db32d826c18?w=800&auto=format&fit=crop&q=60';
        }

        try {
            if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
                $response = \Illuminate\Support\Facades\Http::timeout(10)->get($imageUrl);
                if ($response->successful()) {
                    $imageContent = $response->body();
                    $contentType = $response->header('Content-Type') ?? 'image/png';
                    
                    // Determine extension based on Content-Type
                    $extension = 'png';
                    if (str_contains($contentType, 'jpeg') || str_contains($contentType, 'jpg')) {
                        $extension = 'jpg';
                    } elseif (str_contains($contentType, 'webp')) {
                        $extension = 'webp';
                    }

                    $filename = \Illuminate\Support\Str::slug($poster->title) . '.' . $extension;

                    return response()->streamDownload(function () use ($imageContent) {
                        echo $imageContent;
                    }, $filename, [
                        'Content-Type' => $contentType,
                    ]);
                }
            } else {
                // If it's a local file path
                if (file_exists(public_path($imageUrl))) {
                    return response()->download(public_path($imageUrl));
                }
                if (file_exists(public_path('storage/' . $imageUrl))) {
                    return response()->download(public_path('storage/' . $imageUrl));
                }
            }
        } catch (\Exception $e) {
            // Silently swallow and proceed to fallback redirect
        }

        // Fallback: redirect directly to image
        return redirect()->away($imageUrl);
    }

    public function videos()
    {
        $videos = Video::latest()->paginate(6);
        return view('videos.index', compact('videos'));
    }

    public function quiz()
    {
        // Get all questions grouped by level 1-5
        $questionsByLevel = [];
        for ($i = 1; $i <= 5; $i++) {
            $questionsByLevel[$i] = QuizQuestion::where('level', $i)->get();
        }

        return view('quiz.index', compact('questionsByLevel'));
    }

    public function submitScore(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'class' => 'required|string|max:100',
            'score' => 'required|integer|min:0',
        ]);

        $studentScore = \App\Models\StudentScore::firstOrNew([
            'name' => $validated['name'],
            'class' => $validated['class']
        ]);

        if ($validated['score'] > ($studentScore->score ?? 0) || !$studentScore->exists) {
            $studentScore->score = $validated['score'];
            $studentScore->save();
        }

        return response()->json([
            'success' => true,
            'message' => 'Score updated successfully!',
            'data' => $studentScore
        ]);
    }

    public function leaderboard()
    {
        $leaderboard = \App\Models\StudentScore::orderBy('score', 'desc')
            ->orderBy('updated_at', 'asc')
            ->take(10)
            ->get();

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