<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Response;
use App\Repositories\EmployeeRepository;
use App\Util\CryptUtil;
use Illuminate\Support\Str;

class StaffServiceController extends Controller {

    private $employeeRepository;

    public function __construct(EmployeeRepository $employeeRepository)
    {
        $this->employeeRepository=$employeeRepository;
    }

	public function authentify(Request $request)
	{

        $success = 0;
        $error = 1;
        $cin = $request->get('cin');
        $id=0;
        $password = $request->get('password');
        $employee =$this->employeeRepository->findBy('cin',$cin);
        if (Hash::check($password, $employee->password))
        {
            $success = 1;
            $error = 0;
            $id=$employee->id;
            $token['api_token'] = hash('sha256',Str::random(10),false);
            $token['expires_on'] = Carbon::now()->addMonth()->toDateTimeString();
            if($this->employeeRepository->update($token,$id)) {
                $api_token = $token['api_token'];
            }
        }
        return Response::json(compact('success','error','id','api_token'));
	}

    public function renderLogs(Request $request)
    {
        $success = 0;
        $error = 1;
        $id=$request->get('id');
        $logs = $this->employeeRepository->find($id)->logs()->get();
        if($logs){
            $success = 1;
            $error = 0;
        }
        return Response::json(compact('success','error','logs'));
    }


	public function renderKey(Request $request)
	{
        $success = 0;
        $error = 1;
        $key = null;
        $id=$request->get('id');
        $employee = $this->employeeRepository->find($id);
        if ($employee) {
            $key = CryptUtil::generateKey($employee->cin);
            $success = 1;
            $error = 0;
        }
        return Response::json(compact('success','error','key'));
	}


	public function editProfile(Request $request)
	{
        $success = 0;
        $error = 1;
        $id=$request->get('id');
        $employee = $this->employeeRepository->find($id);
        if($employee){
            $success = 1;
            $error = 0;
        }
        return Response::json(compact('success','error','employee'));
	}


	public function updateProfile(Requests\EditProfileRequest $request)
	{
        $success = 0;
        $error = 1;
        $employee =$this->employeeRepository->update($request->all(),$request->get('id'));
            if ($employee) {
                $success = 1;
                $error = 0;
            }
        return Response::json(compact('success','error'));
	}


    public function download($cin){
        return response()->download(public_path('img/profiles').'/'.$cin.'.jpg');
    }

}
