<?php

namespace App\Http\Controllers\Dashboard\Partner;

use App\Http\Controllers\Controller as ExController;
use App\Models\Partner;

use App\Http\Requests\Dashboard\Partner\Update as UpdateRequest;
use App\Http\Requests\Dashboard\Partner\Store as StoreRequest;

use App\Jobs\Dashboard\Partner\Store as StoreJob;
use App\Jobs\Dashboard\Partner\Update as UpdateJob;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class Controller extends ExController
{
    public function index()
    {
        $this->authorize('view', 'partners');
        $partners = Partner::orderBy('position')->paginate(20);
        return view('dashboard.partners.index', compact('partners'));
    }

    public function create()
    {
        $this->authorize('create', 'partners');
        return view('dashboard.partners.create');
    }

    public function store(StoreRequest $request)
    {
        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('uploads/partners');
        }
        $this->dispatchSync(StoreJob::fromRequest($request, $path));

        $this->info(trans('admin.messages.created'));
        return redirect()->route('dashboard.partners.index');
    }

    public function edit(Partner $partner)
    {
        $this->authorize('update', 'partners');
        return view('dashboard.partners.edit', compact('partner'));
    }

    public function update(UpdateRequest $request, Partner $partner)
    {
        if ($request->hasFile('image')) {
            if (env('FILESYSTEM_DISK') == 's3') {
                // delete old image from s3
                Storage::disk('s3')->delete($partner->image);
            } else {
                // detele old image
                $imagePath = public_path($partner->image);

                if (File::exists($imagePath)) {
                    File::delete($imagePath);
                }
            }

            $path =  $request->file('image')->store('uploads/partners');
        } else {
            $path = $partner->image;
        }

        $this->dispatchSync(UpdateJob::fromRequest($partner, $request, $path));

        $this->info(trans('admin.messages.updated'));
        return redirect()->route('dashboard.partners.index');
    }

    public function destroy(Partner $partner)
    {
        $this->authorize('delete', 'partners');

        if (env('FILESYSTEM_DISK') == 's3') {
            // delete old image from s3
            Storage::disk('s3')->delete($partner->image);
        } else {
            $imagePath = public_path($partner->image);

            if (File::exists($imagePath)) {
                File::delete($imagePath);
            }
        }

        $partner->delete();

        $this->info(trans('admin.messages.deleted'));
        return redirect()->back();
    }
}
