<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Tool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class ToolController extends Controller
{

    function __construct()
    {
        $this->middleware('role_or_permission:home tool access|home tool create|home tool delete', ['only' => ['index']]);
        $this->middleware('role_or_permission:home tool create', ['only' => ['create', 'store']]);
        $this->middleware('role_or_permission:home tool delete', ['only' => ['delete']]);
    }

    function index()
    {
        $datas =  Tool::all();
        return view('admin.home.tool.index', compact('datas'));
    }

    function store(Request $request)
    {
        $request->validate([
            'image' => ['required']
        ]);



        $filename = fileupload($request->file('image'), 'homepage-files');

        Tool::create([
            'file_name' => $filename
        ]);

        $notification = array(
            'messege' => 'Create successfully',
            'alert-type' => 'success'
        );
        return back()->with($notification);
    }

    function create()
    {
        return view('admin.home.tool.create');
    }
    function delete($id)
    {
        $data = Tool::findOrFail($id);
        if (File::exists($data->file_name)) {
            File::delete($data->file_name);
        }

        $data->delete();

        $notification = array(
            'messege' => 'Deleted successfully',
            'alert-type' => 'success'
        );
        return back()->with($notification);
    }
}
