<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SiteBackground;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Intervention\Image\Encoders\WebpEncoder;
use Intervention\Image\Laravel\Facades\Image;

class SiteBackgroundController extends Controller
{
    /**
     * Display admin index page
     */
    public function index(): View
    {
        return view('admin.background.index', [
            'images' => SiteBackground::all(),
        ]);
    }

    /**
     * Create new site backgrounds
     */
    public function create(Request $request): RedirectResponse
    {
        $request->validate([
            'images' => 'required',
            'date_start' => 'required',
            'date_end' => 'required',
        ]);

        foreach ($request->file('images') as $file) {
            // Initiating a database transaction in case something goes wrong.
            DB::beginTransaction();

            try {
                $bg = SiteBackground::create(array_merge(
                    $request->only(['date_start', 'date_end']),
                    [
                        'default' => (bool) $request->input('default', false),
                    ]
                ));

                $resolutions = [1440, 1080, 720, 640];
                foreach ($resolutions as $resolution) {
                    // /images/background/1-2560p.webp
                    $targetPath = "/images/background/{$bg->id}-{$resolution}p.webp";

                    Image::read($file->getRealPath())
                        ->scaleDown(height: $resolution)
                        ->encode(new WebpEncoder)
                        ->save(public_path($targetPath));
                }

            } catch (\Exception $e) {
                DB::rollBack();
                Log::error($e->getMessage());

                return redirect()->back();
            }

            // Committing the database transaction.
            DB::commit();
        }

        cache()->forget('background');

        return redirect()->back();
    }

    public function update(Request $request): RedirectResponse
    {
        $request->validate([
            'id' => 'required|exists:site_backgrounds,id',
            'date_start' => 'required',
            'date_end' => 'required',
        ]);

        SiteBackground::where('id', $request->input('id'))->update(array_merge(
            $request->only(['date_start', 'date_end']),
            [
                'default' => (bool) $request->input('default', false),
            ]
        ));

        cache()->forget('background');

        return redirect()->back();
    }

    /**
     * Delete backround
     */
    public function delete(Request $request): RedirectResponse
    {
        $id = $request->input('id');

        // Initiating a database transaction in case something goes wrong.
        DB::beginTransaction();

        $bg = SiteBackground::where('id', $id)->firstOrFail();
        $bg->delete();

        $resolutions = [1440, 1080, 720, 640];
        try {
            foreach ($resolutions as $resolution) {
                $targetPath = "/images/background/{$id}-{$resolution}p.webp";
                File::delete(public_path($targetPath));
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());

            return redirect()->back();
        }

        // Committing the database transaction.
        DB::commit();

        cache()->forget('background');

        return redirect()->back();
    }
}
