<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Admin;
use App\Win;
use Auth;

class AdminController extends Controller
{
    
    public function wins()
    {

    	return view('admin.tableWins');
    }
     
    public function winsforSuper()
    {

    	return view('admin.tableWinsForSuper');
    }
 
    public function validateCode(Request $data)
    {
    	$this->validate($data,[
    		'code' => 'required',
    		]);

    	$win = Win::where('code',$data->code)->first();
    	if($win){
            $win->isGiven = 1;
    		$win->admin_id = Auth::user()->id;
    		$win->save();
    		return response(200);
    	}

    	return response('not found',404);
    		
    }

    public function winsData()
    {
    	
    	$wins = Win::all();

		$wins->map(function ($win) {
		    $win['reward'] = $win->reward;
		    $win['user'] = $win->user;
		    $win['ville'] = $win->user->ville;
		    if (Auth::user()->isSuper()) {
		    	$win['admin'] = $win->admin;
		    }
		    return $win;
		});

    	return $wins;
    }
    public function searchWinsData(Request $data)
    {
    	if (!$data->value) {
    		return $this->winsData();
    	}
    	$wins = Win::whereHas($data->by, function ($query) use ($data){
	        $query->where($data->where, 'like', '%'.$data->value.'%');
	    })->get();

		$wins->map(function ($win) {
		    $win['reward'] = $win->reward;
		    $win['user'] = $win->user;
		    $win['ville'] = $win->user->ville;
		    $win['admin'] = $win->admin;

		    return $win;
		});

    	return $wins;
    }

    function login(){


        return view('admin.login');

    }

    function logout(){

        Auth::logout();

        return redirect('loginAdmin');

    }
}
