<?php

namespace App\Services\Pages;

use App\Models\ComponentField;
use App\Models\Page;
use App\Models\PageComponent;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Encoders\WebpEncoder;

class PagesService
{

    public static function create($data)
    {
        $prepard = collect($data);

        $image_name = Self::Image($data['image'], false);
        $pages = Page::create([
            'name' => $prepard['name'],
            'permalink' => $prepard['permalink'],
            'description' => $prepard['description'],
            'status' => $prepard['status'],
            'image' => $image_name,

        ]);
        $components = isset($prepard['component_id']) ?  $prepard['component_id']  : [];
        foreach ($components as $key => $value) {
            PageComponent::create([
                'page_id' => $pages->id,
                'component_master_id' => $value,
                'limit' => $prepard['display'][$key],
            ]);
        }
    }

    public static function update($data, $id)
    {
        $prepard = collect($data);


        $page = Page::where('id', $id)->first();
        if (isset($prepard['image'])) {
            $image_name = Self::Image($data['image'], false);
            if ($image_name) {
                unlink('images/' . $page->image);
            }
        } else {
            $image_name = $page->image;
        }

        $page->update([
            'name' => $prepard['name'],
            'permalink' => $prepard['permalink'],
            'description' => $prepard['description'],
            'status' => $prepard['status'],
            'image' => $image_name,

        ]);
        $components = isset($prepard['component_id']) ?  $prepard['component_id']  : [];
        PageComponent::where('page_id', $page->id)->delete();
        foreach ($components as $key => $value) {
            PageComponent::create([
                'page_id' => $page->id,
                'component_master_id' => $value,
                'limit' => $prepard['display'][$key],
            ]);
        }
    }
    public static function  PagesUI(array $data)
    {
        $prepard = collect($data)->all();


        if (isset($prepard['field_id'])) {

            $fieldlist =  isset($prepard['field_name']) ? $prepard['field_name'] : [];
            $field_image =  isset($prepard['field_image']) ? $prepard['field_image'] : [];
            foreach ($fieldlist as $key => $value) {
                ComponentField::where('id', $prepard['field_id'][$key])->update([
                    'value' =>  $value,
                ]);
            }
            foreach ($field_image as $key => $value) {
                $updateImage = ComponentField::where('id', $prepard['field_image_id'][$key])->first();
                $image = Self::Image($value, $updateImage);
                $updateImage->update([
                    'value' =>  $image,
                ]);
            }
        }
        if (isset($prepard['sub_field_id'])) {

            $SubFieldList = ComponentField::where('component_id', $prepard['id'])
                ->where('group', 1)
                ->pluck('type', 'name')->toArray();

            $name = array_keys($SubFieldList);
            $type = array_values($SubFieldList);
            $id = ComponentField::wherein('id', isset($prepard['sub_field_id']) ? $prepard['sub_field_id'] : false)->pluck('id')->toArray();
            $all_id = ComponentField::where('component_id', $prepard['id'])->pluck('id')->toArray();
            $j = 0;
            $group = 1;
            foreach ($prepard['subfield'] as $key => $value) {
                for ($i = 0; $i < count($SubFieldList); $i++) {
                    if (in_array(isset($prepard['sub_field_id'][$j]), $id)) {
                        //   Sub Field Image Upload
                        $value_key = array_keys($value);
                        if ($SubFieldList[$name[$i]] == "file") {
                            $oldimage = ComponentField::where('id',  $prepard['sub_field_id'][$j])->first();
                            if (isset($value_key[$i])) {
                                $image_name = Self::Image($value[$name[$i]], $oldimage);
                            } else {
                                $image_name = $oldimage->value;
                            }

                            ComponentField::where('id', $prepard['sub_field_id'][$j])->update([
                                'value' =>   $image_name,
                            ]);
                        } else {
                            ComponentField::where('id', $prepard['sub_field_id'][$j])->update([
                                'value' =>  $value[$name[$i]],
                            ]);
                        }

                        $j++;
                    } else {
                        if ($SubFieldList[$name[$i]] == "file") {
                            if (isset($value_key[$i])) {
                                $image_name = Self::Image($value[$name[$i]], false);
                            } else {
                                $image_name = null;
                            }
                            ComponentField::create([
                                'name' => $name[$i],
                                'type' => $type[$i],
                                'value' =>  $image_name,
                                'component_id' =>   $prepard['id'],
                                'group' =>  $group,
                            ]);
                        } else {
                            ComponentField::create([
                                'name' => $name[$i],
                                'type' => $type[$i],
                                'value' =>  isset($value[$name[$i]]) ? $value[$name[$i]] : null,
                                'component_id' =>   $prepard['id'],
                                'group' =>  $group,
                            ]);
                        }
                    }
                }
                $group++;
            }
            if (count($all_id) >= count($prepard['sub_field_id'])) {
                $result = array_diff($all_id, $prepard['sub_field_id']);
                $lists = ComponentField::wherein('id', $result)->whereNotNull('group')->get();
                foreach ($lists as $key => $value) {
                    $field = ComponentField::where('id', $value->id)->first();

                    if ($field->type == 'file') {
                        if ($field->value) {
                            unlink('images/' . $field->value);
                        }
                    } else {
                        $field->delete();
                    }
                }
            }
        }
    }

    public static function Image($file, $oldimage)
    {
        // create image manager with desired driver
        $manager = new ImageManager(new Driver());
        // read image from file system
        $image = $manager->read($file);
        // save modified image in new format 
        // encode jpeg as webp format
        $encoded = $image->encode(new WebpEncoder(quality: 65)); // Intervention\Image\EncodedImage
        $encrypted =  md5($file) . '.webp';
        $encoded->save('images/' . $encrypted);
        if ($oldimage && isset($oldimage->value)) {
            unlink('images/' . $oldimage->value);
        }
        return $encrypted;
    }
}