<?php

namespace App\Controllers;

use App\Models\ActivityModel;

class ActivityController extends BaseController
{
    protected $activityModel;

    public function __construct()
    {
        $this->activityModel = new ActivityModel();
    }

    /**
     * List activities with search, filter, and pagination
     */
    public function index()
    {
        $request = $this->request;
        
        // Get query parameters
        $search   = $request->getGet('q');
        $category = $request->getGet('category');
        $page     = (int) ($request->getGet('page') ?? 1);

        // Get activities with pagination
        $activities = $this->activityModel->getPublishedActivities($search, $category, 6);
        
        // Parse tags for each activity
        foreach ($activities as &$activity) {
            $activity['tags_array'] = json_decode($activity['tags'] ?? '[]', true) ?? [];
        }

        // Get categories for filter dropdown
        $categories = $this->activityModel->getCategories();

        $data = [
            'title'      => 'Aktivitas',
            'activities' => $activities,
            'pager'      => $this->activityModel->pager,
            'categories' => $categories,
            'search'     => $search,
            'category'   => $category,
            'total'      => $this->activityModel->where('status', 'published')->countAllResults(false),
        ];

        return view('activities/index', $data);
    }

    /**
     * Show single activity by slug
     */
    public function show(string $slug)
    {
        $activity = $this->activityModel->findBySlug($slug);

        if (!$activity || $activity['status'] !== 'published') {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Aktivitas tidak ditemukan');
        }

        // Get related activities (same category, exclude current)
        $relatedActivities = $this->activityModel
            ->where('category', $activity['category'])
            ->where('id !=', $activity['id'])
            ->where('status', 'published')
            ->orderBy('activity_date', 'DESC')
            ->limit(3)
            ->findAll();

        foreach ($relatedActivities as &$related) {
            $related['tags_array'] = json_decode($related['tags'] ?? '[]', true) ?? [];
        }

        $data = [
            'title'             => $activity['title'],
            'activity'          => $activity,
            'relatedActivities' => $relatedActivities,
        ];

        return view('activities/show', $data);
    }
}
