<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Industry;
use Faker\Provider\File;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class IndustryController extends Controller
{

    public function index()
    {
        return view(config('app.admin.view') . '.industry.index', ['industrys' => Industry::all()]);
    }

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

    public function store(Request $request)
    {

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

        $errors['additional'] = "";

        $validatedData = $request->validate($errors); // all fields validation
        $request->validate([
            'image' => 'required|mimes:jpg,png,jpeg,gif,svg,webp|max:2048',
        ], [
            'image.required' => 'Please select an image to upload.',
            'image.mimes' => 'Only JPG, PNG, JPEG, GIF, SVG, and WebP images are allowed.',
            'image.max' => 'The maximum allowed file size is 2048 KB.',
        ]);

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


        $image = $request->file('image');
        $imagename = $validatedData['slug'] . '_' . time() . '.' . $image->extension();
        $destinationPath = public_path('/assets/industry/');
        $img = Image::make($image->path());
        $img->resize(1200, 630)->save($destinationPath . '/meta/' . $imagename); // for meta share image
        $request->image->move($destinationPath . '/grid/', $imagename); // for grid
        $img->resize(800, 600)->save($destinationPath . '/details/' . $imagename); // for details page

        $validatedData['image'] = $imagename;

        $banner = $request->file('banner');
        if (isset($banner) && !empty($banner)) {

            $bannername = $validatedData['slug'] . '1_' . $time . '.' . $banner->extension();
            $bannername2 = $validatedData['slug'] . '2_' . $time . '.webp';

            $request->banner->move($destinationPath . '/banner/', $bannername); // for 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);

            $validatedData['banner'] = $bannername2;

        }

        Industry::create($validatedData); // saving the data

        return redirect(config('app.admin.route') . '/industry/create')->with('success', 'Industry added successfully');
    }

    public function show($id)
    {
        $id = decrypt($id);
        $industry = Industry::find($id);
        return view(config('app.admin.view') . '.industry.show', compact('industry'));
    }

    public function edit($id)
    {
        $id = decrypt($id);
        $industry = Industry::find($id);
        return view(config('app.admin.view') . '.industry.edit', compact('industry'));
    }

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

        $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'] = "";
        $time = time();


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

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

        $destinationPath = public_path('/assets/industry/');

        $image = $request->file('image');
        $validatedData['image'] = Industry::whereId($xid)->pluck('image')->first();
        if (!empty($image)) {
            $request->validate([
                'image' => 'required|mimes:jpg,png,jpeg,gif,svg,webp|max:2048',
            ], [
                'image.required' => 'Please select an image to upload.',
                'image.mimes' => 'Only JPG, PNG, JPEG, GIF, SVG, and WebP images are allowed.',
                'image.max' => 'The maximum allowed file size is 2048 KB.',
            ]);

            if (file_exists(public_path($destinationPath . '/grid/' . $validatedData['image']))) {
                unlink($destinationPath . '/meta/' . $validatedData['image']);
                unlink($destinationPath . '/grid/' . $validatedData['image']);
                unlink($destinationPath . '/details/' . $validatedData['image']);
            }

            $imagename = $validatedData['slug'] . '_' . time() . '.' . $image->extension();
            $img = Image::make($image->path());
            $img->resize(1200, 630)->save($destinationPath . '/meta/' . $imagename); // for meta share image
            $request->image->move($destinationPath . '/grid/', $imagename); // for grid
            $img->resize(800, 600)->save($destinationPath . '/details/' . $imagename); // for details page

            $validatedData['image'] = $imagename;
        }

        $banner = $request->file('banner');
        $validatedData['banner'] = Industry::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'])) {
                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);

        }

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

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

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

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