<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Dynamic;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class DynamicController extends Controller
{

    public function index()
    {
        return view(config('app.admin.view') . '.dynamic.index', ['dynamics' => Dynamic::all()]);
    }

    public function create()
    {
        return view(config('app.admin.view') . '.dynamic.create');
    }

    public function store(Request $request)
    {
        $time = time();

        $input = array_keys($request->input()); // all inputs
        $input = array_diff($input, ['_token', '_method']); // removing _token & _method
        $errors = array_fill_keys($input, 'required'); // all fields are required

        $errors['additional'] = "";

        
        if (empty($request->input('details'))) {
            unset($errors['details']);
        }

        $validatedData = $request->validate($errors); // all fields validation

        // $validatedData['slug'] = \Str::slug($request->input('name'));


        $image = $request->file('image');
        if (isset($image) && !empty($image)) {
            $request->validate(['image' => 'required|mimes:jpg,png,jpeg,gif,svg,webp|max:2048']);
            
            $imagename = $validatedData['slug'] . '_img_1' . $time . '.' . $image->extension();
            $imagename2 = $validatedData['slug'] . '_img_2' . $time . '.webp';
            $destinationPath = public_path('/assets/dynamic/');
            $request->image->move($destinationPath . '/meta/', $imagename); // for grid
            $validatedData['image'] = $imagename2;
        }

        $banner = $request->file('banner');
        if (isset($banner) && !empty($banner)) {
            $request->validate(['banner' => 'required|mimes:jpg,png,jpeg,gif,svg,webp|max:2048']);

            $bannername = $validatedData['slug'] . '1_' . $time . '.' . $banner->extension();
            $bannername2 = $validatedData['slug'] . '2_' . $time . '.webp';
            $destinationPath = public_path('/assets/dynamic/');
            $request->banner->move($destinationPath . '/banner/', $bannername); // for banner
            $validatedData['banner'] = $bannername2;

        }

        Dynamic::create($validatedData);

        if (isset($image) && !empty($image)) {
            // Resize and optimize the image using Intervention/Image package
            $img = Image::make($destinationPath . '/meta/' . $imagename);
            $img->resize(1200, 627)->encode('webp');
            $img->save($destinationPath . '/meta/' . $imagename2);
            
            unlink($destinationPath . '/meta/' . $imagename);
            
        }

        if (isset($banner) && !empty($banner)) {

            // Resize and optimize the image using Intervention/Image package
            $bannerimg = Image::make($destinationPath . '/banner/' . $bannername);
            $bannerimg->encode('webp');
            $bannerimg->save($destinationPath . '/banner/' . $bannername2);
            unlink($destinationPath . '/banner/' . $bannername);

        }

        return redirect(config('app.admin.route') . '/dynamic/create')->with('success', 'Dynamic Page added successfully');

    }

    public function show($id)
    {
        $id = decrypt($id);
        $dynamic = Dynamic::find($id);


        return view(config('app.admin.view') . '.dynamic.show', compact('dynamic'));
    }

    public function edit($id)
    {
        $id = decrypt($id);
        $dynamic = Dynamic::find($id);
        

        return view(config('app.admin.view') . '.dynamic.edit', compact('dynamic'));
    }

    public function update(Request $request, $id)
    {
        $xid = decrypt($id);
        $time = time();

        $input = array_keys($request->input()); // all inputs
        array_splice($input, 0, 2); // removing _token & _method
        $errors = array_fill_keys($input, 'required'); // all fields are required

        $errors['additional'] = "";

        $validatedData = $request->validate($errors); // all fields validation
        // $validatedData['slug'] = \Str::slug($request->input('name'));
        $destinationPath = public_path('/assets/dynamic/');

        $image = $request->file('image');
        $validatedData['image'] = Dynamic::whereId($xid)->pluck('image')->first();
        if (!empty($image)) {
            $request->validate(['image' => 'required|mimes:jpg,png,jpeg,gif,svg,webp|max:2048']);

            if (file_exists($destinationPath . '/meta/' . $validatedData['image'])  && !empty($validatedData['image'])) {
                unlink($destinationPath . '/meta/' . $validatedData['image']);
            }

            $imagename = $validatedData['slug'] . '_img_1' . $time . '.' . $image->extension();
            $imagename2 = $validatedData['slug'] . '_img_2' . $time . '.webp';
            $request->image->move($destinationPath . '/meta/', $imagename); // for grid
            $validatedData['image'] = $imagename2;

            // Resize and optimize the image using Intervention/Image package
            $img = Image::make($destinationPath . '/meta/' . $imagename);
            // Resize and store the image for the meta image

                // Resize and store the image for the meta image
                $img->resize(1200, 627)->encode('webp', 100);
                $img->save($destinationPath . '/meta/' . $imagename2);

                $img->encode('webp');
                $img->save($destinationPath . '/meta/' . $imagename);


            unlink($destinationPath . '/meta/' . $imagename);

        }

        $banner = $request->file('banner');
        $validatedData['banner'] = Dynamic::whereId($xid)->pluck('banner')->first();
        if (!empty($banner)) {
            $request->validate(['banner' => 'required|mimes:jpg,png,jpeg,gif,svg,webp|max:2048']);
            if (file_exists($destinationPath . '/banner/' . $validatedData['image']) && !empty($validatedData['banner'])) {
                unlink($destinationPath . '/banner/' . $validatedData['banner']);
            }

            $bannername = $validatedData['slug'] . '_1' . $time . '.' . $banner->extension();

            $bannername2 = $validatedData['slug'] . '_2' . $time . '.webp';
            $request->banner->move($destinationPath . '/banner/', $bannername); // for grid
            $validatedData['banner'] = $bannername2;

            // Resize and optimize the banner using Intervention/Image package
            $bannernameimg = Image::make($destinationPath . '/banner/' . $bannername);
            // Resize and store the banner for the banner banner
            $bannernameimg->encode('webp');
            $bannernameimg->save($destinationPath . '/banner/' . $bannername2);
            unlink($destinationPath . '/banner/' . $bannername);

        }

        Dynamic::whereId($xid)->update($validatedData); // saving the data

        return redirect(config('app.admin.route') . '/dynamic/edit/' . $id)->with('success', 'Dynamic Page has been updated');
    }

    public function destroy($id)
    {
        $id = decrypt($id);
        $dynamic = Dynamic::find($id);
        $dynamic->delete();

        return redirect(config('app.admin.route') . '/dynamic')->with('success', 'Dynamic has been deleted');
    }
}
