<?php

namespace App\Http\Controllers;

use App\Models\Site;
use Illuminate\Http\Request;

class SiteController extends Controller
{
    public function index(){
        $site = Site::where('delete_status', '0')->latest()->get();
        return view('backend.site.index', compact('site'));
        
    }

    public function store(Request $request)
    {

        $site = $request->all();

        if($request->file('image')){
            $imageName = time().'.'.$request->image->extension();
            $request->image->move(public_path('backend/images/site'), $imageName);
            $site['image']=$imageName;
        }
        $site['slug'] = \Str::slug($request->name).'-'.rand();
        Site::create($site);
        return redirect()->route('site.index')->with('success','Site added successfully.');
    }

    public function edit($id)
    {
        $edit_site = Site::find($id);
        $site = Site::latest()->where('delete_status','0')->get();
        return view('backend.site.index', compact('edit_site' , 'site'));
    }

    public function update(Request $request,  $id)
    {
        $site = Site::find($id);
        $input = $request->all();

        if($request->file('image')){
            $imageName = time().'.'.$request->image->extension();
            $request->image->move(public_path('backend/images/site'), $imageName);
            $input['image'] = $imageName;
        }
        $site->update($input);
        return redirect()->route('site.index')->with('success','Site updated successfully.');
    }

    public function destroy($id)
    {
        $site = Site::where('id', $id)->update(array('delete_status' => 1));
        return redirect()->route('site.index')->with('success','Site deleted successfully');
    }

    public function changeStatus(Request $request)
    {
        $site = Site::find($request->id);
        $site->status = $request->status;
        $site->save();

        return response()->json(['success'=>'Status change successfully.']);
    }
}
