<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Routing\Controller;
use App\Http\Models\FileVideoModel;
use App\Http\Models\FileSoundModel;
use App\Http\Models\FileImageModel;
use App\Http\Models\FileDocumentModel;
use App\Http\Models\ArticleModel;
use App\Http\Models\SubCategoryModel;
use View;

class AdminController extends Controller
{

    // dashboard
    public function index()
    {
        
        // Initialize data arrays
        $data["sub_category_no_where_else"] = [];
        $data["sub_category_where_else"] = [];

        // Query for subcategories where category_id is 1
        $subCateNoWhereElse = SubCategoryModel::where('active', 1)->where('category_id', 1)->get();
        foreach ($subCateNoWhereElse as $item) {
            $subCateId = $item->id;

            $articleCount = ArticleModel::where('active', 1)
                ->where('category_id', 1)
                ->whereRaw('FIND_IN_SET(?, sub_category_ids)', [$subCateId])
                ->count();

            $data["sub_category_no_where_else"][] = [
                'id' => $subCateId,
                'name' => $item->name,
                'article_count' => $articleCount,
            ];
        }

        // Query for subcategories where category_id is 2
        $subCateQueryWhereElse =  SubCategoryModel::where('active', 1)->where('category_id', 2)->get();
        foreach ($subCateQueryWhereElse as $item) {
            $subCateId = $item->id;

            $articleCount = ArticleModel::where('active', 1)
                ->where('category_id', 2)
                ->whereRaw('FIND_IN_SET(?, sub_category_ids)', [$subCateId])
                ->count();

            $data["sub_category_where_else"][] = [
                'id' => $subCateId,
                'name' => $item->name,
                'article_count' => $articleCount,
            ];
        }


        // Optionally, you can calculate the total number of articles for each set
        $data["total_articles_no_where_else"] = array_sum(array_column($data["sub_category_no_where_else"], 'article_count'));
        $data["total_articles_where_else"] = array_sum(array_column($data["sub_category_where_else"], 'article_count'));

        $cVideo = FileVideoModel::count();
        $cSound = FileSoundModel::count();
        $cImage = FileImageModel::count();
        $cDocument = FileDocumentModel::count();

        return View::make('backend/dashboard')
        ->with('countVideoView', $cVideo)
        ->with('countSoundView', $cSound)
        ->with('countImageView', $cImage)
        ->with('countDocumentView', $cDocument)
        ->with('itemView', $data);
    }

}
