<?php

namespace App\Http\Controllers;

use App\Models\Activity;
use App\Models\ContactMessage;
use App\Models\Division;
use App\Models\Post;
use App\Models\User;

class PublicController extends Controller
{
    public function home()
    {
        return view('public.home', [
            'totalAnggota'  => User::where('status', 'aktif')->count(),
            'totalDivisi'   => Division::count(),
            'totalKegiatan' => Activity::where('status', 'approved')->whereNotNull('executed_at')->count(),
            'divisi'        => Division::withCount('members')->get(),
            'kegiatan'      => Activity::where('status', 'approved')->latest('start_date')->take(3)->get(),
            'posts'         => Post::published()->latest('published_at')->take(2)->get(),
        ]);
    }

    public function tentang()
    {
        return view('public.tentang', [
            'divisi' => Division::withCount('members')->get(),
        ]);
    }

    public function kegiatan()
    {
        return view('public.kegiatan', [
            'kegiatan' => Activity::where('status', 'approved')
                ->latest('start_date')->paginate(9),
        ]);
    }

    public function kegiatanDetail(Activity $activity)
    {
        abort_if($activity->status !== 'approved', 404);

        return view('public.kegiatan-detail', compact('activity'));
    }

    public function blog()
    {
        return view('public.blog', [
            'posts' => Post::published()->with('author')->latest('published_at')->paginate(9),
        ]);
    }

    public function blogDetail(Post $post)
    {
        abort_if($post->status !== 'published' || ! $post->published_at, 404);

        return view('public.blog-detail', compact('post'));
    }

    public function kontak()
    {
        return view('public.kontak');
    }

    public function kontakStore(\Illuminate\Http\Request $request)
    {
        $data = $request->validate([
            'name'    => 'required|string|max:100',
            'email'   => 'nullable|email|max:100',
            'phone'   => 'nullable|string|max:20',
            'subject' => 'required|string|max:150',
            'message' => 'required|string|max:2000',
        ]);

        ContactMessage::create($data);

        return back()->with('success', 'Pesan Anda berhasil dikirim. Kami akan segera menghubungi Anda.');
    }
}
