<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Mail\Email;
use Mail;
use Str;
use DB;
use Hash;
class UserApiController extends Controller
{
    public function createPost(Request $request){

        $jsondata =[];
        $upassword = Str::random(8);
        $data = new User;
        $username = explode('@',$request->email)['0'];
        $data->name = $request->name;
        $data->email = $request->email;
        $data->role = $request->role;
        $data->username = $username;
        $data->phone = $request->phone;
       // $data->department = $request->department;
        $data->password = Hash::make($upassword);
        $data->added_by = $request->added_by;
        $data->save();
 
        $mailData = [
         "title" => "Dear $request->name, your login credential is as below.",
         "Email"  => $request->email,
         "Password"  => $upassword,
         "data"  =>$data
        ];
        $jsondata=$mailData;
        Mail::to($request->email)->send(new Email($mailData));
        //echo "Mail send successfully !!";
        try{
        return response()->json($jsondata);   
//         return redirect('superadmin')->with(['message' =>'User Successfully Created']);
        } catch (QueryException $e) {
            if ($this->isDuplicateEntryException($e)) {
             throw new DuplicateEntryException('Duplicate Entry');
            }
            throw $e;
     }
     }

     public function agentLsit(){
        $jsondata = [];
        $data = User::where('role', '2')->get();
        $jsondata=$data;
        return response()->json(['message'=>'Agent list', 'data'=>$jsondata]);
     }
     
}