<?php

namespace Modules\Team\Models;

use CodeIgniter\Model;

class TeamCategoryModel extends Model
{

  protected $table = 'team_category';
    protected $primaryKey = 'id';

    protected $allowedFields = ['name', 'parent_category_id', 'alias', 'description', 'created_by', 'updated_at', 'updated_by'];

    protected $returnType     = 'array';
    protected $useTimestamps  = true;
    protected $useSoftDeletes = true;
    
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    //Get all Post Categories
    public function getAll()
    {
      $builder = $this->db->table('team_category');
      $builder->where('deleted_at', Null);
      $builder->orderBy('id', 'DESC');
	    $result = $builder->get()->getResult();
	    return $result;
    }

    //Get Single Category
    public function getSingleTeamCategory($category)
    {
        $builder = $this->db->table('team_category as tc');
        $builder->where('tc.id', $category);
        $builder->orWhere('tc.alias', $category);
	    $result = $builder->get()->getRow();
	    return $result;

    }

    public function getParentCategory($id)
    {
        $builder = $this->db->table('team_category');
        $builder->select('parent_category_id');
        $builder->where('id', $id); // Use 'id' instead of 'master_category_id'
        $result = $builder->get()->getRow();

        if ($result !== null) {
            $masterCategoryId = $result->parent_category_id;

            // Fetch the master category name based on the master category ID
            $masterCategory = $this->db->table('team_category')
                ->select('name')
                ->where('id', $masterCategoryId)
                ->get()
                ->getRow();

            return $masterCategory;
        }
        return null;
    }

     // Recursive function to get categories and subcategories
     public function getCategoryList()
     {
         $categories = $this->findAll(); // Fetch all categories
 
         // Create a hierarchical structure for categories and subcategories
         $categoryTree = [];
 
         foreach ($categories as $category) {
             if ($category['parent_category_id'] === null ) {
                 // This is a parent category (exclude category with id = 1)
                 $categoryTree[$category['id']] = [
                     'name' => $category['name'],
                     'subcategories' => [],
                     'id' => $category['id'],
                 ];
             } else {
                 // This is a subcategory (exclude category with id = 1)
                 $categoryTree[$category['parent_category_id']]['subcategories'][] = [
                     'id' => $category['id'],
                     'name' => $category['name'],
                 ];
             }
         }
 
         return $categoryTree;
     }


}
