<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Portfolio_model — campaigns / projects showcase.
 */
#[\AllowDynamicProperties]
class Portfolio_model extends MY_Model {

	protected $table = 'portfolio';
	protected $order_by = 'sort_order ASC, created_at DESC';

	/** Active projects, optionally filtered by category. */
	public function active($category = NULL, $limit = NULL, $offset = 0)
	{
		$where = array('is_active' => 1);
		if ($category) $where['category'] = $category;
		return $this->get_all($where, $limit, $offset);
	}

	/** Featured projects for the homepage preview. */
	public function featured($limit = 6)
	{
		return $this->get_all(array('is_active' => 1, 'is_featured' => 1), $limit);
	}

	/** Fetch a single active project by slug. */
	public function by_slug($slug)
	{
		return $this->get_by(array('slug' => $slug, 'is_active' => 1));
	}

	/** Related projects in the same category, excluding the current one. */
	public function related($category, $exclude_id, $limit = 3)
	{
		return $this->db->where('is_active', 1)
			->where('category', $category)
			->where('id !=', $exclude_id)
			->order_by('id', 'RANDOM')
			->limit($limit)
			->get($this->table)->result_array();
	}

	/** Increment the view counter. */
	public function add_view($id)
	{
		return $this->db->where('id', $id)
			->set('views', 'views+1', FALSE)
			->update($this->table);
	}

	/** Distinct categories present in active projects, with counts. */
	public function category_counts()
	{
		$rows = $this->db->select('category, COUNT(*) AS total')
			->where('is_active', 1)
			->group_by('category')
			->get($this->table)->result_array();
		$out = array();
		foreach ($rows as $r) $out[$r['category']] = $r['total'];
		return $out;
	}
}
