<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Http\Controllers\Controller;
use App\Models\Services;

use function PHPSTORM_META\elementType;

class PageController extends Controller
{
    public function index()
    {

        $page = Page::where('permalink',  request()->path())->with('component')->first();

        $elements = $page->component->flatMap(function ($component) {
            return [
                $component->name => $component->componentFiled->map(function ($field) {
                    $group = $field->group ? $field->group  : 0;
                    return [$group => [
                        $field->name => $field->value,
                    ]];
                })
            ];
        });

        $components = [];
        foreach ($elements as $parent => $value) {
            $group = [];
            foreach ($value as $child) {
                $firstKey = key($child);
                $name = key($child[$firstKey]);
                $group[$firstKey][$name] = current($child[$firstKey]);
            }

            $components[$parent] = $group;
        }

        foreach ($page->component as $data) {
            $db_name = $data->database;
            if ($db_name && $data->set_from == 'database') {
                if (count($components[$data->name]) == 0) {
                    $components[$data->name][0] = [];
                }
                $limit = $data->limits->limit == 'null' || $data->limits->limit == 0 ? 100 : $data->limits->limit;
                $components[$data->name][1] = DB::table($db_name)->limit($limit)->get()->toArray();
            }
        }

        return view('pages', compact('components', 'page'));
    }

    public function serviceView($id)
    {
        $service =  Services::where('id', $id)->first();
        $allService =  Services::get(['id', 'title']);
        return view('service-view', compact('service', 'allService'));
    }
}