<?php

namespace App\Http\Controllers\Backend\Component;

use App\Http\Controllers\Controller;
use App\Http\Requests\Component\ComponentCreateRequest;
use App\Models\ComponentField;
use App\Models\ComponentMaster;
use App\Services\Component\ComponentService;
use Illuminate\Http\Request;

class ComponentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {

        $components = ComponentMaster::orderBydesc('id')->with('componentFiled')->get();

        return view('backend.pages.component.index', compact('components'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(ComponentCreateRequest $request)
    {
        ComponentService::ComponentCreate(request()->all());
        return redirect()->back()->with(['success' => "Component create successfully"]);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        ComponentService::ComponentUpdate(request()->all(), $id);
        return redirect()->back()->with(['success' => "Component Update successfully"]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        ComponentMaster::where('id', $id)->delete();
        return redirect()->back()->with(['success' => "Component Delete successfully"]);
    }
    public function fieldDelete()
    {
        $component = ComponentField::where('id', request()->id)->first();
        if (!empty($component->group)) {
            $parent = $component->component_id;
            $name = $component->name;
            $deleted_data = ComponentField::where('name', $name)->where('component_id', $parent)->whereNotNull('group')->get();
            foreach ($deleted_data as $key => $value) {
                $filed = ComponentField::where('id', $value->id)->first();
                if ($filed->type == 'file') {
                    if ($filed->value) {
                        unlink('images/' . $filed->value);
                    }
                }
                $filed->delete();
            }
        } else {

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


        return response()->json(true);
    }
}
