<?php

namespace App\Http\Controllers;

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

class ClientController extends Controller
{

	public function index(){
		$data = Client::all();
		return view('pages.home')->with('data',$data);
	}

	public function create(){
		return view('pages.create');
	}

	public function store(Request $request){
		Client::create($request->all());
		return redirect('home');
	}	

	public function edit($id){
		$data = Client::find($id);
		return view('pages.update')->with('data',$data);
	}

	public function update(Request $request, $id){
		Client::find($id)->update($request->all());
		return redirect('home');
	}

	public function destroy($id){
		Client::find($id)->delete();
		return redirect('home');
	}

	public function search(Request $request)
	{
		if($request->ajax())
		{
			$outputHtml = "";
			$clients = Client::where('fullnames','LIKE','%'.$request->search.'%')->get();
			if($clients)
			{
				foreach ($clients as $key => $client) {
					$outputHtml.='<tr>'.
					'<td>'.$client->id.'</td>'.
					'<td>'.'<img src="images/'.$client->image.'"style="max-width: 5em; max-height: 5em;">'.'</td>'.
					'<td>'.$client->fullnames.'</td>'.
					'<td>'.$client->sex.'</td>'.
					'<td>'.$client->idcard.'</td>'.
					'<td>'.$client->birthdate.'</td>'.
					'<td>'.$client->province.'</td>'.
					'<td>'.$client->district.'</td>'.
					'<td>'.$client->sector.'</td>'.
					'<td>'
					.'<form action="home/'.$client->id.'" method="post">'.
					csrf_field().
					'<a href="home/'.$client->id.'/edit" class="btn btn-success" title="update'.$client->fullnames.'"><i class="glyphicon glyphicon-edit"></i></a>'.
					'<input type="hidden" name="_method" value="delete">
					<button type="submit" class="btn btn-danger" title="delete '.$client->name.'">
					<i class="glyphicon glyphicon-trash"></i></button>
					</form>'.
					'</td>'.
				'</tr>';
					}	
				return Response($outputHtml);
			}

		}
	}
    
}
