<?php

namespace App\Models;

use CodeIgniter\Model;

class ActivityModel extends Model
{
    protected $table            = 'activities';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'title', 'slug', 'description', 'category', 'tags',
        'activity_date', 'status', 'cover_image'
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation
    protected $validationRules = [
        'title'         => 'required|min_length[3]|max_length[200]',
        'slug'          => 'required|is_unique[activities.slug,id,{id}]',
        'category'      => 'required|in_list[Project,Campus,Freelance]',
        'activity_date' => 'permit_empty|valid_date[Y-m-d]',
        'status'        => 'required|in_list[draft,published]',
    ];

    protected $validationMessages = [
        'slug' => [
            'is_unique' => 'Slug sudah digunakan, pilih judul lain.',
        ],
    ];

    protected $skipValidation = false;

    // Callbacks
    protected $beforeInsert = ['generateSlug'];
    protected $beforeUpdate = ['generateSlug'];

    /**
     * Generate slug from title
     */
    protected function generateSlug(array $data): array
    {
        if (isset($data['data']['title']) && empty($data['data']['slug'])) {
            $data['data']['slug'] = url_title($data['data']['title'], '-', true);
        }
        return $data;
    }

    /**
     * Get published activities with search, filter, and pagination
     */
    public function getPublishedActivities(?string $search = null, ?string $category = null, int $perPage = 6)
    {
        $builder = $this->where('status', 'published');

        if (!empty($search)) {
            $builder->groupStart()
                    ->like('title', $search)
                    ->orLike('description', $search)
                    ->orLike('tags', $search)
                    ->groupEnd();
        }

        if (!empty($category)) {
            $builder->where('category', $category);
        }

        return $builder->orderBy('activity_date', 'DESC')
                       ->paginate($perPage);
    }

    /**
     * Get activities for admin with search, filter, and pagination
     */
    public function getAdminActivities(?string $search = null, ?string $status = null, ?string $category = null, string $sort = 'latest', int $perPage = 10)
    {
        $builder = $this;

        if (!empty($search)) {
            $builder->groupStart()
                    ->like('title', $search)
                    ->orLike('description', $search)
                    ->groupEnd();
        }

        if (!empty($status)) {
            $builder->where('status', $status);
        }

        if (!empty($category)) {
            $builder->where('category', $category);
        }

        // Sorting
        switch ($sort) {
            case 'title_asc':
                $builder->orderBy('title', 'ASC');
                break;
            case 'oldest':
                $builder->orderBy('activity_date', 'ASC');
                break;
            default: // latest
                $builder->orderBy('activity_date', 'DESC');
        }

        return $builder->paginate($perPage);
    }

    /**
     * Find by slug
     */
    public function findBySlug(string $slug): ?array
    {
        $activity = $this->where('slug', $slug)->first();
        
        if ($activity && !empty($activity['tags'])) {
            $activity['tags_array'] = json_decode($activity['tags'], true) ?? [];
        } else {
            $activity['tags_array'] = [];
        }
        
        return $activity;
    }

    /**
     * Get distinct categories
     */
    public function getCategories(): array
    {
        return $this->distinct()
                    ->select('category')
                    ->findAll();
    }

    /**
     * Count by status
     */
    public function countByStatus(string $status): int
    {
        return $this->where('status', $status)->countAllResults();
    }
}
