<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Advertisement;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\Response;

class AdvertisementController extends Controller
{
    public function index(Request $request)
    {
        abort_if(Gate::denies('advertisement_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        if ($request->ajax()) {
            $query = Advertisement::query()->select(sprintf('%s.*', (new Advertisement)->table));
            $table = Datatables::of($query);

            $table->addColumn('actions', '&nbsp;');

            $table->addColumn('actions', function ($row) {
                $viewGate      = 'advertisement_show';
                $editGate      = 'advertisement_edit';
                $deleteGate    = 'advertisement_delete';
                $crudRoutePart = 'advertisement';

                return view('partials.datatablesActions', compact(
                    'viewGate',
                    'editGate',
                    'deleteGate',
                    'crudRoutePart',
                    'row'
                ));
            });

            $table->addColumn('id', function ($row) {
                return $row->id ? $row->id : '';
            });
            $table->addColumn('order', function ($row) {
                return $row->order ? $row->order : '';
            });
            $table->addColumn('status', function ($row) {
                return isset(Advertisement::STATUS_SELECT[$row->status]) ? Advertisement::STATUS_SELECT[$row->status] : '';
            });
            $table->addColumn('image', function ($row) {
                return sprintf(
                    '<a class="fancybox-popup" href="%s"><img src="%s" style="height: 50px;"></a>',
                    asset($row->image),
                    asset($row->image),
                );
                return '';
            });

            $table->rawColumns(['actions', 'image']);

            return $table->make(true);
        }

        return view('admin.advertisement.index');
    }

    public function create()
    {   
        abort_if(Gate::denies('advertisement_create'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        return view('admin.advertisement.create');
    }

    public function store(Request $request)
    {
        $advertisement_data = $request->all();

        if ($request->hasFile('image')) {
            $imageName = time().'.'.$request->file('image')->getClientOriginalExtension();
            $request->file('image')->move(public_path('uploads/advertisement'), $imageName);
            $advertisement_data['image']= 'uploads/advertisement/' . $imageName;
        }

        Advertisement::create($advertisement_data);
      
        return redirect()->route('admin.advertisement.index')->with('success', 'Advertisement added successfully!');
    }

    public function edit($id)
    {
        abort_if(Gate::denies('advertisement_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $advertisement = Advertisement::findOrFail($id);

        return view('admin.advertisement.edit', compact('advertisement'));
    }

    public function update(Request $request, Advertisement $advertisement)
    {
        $advertisement_data = $request->all();

        if ($request->hasFile('image')) {
            if ($advertisement->image) {
                $oldImagePath = public_path($advertisement->image);
    
                if (file_exists($oldImagePath)) {
                    unlink($oldImagePath); // Delete the file
                } 
            }

            $imageName = time().'.'.$request->file('image')->getClientOriginalExtension();
            $request->file('image')->move(public_path('uploads/advertisement'), $imageName);
            $advertisement_data['image']= 'uploads/advertisement/' . $imageName;
        }

        $advertisement->update($advertisement_data);


        return redirect()->route('admin.advertisement.index')->with('success', 'Advertisement updated successfully.');
    }

    public function destroy(Advertisement $advertisement)
    {
        abort_if(Gate::denies('advertisement_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden');
        
        if ($advertisement->image) {
            $oldImagePath = public_path($advertisement->image);

            if (file_exists($oldImagePath)) {
                unlink($oldImagePath); // Delete the file
            } 
        }

        $advertisement->delete();

        return back();
    }

    public function show($id)
    {   
        abort_if(Gate::denies('advertisement_show'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $advertisement = Advertisement::find($id);

        return view('admin.advertisement.show', compact('advertisement'));
    }
}
