<?php

namespace App\Http\Controllers\Admin;

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

class NewsController extends Controller
{

    public function index()
    {
        return view(config('app.admin.view') . '.news.index', ['newss' => News::all()]);
    }

    public function create()
    {
        return view(config('app.admin.view') . '.news.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
        
        $time = time();

        $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'));

        $image = $request->file('image');
        $imagename = $validatedData['slug'] . '_' . time() . '.' . $image->extension();
        $destinationPath = public_path('/assets/news/');
        $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;

        }

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

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

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

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

    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('title'));

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

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

        }

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

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

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

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