<?php

namespace App\Http\Controllers;

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

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

    public function store(Request $request){
        $client = $request->all();
        if($request->file('image')){
            $imageName = time().'.'.$request->image->extension();
            $request->image->move(public_path('backend/images/client'), $imageName);
            $client['image']=$imageName;
        }
        Client::create($client);
        return back()->with('success', 'Client added successfully');
    }

    public function edit(Client $client){
        $clients = Client::where('delete_status', '0')->latest()->get();
        return view('backend.client.index', compact('client', 'clients'));
    }

    public function update(Request $request, $id){
        $client = Client::find($id);
        $input = $request->all();
        if($request->file('image')){
            $imageName = time().'.'.$request->image->extension();
            $request->image->move(public_path('backend/images/client'), $imageName);
            $client['image']=$imageName;
        }
        $client->update($input);
        return back()->with('success', 'Client updated successfully');
    }

    public function destroy($id)
    {
        $client = Client::where('id', $id)->update(array('delete_status' => 1));

        return redirect()->route('client.index')
                        ->with('success','Client deleted successfully');
    }

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

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