<?php
namespace App\Http\Controllers;

use Illuminate\Support\Str; 
use Backpack\PageManager\app\Models\Page;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Glossary;

use Log;

class GlossaryController extends Controller
{
    public function index()
    {
        // GET PRACTICE AREAS
        $p_areas_parent = array();
        $p_areas = array();
        $practice_a = DB::select('SELECT `id`,`name`,`parent_id` FROM `practice_areas`');
        if (!empty($practice_a)) {
            foreach ($practice_a as $p_a) {
                if ($p_a->parent_id == "") {
                    $p_areas_parent[$p_a->id] = $p_a->name;
                }
            }

            foreach ($practice_a as $p_a) {
                if ($p_a->parent_id != "") {
                    if(isset($p_areas_parent[$p_a->parent_id])){
                        $p_areas[$p_areas_parent[$p_a->parent_id]][] = $p_a->name;
                    }
                }
            }
        }

        $data["p_areas"] = $p_areas;
        $data["p_area"] = "Glossary";

        $glossaries = Glossary::all()->groupBy(function ($item) {
            return Str::upper(substr($item->name, 0, 1));
        });

        // Optionally, sort the terms within each group
        $glossaries = $glossaries->map(function ($group) {
            return $group->sortBy('name');
        });

        $glossaries = $glossaries->sortKeys();

        // META
        $page = Page::findBySlug('glossary-of-legal-terms');

        $this->data['title'] = $page->title;
        $this->data['page'] = $page->withFakes();
        $this->data['data'] = $data;
        $this->data['glossaries'] = $glossaries;

        return view('glossary/index', $this->data);
    }
}
