<?php

namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Category extends Model
{
    use SoftDeletes;

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * Retrieves categories along with nested sub-categories and sub-sub categories.
     *
     * @param  int  $business_id
     * @return array
     */
    public static function catAndSubCategories($business_id)
    {
        // Get all categories for the business of type 'product'
        $all_categories = Category::where('business_id', $business_id)
                            ->where('category_type', 'product')
                            ->orderBy('name', 'asc')
                            ->get()
                            ->toArray();

        if (empty($all_categories)) {
            return [];
        }

        // Group the categories by parent_id
        $grouped = [];
        foreach ($all_categories as $category) {
            $grouped[$category['parent_id']][] = $category;
        }

        // Recursive function to build the tree
        $buildTree = function ($parentId) use (&$buildTree, $grouped) {
            $branch = [];

            if (isset($grouped[$parentId])) {
                foreach ($grouped[$parentId] as $category) {
                    // Recursively get children for this category
                    $children = $buildTree($category['id']);
                    if ($children) {
                        $category['sub_categories'] = $children;
                    }
                    $branch[] = $category;
                }
            }

            return $branch;
        };

        // Build the tree starting from parent_id = 0 (main categories)
        return $buildTree(0);
    }

    /**
     * Category Dropdown
     *
     * @param  int  $business_id
     * @param  string  $type  Category type
     * @return \Illuminate\Support\Collection
     */
    public static function forDropdown($business_id, $type)
    {
        $categories = Category::where('business_id', $business_id)
                            ->where('parent_id', 0)
                            ->where('category_type', $type)
                            ->select(DB::raw('IF(short_code IS NOT NULL, CONCAT(name, "-", short_code), name) as name'), 'id')
                            ->orderBy('name', 'asc')
                            ->get();

        return $categories->pluck('name', 'id');
    }

    /**
     * Defines a relationship to fetch immediate sub-categories.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function sub_categories()
    {
        return $this->hasMany(\App\Category::class, 'parent_id');
    }

    /**
     * Recursive relationship to fetch all nested children.
     *
     * You can use this in your queries to eager load all children:
     * Category::with('children')->find($id);
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id')->with('children');
    }

    /**
     * Scope a query to only include main (parent) categories.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOnlyParent($query)
    {
        return $query->where('parent_id', 0);
    }
}
