<?php

namespace App\Modules\Client\Controllers;

use App\AIFeed;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use App\ConcernMessage;
use App\Notifications;
use App\Mail\SendMail;
use App\RaiseConcern;
use App\RolesEvent;
use App\MealMenu;
use Storage;
use App\VendorDocs;
use App\Feedback;
use App\Marshal;
use App\MarshalDocs;
use App\MapRole;
use Validator;
use App\Invoice;
use App\Vendor;
use App\MealCountDetail;
use App\User;
use Auth;
use DB;

use App\QRScanDetail;
use App\QRDetail;
use App\ClientsEmp;
use App\Client;
use App\Type4QrScanDetail;
use QrCode;
use File;
use Image;
use Excel;

use App\Exports\InvoiceExport;

class ClientController extends Controller
{
    public function __construct()
    {
        $this->middleware(['role:client', 'auth']);
    }

    protected function sendInvitationMail($type, $sendMailId, $foodcraftRole, $subject, $additional_data) {
        \Log::info("Send Invitation Mail");
        if($type == "newConcern"){
          $subject = "Concern Raised! by " . $additional_data['client_name'] . " on date " . date('Y-m-d H:i:s');
        }
        $existingData = array(
            'type' => $type,
            'subject' => $subject,
            'mailId' => $sendMailId,
            'role' => $foodcraftRole,
            'note' => 'This is a Test Email only..',
        );
        // dd($existingData);
        // dd($additional_data);
        $data = array_merge($existingData, $additional_data);
        // dd($data);
        $res = Mail::to($sendMailId)
                ->send(new SendMail($data));
    }

    public function marshal_list()
    {
        // dd('Clients Marshal');
        $marshals = MapRole::where('map_roles.clientId', Auth::user()->id)
            ->join('users', 'map_roles.marshalId', '=', 'users.id')
            ->join('marshals', 'map_roles.marshalId', '=', 'marshals.marshalId')
            ->select(
                    'marshals.marshalId as marshal_id',
                    'marshals.designation',
                    'users.name as marshal_name',
                    'users.email as marshal_email',
                    'users.username as marshal_username',
                    'users.contactNumber as marshal_number'
                )
            ->get();
        // dd($marshals);
        return view('Client::marshals', compact('marshals'));
    }

    public function showEventsList()
    {
        $events = RolesEvent::where('client_id', Auth::user()->id)->get();
        // return view('Client::eventSection', compact('events'));
        return view('Client::event/event', compact('events'));
    }

    public function showEventForm()
    {
        return view('Client::event/event');
    }

    protected function validateErrorMesage(array $allrequest)
    {
        return Validator::make($allrequest, [
            'reservation_date' => 'required|date_format:d/m/Y',
            'guest_num' => 'required|numeric',
            'per_plate' => 'required|numeric',
            'event_type' => ['required', Rule::in(['corporateEvent', 'indoorThemeEvent', 'odc', 'outdoorThemeEvent'])],
            'event_decoration' => ['required', Rule::in(['yes', 'no'])],
            'cultry_crockery' => ['required', Rule::in(['yes', 'no'])],
            'description' => 'required|string|max:255',
            'menu' => 'mimes:doc,pdf,docx|max:1000'
        ]);
    }

    protected function errorBag(array $errors)
    {
        $message = ["message" => implode(" ", $errors), "alert-type" => "error"];
        return $message;
    }

    public function add_event(Request $request)
    {
        $validate = $this->validateErrorMesage($request->all());
        if($validate->fails()){
            return back()->with($this->errorBag($validate->errors()->all()));
        }else{
            $roleEvent = $this->generate_event($request);

            $this->notify_by_mail($request->except('_token'));

            Notifications::create([
                'to' => Auth::user()->email,
                'type' => 'newEvent',
                'subject' => 'Raised Event!',
                'content' => $roleEvent->id,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
            return redirect('client/existing/event')->with(["message" => "Event Created Successfully", "alert-type" => "success"]);
        }
    }

    protected function notify_by_mail($request)
    {
        $mapped_marshals = MapRole::where('clientId', Auth::user()->id)
            ->join('users', 'map_roles.marshalId', '=', 'users.id')
            ->select('name', 'username', 'marshalId', 'email')
            ->groupBy('username')
            ->get();
        $mapped_vendor = MapRole::where('clientId', Auth::user()->id)
            ->join('users', 'map_roles.vendorId', '=', 'users.id')
            ->select('name', 'username', 'vendorId', 'email')
            ->groupBy('username')
            ->get();
        $additional_data = array(
            'client_name' => Auth::user()->name,
            'client_username' => Auth::user()->username,
            'client_email' => Auth::user()->email,
            'vendor_mail' => isset($mapped_vendor) ? $mapped_vendor->toArray() : '',
            'marshal_mail' => isset($mapped_marshals) ? $mapped_marshals->toArray() : '',
            'details' => $request
        );
        // dd($request->all(), $additional_data);
        if(isset($mapped_marshals)){
            foreach($mapped_marshals as $value){
                $this->sendInvitationMail('newEvent', $value->email, 'marshal', 'Raised Event!', $additional_data);
            }
        }
        if(isset($mapped_vendor)){
            foreach($mapped_vendor as $value){
                $this->sendInvitationMail('newEvent', $value->email, 'vendor', 'Raised Event!', $additional_data);
            }
        }
        $this->sendInvitationMail('newEvent', Auth::user()->email, 'client', 'Raised Event!', $additional_data);
        // $this->sendInvitationMail('newEvent', 'admin@gmail.com', 'admin', 'Raised Event!');
    }

    protected function generate_event($request)
    {
        $event_ticket = hexdec(uniqid());
        $ticket_exists = RolesEvent::where('event_ticket', $event_ticket)->first();
        // \Log::info($event_ticket);
        // \Log::info($ticket_exists);
        // \Log::info(!isset($ticket_exists));
        if(!isset($ticket_exists)){
            // dd($request->all());
            $name = $this->save_menu_suggestion($request->menu_suggest);
            return RolesEvent::create([
                'event_ticket' => $event_ticket,
                'client_id' => Auth::user()->id,
                'event_date' => strtotime(str_replace("/", "-", $request->reservation_date)),
                'guest_number' => $request->guest_num,
                'rate_per_plate' => $request->per_plate,
                'type_of_event' => $request->event_type,
                'decoration_needed' => $request->event_decoration,
                'status' => 'waiting',
                'cultry_crockery' => $request->cultry_crockery,
                'menu_suggest' => $name,
                'description' => $request->description
            ]);
        }else{
            $this->generate_event($request);
        }
    }

    protected function save_menu_suggestion($file){
        if(isset($file)){
            $name = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
            $extension = $file->getClientOriginalExtension();
            $storageName = $name . '_' . rand(10, 10000) . '.' . $extension;
            $store = $file->storeAs('public/vendor/suggestion/'.Auth::user()->id.'/', $storageName);
            return $storageName;
        }else{
            return null;
        }
    }

    public function viewOrEditEvent(string $type, int $id)
    {
        $event = RolesEvent::where('id', $id)->first();
        if($type == 'view'){
            return view('Client::event/view_event', compact('type', 'event'));
        }elseif($type == 'edit'){
            return view('Client::event/edit_event', compact('type', 'event'));
        }
    }

    public function updateEvent(Request $request)
    {
        $validate = $this->validateErrorMesage($request->all());
        if($validate->fails()){
            return back()->with($this->errorBag($validate->errors()->all()));
        }else{
            $name = $this->save_menu_suggestion($request->menu_suggest);
            RolesEvent::where([
                    'event_ticket' => $request->ticket,
                    'client_id' => Auth::user()->id
                ])
                ->update([
                    'event_date' => strtotime(str_replace("/", "-", $request->reservation_date)),
                    'guest_number' => $request->guest_num,
                    'rate_per_plate' => $request->per_plate,
                    'type_of_event' => $request->event_type,
                    'decoration_needed' => $request->event_decoration,
                    'cultry_crockery' => $request->cultry_crockery,
                    'menu_suggest' => $name,
                    'description' => $request->description
                ]);
            return redirect('client/existing/event')->with(["message" => "Event Updated Successfully", "alert-type" => "success"]);
        }
    }

    public function all_concerns(Request $request)
    {
        $concernType = "existing";
        if($request->all()){
            //dd($request->all());
          $shortparameter = $request->sorted;
          if($request->sorted == "allconcerns") {
            $concernList = RaiseConcern::where('clientId', Auth::user()->id)->get();
          } else {
            $concernList = RaiseConcern::where('clientId', Auth::user()->id)
                ->where('status', $request->sorted)
                ->get();
          }            
        }else{
            // dd("Raise Concern");
          $shortparameter = "allconcerns";
          $concernList = RaiseConcern::where('clientId', Auth::user()->id)->get();
        }
        return view('Client::raiseConcern', compact('concernType', 'concernList', 'shortparameter'));
    }

    public function concern()
    {
        $concernType = "raise";
        $vendorList = MapRole::where('clientId', Auth::user()->id)
                ->join('users', 'map_roles.vendorId', '=', 'users.id')
                ->select('name', 'username', 'vendorId', 'email')
                ->groupBy('username')
                ->get()->toArray();
        return view('Client::raiseConcern', compact('concernType', 'vendorList'));
    }

    public function generateConcern(Request $request)
    {
        //dd($request->all());
        $validate = Validator::make($request->all(), [
            'description' => 'required',
            'vendorName' => 'required',
            'comment' => 'required|min:5|max:300',
            'imageproof.*' => 'image|mimes:jpeg,jpg,png|max:1000',
            'videoproof.*' => 'array|mimes:mp4|max:10000',
        ]);
        if($validate->fails()){
            return back()->with($this->errorBag($validate->errors()->all()));
        }else{
          
            $vendor_info = User::where('email', $request->vendorName)->select('name', 'email', 'username')->first()->toArray();
            $mapped_marshals = MapRole::where('clientId', Auth::user()->id)
                            ->join('users', 'map_roles.marshalId', '=', 'users.id')
                            ->select('name', 'username', 'marshalId', 'email')
                            ->groupBy('username')
                            ->get()->toArray();
            // dd($mapped_marshals);
            $additional_data = array(
                'client_name' => Auth::user()->name,
                'client_username' => Auth::user()->username,
                'client_email' => Auth::user()->email,
                'vendor_name' => $vendor_info['name'],
                'vendor_username' => $vendor_info['username'],
                'vendor_email' => $vendor_info['email'],
                'marshal_mail' => $mapped_marshals,
                'content' => $request->comment
            );
            // dd($additional_data);
            $combineImageNames = [];
            // Loop over here for its mapped vendor and marshal and admin
            $this->sendInvitationMail('newConcern', Auth::user()->email, 'client', 'Raised Concern!', $additional_data);
            $this->sendInvitationMail('newConcern', $vendor_info['email'], 'vendor', 'Raised Concern!', $additional_data);
            $this->sendInvitationMail('newConcern', "pradeep@finchat.tech", 'vendor', 'Raised Concern!', $additional_data);
            
            // $this->sendInvitationMail('newConcern', 'admin@gmail.com', 'admin', 'Raised Concern!', $additional_data);
            foreach($mapped_marshals as $value){
                // dd($value);
                $this->sendInvitationMail('newConcern', $value['email'], 'marshal', 'Raised Concern!', $additional_data);
            }
            
            
            if(isset($request->imageproof)){
                foreach($request->imageproof as $image){
                    $name = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
                    $extension = $image->getClientOriginalExtension();
                    $storageName = $name . '_' . rand(10, 10000) . '.' . $extension;
                    $store = $image->storeAs('public/concerns/client/'.Auth::user()->id.'/', $storageName);
                    array_push($combineImageNames, $storageName);
                }
            }
            
            $concern = RaiseConcern::create([
                'clientId' => Auth::user()->id,
                'description' => $request->description,
                'vendorEmail' => $request->vendorName,
                'comment' => $request->comment,
                //'images' => isset($request->imageproof) ? (count($combineImageNames) > 1 ? implode(", ", $combineImageNames) : $combineImageNames) : null,
                'images' => implode(", ", $combineImageNames),
                'videos' => isset($request->videoproof) ? $request->videoproof : null,
                'status' => 'Processing',
                'created_at' => date('Y-m-d H:i:s')
            ]);
            Notifications::create([
                'to' => Auth::user()->email,
                'type' => 'newConcern',
                'subject' => 'Raised Concern!',
                'content' => $concern->clientId,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
            return back()->with(["message" => "Concern Raised Successfully", "alert-type" => "success"]);
        }
    }
    
    public function viewConcern(int $id)
    {
        $concernType = "viewRaised";
        $concern = RaiseConcern::where('raise_concerns.id', $id)
                    ->join('users as u1', 'raise_concerns.clientId', '=', 'u1.id')
                    ->join('users as u2', 'raise_concerns.vendorEmail', '=', 'u2.email')
                    ->select('raise_concerns.id', 'clientId', 'description', 'vendorEmail', 'status', 'comment', 'images', 'videos', 'u1.email', 'u1.username as client_username', 'u2.username as vendor_username', 'u2.name as vendor_name')
                    ->first();
        // dd($concern);
        $messages = ConcernMessage::where('concern_id', $id)
                        ->where('status', '!=', 'closed')
                        ->orderBy('created_at')->get();
        // dd($messages);
        return view('Client::raiseConcern', compact('concernType', 'concern', 'messages'));
    }
    
    public function closeConcern(int $id)
    {
        $concernType = "closeRaised";
        $concern = DB::table('raise_concerns')
              ->where('id', $id)
              ->update(['status' => "Resolved"]);
        return back()->with(["message" => "Rasied Concern Resolved!!", "alert-type" => "success"]);
    }

    public function concernMessageInput(Request $request)
    {
        \Log::info($request->all());
        try{
            $concern_msg = new ConcernMessage;
            $concern_msg->concern_id = $request->id;
            $concern_msg->status = $request->status;
            $concern_msg->sender = Auth::user()->username;
            $concern_msg->messages = $request->message;
            $concern_msg->save();
            return response()->json([
                'success' => 'Concern Message Saved Successfully!'
            ]);
        }
        catch(Exception $e){
            \Log::info($e);
        }
    }

    public function viewVendorMenu(int $vendorId=null)
    {
        // dd("Containing Menu Vendor List");
        if($vendorId == null)
        {
            $allVendors = MapRole::where('clientId', Auth::user()->id)
            ->join('users', 'map_roles.vendorId', '=', 'users.id')
            // ->join('meal_menus', 'map_roles.vendorId', '=', 'meal_menus.vendorId')
            ->select('name', 'username', 'email', 'contactNumber', 'address', 'map_roles.vendorId')
            ->groupBy('username')
            ->get();

            foreach($allVendors as $vendor){
                // dd($vendor);
                $meal_status = MealMenu::where('vendorId', $vendor->vendorId)
                ->where('clientId', Auth::user()->id)
                ->select('client_meal_status')
                ->orderBy('id', 'DESC')
                ->first();
                $vendor->meal_status = isset($meal_status) ? $meal_status->client_meal_status : 'pending';
            }
            // dd($allVendors);
            return view('Client::vendorMenu', compact('allVendors'));
        }
        else
        {
            // dd("VendorId: ", $vendorId);
            $menu = MealMenu::where('vendorId', $vendorId)->where('clientId', Auth::user()->id)->orderBy('id', 'DESC')->first();
            $vendorDetails = User::where('id', $vendorId)->select('id', 'name', 'username', 'email')->first();
            // dd($menu);
            return view('Client::vendorMenu', compact('menu', 'vendorDetails', 'vendorId'));
        }
    }

    public function viewVendorDocuments(string $type=null, int $vendorId=null)
    {
        // dd("Containing Documents Vendor List");
        if($vendorId == null)
        {
            $allVendors = MapRole::where('clientId', Auth::user()->id)
                ->join('users', 'map_roles.vendorId', '=', 'users.id')
                ->join('vendors', 'users.id', '=', 'vendors.vendorId')
                ->select(
                    'name',
                    'contactName',
                    'users.username',
                    'users.email',
                    'contactNumber',
                    'address',
                    'map_roles.vendorId',
                    'map_roles.vendor_doc_status'
                )
                ->get();
            // dd($allVendors);
            return view('Client::vendorDocument', compact('allVendors'));
        }
        else
        {
            // dd("VendorId: ". $vendorId);
            if($type == "document"){
                $document_list = VendorDocs::where('vendorId', $vendorId)->first();
                $vendor_doc_status = MapRole::where('clientId', Auth::user()->id)
                    ->where('vendorId', $vendorId)
                    ->select('vendor_doc_status')
                    ->first();
                // dd($document_list, $vendor_doc_status);
                return view('Client::vendorDocument', compact('document_list', 'vendorId', 'vendor_doc_status'));
            }elseif($type == "detail"){
                // dd("detail");
                $user = User::where('id', $vendorId)
                    ->select('id', 'name', 'email', 'username', 'contactNumber', 'address')
                    ->first()->toArray();
                $role['foodscraftRole'] = User::find($vendorId)->getRoleNames()->toArray()[0];
                $details = Vendor::where([
                        ['vendorId', '=', $user['id']],
                        ['username', '=', $user['username']]
                    ])->first()->toArray();
                $result = array_merge($user, array_merge($details, $role));
                $type = "view";
                $docs = [];
                $docs['documents'] = VendorDocs::where('vendorId', $result['vendorId'])->get()->toArray();
                $result = array_merge($result, $docs);
                return view("Client::vendor_detail", compact('result', 'type'));
            }
        }
    }

    public function changeStatus(Request $request)
    {
        \Log::info($request->all());
        try{
            $map_role = MapRole::where('vendorId', $request->vendorId)
                    ->where('clientId', Auth::user()->id)
                    ->update([
                        'vendor_doc_status' => $request->status,
                        'vendor_doc_comment' => isset($request->vendor_doc_comment) ? $request->vendor_doc_comment : null
                    ]);
            // $this->status_mail($request->status);
            return response()->json([
                'success' => 'Status Saved Successfully!'
            ]);
        }
        catch(Exception $e){
            \Log::info($e);
        }
    }

    public function changeMealStatus(Request $request)
    {
        \Log::info("Change Meal Status");
        \Log::info($request->all());
        try{
            $add_context = MealMenu::where('vendorId', $request->vendorId)
            ->where('clientId', Auth::user()->id)->first();
            \Log::info($add_context);
            $new_context = $add_context->client_meal_comment . ' ' . (isset($request->vendor_doc_comment) ? $request->vendor_doc_comment : null);
            \Log::info($new_context);
            $map_role = MealMenu::where('vendorId', $request->vendorId)
                    ->where('clientId', Auth::user()->id)
                    ->update([
                        'client_meal_status' => $request->status,
                        'client_meal_comment' => $new_context
                    ]);
            $this->status_mail($request->status);
            return response()->json([
                'success' => 'Status Saved Successfully!'
            ]);
        }
        catch(Exception $e){
            \Log::info($e);
        }
    }

    protected function status_mail($status)
    {
        if($status == 'approve'){
            // Mail
        }elseif($status == 'disapprove'){
            // Mail
        }
    }

    public function feedback()
    {
        $vendorList = MapRole::where('map_roles.clientId', Auth::user()->id)
        ->join('users', 'map_roles.vendorId', '=', 'users.id')
        ->get();

        foreach ($vendorList as $vendor){
            $vendor->meal_menu = MealMenu::where('clientId', $vendor->clientId)->where('vendorId', $vendor->vendorId)->exists();
        }

        // return view('Client::feedback', compact('vendorList'));
        return view('Client::feedback');
    }

    public function submitFeedback(Request $request)
    {
        \Log::info($request->all());
        $validate = Validator::make($request->all(), [
            'clientId' => 'required',
            'vendorId' => 'required',
            'reply' => 'min:2|max:150',
        ]);
        if($validate->fails()){
            // return back()->with($this->errorBag($validate->errors()->all()));
            return response()->json([
                'error' => 'Invalid Feedback!'
            ]);
        }else{
            $feedback = new Feedback;
            $feedback->clientId = Auth::user()->id;
            $feedback->vendorId = $request->vendorId;
            $feedback->reply = $request->reason;
            $feedback->created_at = date('Y-m-d H:i:s');
            $feedback->save();
            return response()->json([
                'success' => 'Feedback Saved Successfully!'
            ]);
        }
        
    }

    protected function marshalDetails($user) {
        return Marshal::where([
            ['marshalId', '=', $user['id']],
            ['username', '=', $user['username']]
        ]);
    }

    protected function userInfo($id) {
        return User::where('id', $id)
            ->select('id', 'name', 'email', 'username', 'contactNumber', 'address')
            ->first()->toArray();
    }

    public function marshal_detail(Request $request)
    {
        // dd($request->all());
        if($request->marshal_id){
            $id = $request->marshal_id;
            $user = $this->userInfo($id);
            $role['foodscraftRole'] = User::find($request->marshal_id)->getRoleNames()->toArray()[0];
            $details = [];
            $type = "view";
            $listMapfirst = [];
            $listMapfirstdata = [];
            $listMapsecond = [];
            $listMapseconddata = [];
            $details = $this->marshalDetails($user)->first()->toArray();
            // Fetch mapped vendor
            $listMapfirst = MapRole::where('marshalId', $id)->select('vendorId')->distinct('vendorId')->get()->toArray();
            // foreach ($listMapfirst as $listMapfirstitem) {
                // $listMapfirstdata[] = User::join('vendors', 'users.id', '=', 'vendors.vendorId')
                //         ->join('map_roles as mp1', 'map_roles.vendorId', '=', 'vendors.vendorId')
                //         ->join('map_roles as mp2', 'mp1.marshalId', '=', 'map_roles.marshalId')
                //         ->where('users.id', $listMapfirstitem['vendorId'])
                //         ->select()->get()->toArray();
                $listMapfirstdata[] = MapRole::where('map_roles.marshalId', (int) $request->marshal_id)
                    ->where('map_roles.clientId', Auth::user()->id)
                    ->join('users', 'map_roles.vendorId', '=', 'users.id')
                    ->join('vendors', 'map_roles.vendorId', '=', 'vendors.vendorId')
                    ->get()->toArray();
            // }
            // End
            // Fetch mapped client
            $listMapsecond = MapRole::where('marshalId', $id)->select('clientId')->distinct('clientId')->get()->toArray();
            foreach ($listMapsecond as $listMapseconditem) {
                $listMapseconddata[] = User::join('clients', 'users.id', '=', 'clients.clientId')
                        ->join('map_roles', 'map_roles.clientId', '=', 'clients.clientId')
                        ->where('users.id', $listMapseconditem['clientId'])
                        ->select()->get()->toArray();
            }
            $result = array_merge($user, array_merge($details, $role));
            if ($type == "view") {
                $docs = [];
                if ($role['foodscraftRole'] == "sitemarshal") {
                    $docs['documents'] = MarshalDocs::where('marshalId', $result['marshalId'])->get()->toArray();
                }
                $result = array_merge($result, $docs);
            }
            return view("Client::marshal_detail", compact('result', 'type', 'listMapfirstdata', 'listMapseconddata'));
        }
    }




    public function new_qr_generate_view()
    {
        // $clients = $this->common_icount_emp_value('no');
        $client = Client::where('clients.clientId', Auth::user()->id)
        ->join('users', 'clients.clientId', '=', 'users.id')
        ->select(
            'users.id as client_id',
            'name as client_name',
            'users.username as client_code',
            'contactName as contact_person',
            'contactNumber as client_number'
        )
        ->first();
        $last_qr_id = QRDetail::where('client_id', Auth::user()->id)
            ->orderBy('id', 'desc')
            ->select('qr_id')
            ->first();
        $last_qr_id = isset($last_qr_id) ? ++$last_qr_id->qr_id : 1;
        return view('Client::icount/generate_qr', compact('client', 'last_qr_id'));
    }

    protected function make_img_of_text($id, $client_id)
    {
        $text = $id . '_' . $client_id;
        // $img = Image::make(public_path('webImages/white_bg.jpg'));
        $img = Image::canvas(200, 200)->fill('rgba(255,245,255, 0.9)');
        $img->resize(200, 200);
        $img->text($text, 100, 100, function($font){
            $font->file(public_path('fontStyles/red_rose/RedRose-Bold.ttf'));
            $font->size(27);
            $font->color('#445160');
            $font->align('center');  
            $font->valign('middle');  
            $font->angle(0);  
        });
        $image = $img->save(public_path('storage/upload/client' . '/' . $text . '.jpg'));
        return $text;
    }

//    protected function qr_detail_generator($id, $client_id, $client_code, $qr_name){
//        $absolute_path = public_path() . '/' . "storage/upload/client" . '/' . $client_code . '/' . $qr_name;
//        $relative_path = asset('public/storage/upload/client') . '/' . $client_code . '/' . $qr_name;
//        $input = array("qr_id" => $id, "client_code" => $client_code, "client_id" => $client_id);
//        $sensitive_value = implode(', ', array_map(
//            function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
//            $input,
//            array_keys($input)
//        ));
//        // $merge_text_name = $this->make_img_of_text($id, $client_code);
//        QrCode::format('png')
//            // ->merge(asset('/public/storage/upload/client') . '/' . $merge_text_name . '.jpg', 0.3, true)
//            ->size(200)
//            ->generate($sensitive_value, $absolute_path);
//        // Storage::delete('public/upload/client'.'/'.$merge_text_name . '.jpg');
//        QRDetail::create([
//            'qr_id' => $id,
//            'client_id' => $client_id,
//            'client_code' => $client_code,
//            'qr_path' => $relative_path
//        ]);
//    }
    
     protected function qr_detail_generator($id, $client_id, $client_code, $meal_category, $qr_name)
    {
        $absolute_path = public_path() . '/' . "storage/upload/client" . '/' . $client_code . '/' . $qr_name;
        $relative_path = asset('public/storage/upload/client') . '/' . $client_code . '/' . $qr_name;
        $input = array("qr_id" => (int) $id, "client_code" => (string) $client_code, "client_id" => (int) $client_id);
        $sensitive_value = implode(', ', array_map(
            function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
            $input,
            array_keys($input)
        ));
        QrCode::format('png')
            ->size(200)
            ->generate($sensitive_value, $absolute_path);
        QRDetail::create([
            'qr_id' => $id,
            'client_id' => $client_id,
            'meal_category' => $meal_category,
            'client_code' => $client_code,
            'qr_path' => $relative_path
        ]);
    }

//    public function qr_code_generator(Request $request)
//    {
//        // dd($request->all());
//        $qr_created_or_not = Client::where('username', Auth::user()->username)->where('qr_code_status', 'no')->first();
//        $this->add_directory(public_path() . '/' . "storage/upload/client" . '/' . Auth::user()->username);
//        // dd($qr_created_or_not);
//        if(isset($qr_created_or_not)){
//            for ($x = $request->qr_id; $x <= $request->qr_code_limit; $x++) {
//                $qr_name = $x . '_' . Auth::user()->username . '.png';
//                $this->qr_detail_generator($x, $request->client_id, Auth::user()->username, $qr_name);
//            }
//        }else{
//            $increment = $request->qr_id;
//            for ($x = 1; $x <= $request->qr_code_limit; $x++) {
//                $qr_name = $increment . '_' . Auth::user()->username . '.png';
//                $this->qr_detail_generator($increment, $request->client_id, Auth::user()->username, $qr_name);
//                ++$increment;
//            }
//        }
//        // SWITCH VALUE TO yes IN Client's TABLE
//        Client::where('clientId', $request->client_id)->update(['qr_code_status' => 'yes']);
//        return redirect('client/ICount/I-count/client_success_qr_generate');
//    }
    
    public function qr_code_generator(Request $request)
    {
        // dd($request->all());
        $validator = Validator::make($request->all(), [
            'qr_code_limit' => 'required|numeric|min:1',
            'qr_code_type' => 'required|string|max:25',
        ]);
        // dd($validator->fails());
        if(isset($validator) && $validator->fails()){
            return back()->with($this->errorBag($validator->errors()->all()))->withInput();
        }else{
            $qr_created_or_not = Client::where('username', Auth::user()->username)->where('qr_code_status', 'no')->first();
            $this->add_directory(public_path() . '/' . "storage/upload/client" . '/' . Auth::user()->username);
            if(isset($qr_created_or_not)){
                for ($x = $request->qr_id; $x <= $request->qr_code_limit; $x++) {
                    $qr_name = $x . '_' . Auth::user()->username . '_' . $request->qr_code_type . '.png';
                    $this->qr_detail_generator($x, $request->client_id, Auth::user()->username, $request->qr_code_type, $qr_name);
                }
            }else{
                $increment = $request->qr_id;
                for ($x = 1; $x <= $request->qr_code_limit; $x++) {
//                    ++$increment;
                    $qr_name = $increment . '_' . $request->client_code . '_' . $request->qr_code_type . '.png';
                    $this->qr_detail_generator($increment, $request->client_id, Auth::user()->username, $request->qr_code_type, $qr_name);
                    ++$increment;
                }
            }
            // SWITCH VALUE TO yes IN Client's TABLE
            Client::where('clientId', $request->client_id)->update(['qr_code_status' => 'yes']);
            return redirect('client/ICount/I-count/client_success_qr_generate');
        }
    }

    public function success_qr_generate()
    {
        $all_qr_codes = QRDetail::where('client_code', Auth::user()->username)
            ->select('qr_path')->get();
        return view('Admin::icount/success_qr_generate', compact('all_qr_codes'))
            ->with("message", 'QR Codes are successfully generated. Please download your new generated qr as following. Create employees of '. Auth::user()->username .' client to assign them!');
    }
    
    public function client_qr_code()
    {
        $all_qr_codes = QRDetail::where('client_code', Auth::user()->username)
            ->select('qr_path')->get();
        return view('Admin::icount/client_all_qr_code', compact('all_qr_codes'))
            ->with("message", 'QR Codes are successfully generated. Please download your new generated qr as following. Create employees of '. Auth::user()->username .' client to assign them!');
    }

    public function add_directory($directory) {
        if(!File::exists($directory)){
            File::makeDirectory($directory, 0777, true);
        }
    }
    
    public function client_emp_type4_view_list(Request $request, $search=null){
      //$client_code = $request->client_code;
      //$client = $request->all();
      $client = array();
      $client["client_id"] = Auth::user()->id;
      $client["client_code"] = Auth::user()->username;
      $client["qr_type"] = "type4";
      $clintid = Auth::user()->id;
      $client_code = Auth::user()->username;
      $qr_type = "type4";
      if($request->ajax()){
          $qr_type = "type4";
          $data = ClientsEmp::where('clients_emps.client_id', $clintid)
              ->join('qr_code_details', function($join) use($client_code){
                  $join->on('clients_emps.id', '=', 'qr_code_details.assigned_emp_id')
                  ->on('clients_emps.client_code', '=', 'qr_code_details.client_code');
              })
              ->where('clients_emps.client_code', $client_code)
              ->where('clients_emps.emp_name', 'LIKE', "%{$search}%");
          if($qr_type){
              $data->where('qr_code_details.meal_category', 'type4');
          }
          $employees = $data->paginate(50);
          return $employees;
      }
      return view('Client::icount/dining-report/client_emp_type4_view_list', compact('client', 'qr_type'));
    }
    
    public function client_emp_cal_report(Request $request)
    {
      $client_emp = ClientsEmp::with('client')->where('client_id', $request->client_id)
          ->where('emp_id', $request->emp_id)->first();
      return view('Client::icount/dining-report/client_emp_cal_report', compact('client_emp'));
    }
    
    public function getEmpCalReport(Request $request){
        // dd($request->client_id);
        $clientDataPP = Client::select('clientname', 'username')->where('clientId', $request->client_id)->first();
        $employee = ClientsEmp::with('client')->where('emp_id', $request->emp_id)->first();
        $report_data = Type4QrScanDetail::where('emp_id', $request->emp_database_id)
            ->where('client_id', $request->client_id)
            ->whereBetween('created_at', [$request->date_from." 00:00:00", $request->date_to." 23:59:59"])
           ->get();
        foreach($report_data as $key => $data){
          $vendorid = isset($data->vendor_id) ? $data->vendor_id : '';
        }
        if(!empty($vendorid)){
          $vendorDataPP = User::select('name', 'username', 'address')->where('id', $vendorid)->first();
        }else{
            $vendor = MapRole::select('vendorId')->where('clientId', $request->client_id)->first();
            $vendorDataPP = User::select('name', 'username', 'address')->where('id', $vendor->vendorId)->first();
        }
        $date_from = $request->date_from;
        $date_to = $request->date_to;
        $bmivalue = $employee['emp_height']== null || $employee['emp_weight'] == null ? 'No Data': round($employee['emp_weight']/(($employee['emp_height']/100) *($employee['emp_height']/100)),2);
        $bmicategory = '';
        if($bmivalue == 'No Data'){
            $bmicategory = 'No Data';
        }
        else if ( $bmivalue < 18.5){
            $bmicategory = 'Under Weight';
        }
        else if ( $bmivalue >= 18.5 && $bmivalue <=24.9){
            $bmicategory = 'Normal Weight';
        }
        else if ( $bmivalue >= 25 && $bmivalue <=30){
            $bmicategory = 'Over Weight';
        }
        else if ( $bmivalue > 30){
            $bmicategory = 'Obese';
        }
        $bmi = $bmivalue . ' ('.$bmicategory.')';
        return view('Client::icount/dining-report/client_emp_cal_report_data', compact('report_data', 'employee', 'date_from', 'date_to', 'clientDataPP', 'vendorDataPP','bmi','bmivalue'));
    }
    
    public function client_all_emp_cal_report(Request $request)
    {
        if($request->isMethod('get')){
            //dd("get");
                $client = (object) $request->all();
                return view('Client::icount/dining-report/client_emp_type4_view_list', compact('client'));
            }
      $clientdata = Client::select('clientname', 'clientId')->where('clientId', $request->client_id)
          ->first();
      return view('Client::icount/dining-report/client_all_emp_cal_report', compact('clientdata'));
    }
    
    public function getClientEmployeesCal(Request $request){
        $clientDataPP = Client::select('clientname', 'username')->where('clientId', $request->client_id)->first();
        // $report_data = Type4QrScanDetail::where('client_id', $request->client_id)
        //         ->whereBetween('created_at', [$request->date_from." 00:00:00", $request->date_to." 23:59:59"])
        //         ->get();
        $report_data = Type4QrScanDetail::where('client_id', $request->client_id)
            ->whereBetween('created_at', [$request->date_from." 00:00:00", $request->date_to." 23:59:59"])
            ->select('id', 'client_id', 'vendor_id', 'qr_type', 'item_quantity',
                'emp_id', 'item_total_price',
                DB::raw("DATE(created_at) as date,sum(CASE
                    WHEN meal_type = 'breakfast' THEN item_approx_calorie*item_quantity
                    ELSE 0
                    END) as sum_breakfast, 
                    sum(CASE
                    WHEN meal_type = 'lunch' THEN item_approx_calorie*item_quantity
                    ELSE 0
                    END) as sum_lunch,
                    sum(CASE
                    WHEN meal_type = 'dinner' THEN item_approx_calorie*item_quantity
                    ELSE 0
                    END) as sum_dinner,
                    sum(CASE
                    WHEN meal_type = 'others' THEN item_approx_calorie*item_quantity
                    ELSE 0
                    END) as sum_others,
                    GROUP_CONCAT(DISTINCT 
                        @item_name := (CASE
                            WHEN meal_type = 'breakfast' THEN concat(item_name,' (',item_quantity,') (',item_approx_calorie,' calories)')
                            ELSE ''
                            END
                        ) SEPARATOR ', ') as breakfast,
                    GROUP_CONCAT(DISTINCT 
                        @item_name := (CASE
                            WHEN meal_type = 'lunch' THEN concat(item_name,' (',item_quantity,') (',item_approx_calorie,' calories)')
                            ELSE ''
                            END
                        ) SEPARATOR ', ') as lunch,
                    GROUP_CONCAT(DISTINCT 
                        @item_name := (CASE
                            WHEN meal_type = 'dinner' THEN concat(item_name,' (',item_quantity,') (',item_approx_calorie,' calories)')
                            ELSE ''
                            END
                        ) SEPARATOR ', ') as dinner,
                    GROUP_CONCAT(DISTINCT 
                        @item_name := (CASE
                            WHEN meal_type = 'others' THEN concat(item_name,' (',item_quantity,') (',item_approx_calorie,' calories)')
                            ELSE ''
                            END
                        ) SEPARATOR ', ') as others"))
                ->groupBY('emp_id')->orderBy('date')->get();
        foreach($report_data as $key => $data){
          $vendorid = isset($data->vendor_id) ? $data->vendor_id : '';
        }
        if(!empty($vendorid)) {
          $vendorDataPP = User::select('name', 'username', 'address')->where('id', $vendorid)->first();
        }else{
            $vendorDataPP = '';
        }
        $date_from = $request->date_from;
        $date_to = $request->date_to;
        $client = Client::find($request->client_id);

        return view('Client::icount/dining-report/get_client_employees_cal_report', compact('client', 'report_data', 'clientDataPP', 'vendorDataPP', 'date_from', 'date_to'));
    }

    public function emp_list()
    {
        $employees = ClientsEmp::where('client_id', Auth::user()->id)
            ->where('client_code', Auth::user()->username)
            ->get();
        // dd($employees);
        return view('Client::icount/emp_view_list', compact('employees'));
    }

    public function add_emp_view(Type $var = null)
    {
        $avail_qr_code = QRDetail::where('assigned_emp_id', null)->where('client_code', Auth::user()->username)->get();
        return view('Client::icount/assign_qr', compact('avail_qr_code'));
    }

    public function add_emp(Request $request)
    {
        // dd($request->all());
        $validate = Validator::make($request->all(), [
            'client_id' => 'required|numeric',
            'client_code' => 'required|string|max:150',
            'emp_name' => 'required|string|max:150',
            'emp_id' => 'required|numeric',
            'designation' => 'required|string|max:150'
        ]);
        if (isset($validate) && $validate->fails()) {
            return redirect('client/ICount/I-count/emp_list')->with($this->errorBag($validate->errors()->all()));
        } else {
            $client_emp_id = ClientsEmp::create([
                'client_id' => $request->client_id,
                'client_code' => $request->client_code,
                'emp_name' => $request->emp_name,
                'emp_id' => $request->emp_id,
                'designation' => $request->designation,
                'assign_qr_status' => isset($request->avail_qr_code) ? 'yes' : 'no',
                'emp_height' => $request->height,
                'emp_weight' => $request->weight,
            ]);
            // dd($client_emp_id);
            if(isset($request->avail_qr_code)){
                QRDetail::where('client_code', $request->client_code)
                    ->where('qr_id', $request->avail_qr_code)
                    ->update(['assigned_emp_id' => $client_emp_id->id]);
            }
            return redirect('client/ICount/I-count/emp_list')->with(["message" => "Employee Created Successfully", "alert-type" => "success"]);
        }
    }

    public function edit_emp(Request $request)
    {
        $qr_detail = null;
        $client_emp = ClientsEmp::where('client_id', $request->client_id)
            ->where('id', $request->id)->first();
        if($client_emp->assign_qr_status == 'yes'){
            $qr_detail = QRDetail::where('client_code', Auth::user()->username)
                ->where('assigned_emp_id', $request->id)->first();
        }
        $avail_qr_code = QRDetail::where('assigned_emp_id', null)->where('client_code', Auth::user()->username)->get();
        return view('Client::icount/client_emp_edit_list', compact('client_emp', 'qr_detail', 'avail_qr_code'));
    }

    public function update_emp(Request $request)
    {
        // dd($request->all());
        $validate = Validator::make($request->all(), [
            'client_id' => 'required|numeric',
            'client_code' => 'required|string|max:150',
            'emp_name' => 'required|string|max:150',
            'emp_id' => 'required|numeric',
            'designation' => 'required|string|max:150',
            // 'avail_qr_code' => 'required|numeric'
        ]);
        if (isset($validate) && $validate->fails()) {
            return redirect('client/ICount/I-count/emp_list')->with($this->errorBag($validate->errors()->all()));
        } else {
            // if($request->assign_qr_status == "yes"){
            //     QRDetail::where('client_code', $request->client_code)
            //         ->where('assigned_emp_id', $request->client_emp_id)
            //         ->update(['assigned_emp_id' => null]);
            // }
            ClientsEmp::where('client_id', $request->client_id)
                ->where('id', $request->client_emp_id)
                ->update([
                    'emp_name' => $request->emp_name,
                    'emp_id' => $request->emp_id,
                    'designation' => $request->designation,
                    // 'assign_qr_status' => isset($request->avail_qr_code) ? 'no' : 'yes',
                    'emp_height' => $request->height,
                    'emp_weight' => $request->weight
                ]);
            // if(isset($request->avail_qr_code)){
            //     QRDetail::where('client_code', $request->client_code)
            //         ->where('qr_id', $request->avail_qr_code)
            //         ->update(['assigned_emp_id' => $request->client_emp_id]);
            //     ClientsEmp::where('client_id', $request->client_id)
            //         ->where('id', $request->client_emp_id)
            //         ->update(['assign_qr_status' => 'yes']);
            // }
            return redirect('client/ICount/I-count/emp_list')->with(["message" => "Employee Updated Successfully", "alert-type" => "success"]);
        }
    }

    public function delete_emp(Request $request)
    {
        QRDetail::where('client_code', $request->client_code)
            ->where('assigned_emp_id', $request->id)
            ->update(['assigned_emp_id' => null]);
        ClientsEmp::where('client_id', $request->client_id)
            ->where('client_code', $request->client_code)
            ->where('id', $request->id)
            ->where('emp_id', $request->emp_id)
            ->delete();
        return redirect('client/ICount/I-count/emp_list')->with(["message" => "Employee Deleted Successfully", "alert-type" => "success"]);
    }

    public function view_invoice(Request $request)
    {
      $clientuser = auth()->user();
      $invoices = Invoice::where('invoices.client_code', Auth::user()->username)
          ->join('users', 'invoices.client_code', '=', 'users.username')
          ->select('invoices.*', 'users.name as client_name')
          ->paginate(5);
      $client = DB::table('clients')
          ->select('clientId', 'clientname', 'username', 'contactName')
          ->where('clientId', '=', $clientuser->id)     
          ->first();
      return view('Client::icount/invoice/generate_invoice', compact('invoices', 'client'));
    }
    
    public function generate_invoice(Request $request)
    {
      $from = "";
      $to = "";
      $dates = "";
      $data = MealCountDetail::where('client_code', $request->client_code);
      if($request->qr_type != 'all'){
          $data->where('qr_type', $request->qr_type);
      }
      if(!isset($request->date_from) && !isset($request->date_to)){
          $time = Carbon::now();
          $data->where('date', $time->toDateString())
              ->orderBy('date', 'asc');
      }
      elseif(isset($request->date_from) && !isset($request->date_to)){
          $data->where('date', '>=', $request->date_from)
              ->orderBy('date', 'asc');
      }
      elseif(!isset($request->date_from) && isset($request->date_to)){
          $data->where('date', '<=', $request->date_to)
              ->orderBy('date', 'asc');
      }
      elseif(isset($request->date_from) && isset($request->date_to)){
          $data->whereBetween('date', [$request->date_from, $request->date_to])
              ->orderBy('date', 'asc');
      }
      $dates = $data->get();
      $client_detail = (object) $request->all();
      if(!empty($request->date_from)) {
        $date_from = $request->date_from;
      }
      if(!empty($request->date_to)) {
        $date_to = $request->date_to;
      }
      return view('Client::icount/invoice/get_client_invoice', compact('dates', 'client_detail', 'date_from', 'date_to'));
    }

    public function export_invoice(Request $request)
    {
        $from = "";
        $to = "";
        $dates = "";
        if(!isset($request->date_from) && !isset($request->date_to)){
            $time = Carbon::now();
            $dates = MealCountDetail::where('client_code', Auth::user()->username)
                ->where('date', $time->toDateString())
                ->join('users', 'meal_count_details.client_code', '=', 'users.username');
        }
        elseif(isset($request->date_from) && !isset($request->date_to)){
            $dates = MealCountDetail::where('client_code', Auth::user()->username)
                ->where('date', '>=', $request->date_from)
                ->join('users', 'meal_count_details.client_code', '=', 'users.username');
        }
        elseif(!isset($request->date_from) && isset($request->date_to)){
            $dates = MealCountDetail::where('client_code', Auth::user()->username)
                ->where('date', '<=', $request->date_to)
                ->join('users', 'meal_count_details.client_code', '=', 'users.username');
        }
        elseif(isset($request->date_from) && isset($request->date_to)){
            $dates = MealCountDetail::where('client_code', Auth::user()->username)
                ->whereBetween('date', [$request->date_from, $request->date_to])
                ->join('users', 'meal_count_details.client_code', '=', 'users.username');
        }
        $dates = $dates->select(
                            'users.name',
                            'meal_count_details.client_code',
                            'meal_count_details.meal_type',
                            'meal_count_details.meal_rate',
                            'meal_count_details.meal_count',
                            'meal_count_details.total',
                            'meal_count_details.date'
                        )
                    ->orderBy('date', 'asc')
                    ->get();
        $fetch_invoice = Invoice::where('id', $request->invoice_id)
            ->where('client_code', Auth::user()->username)
            ->first();
        $empty = ['', '', '', '', '', '', ''];
        $dates->push($empty);
        $invoice_info = ['', '', 'Total Sum', $fetch_invoice->meal_rate_total, $fetch_invoice->meal_count_total, $fetch_invoice->total, $fetch_invoice->created_at];
        $dates->push($invoice_info);
        // dd($request->all(), $dates, $fetch_invoice, $dates->toArray());
        $export = new InvoiceExport([$dates->toArray()]);
        // dd($export);
        $filename = Auth::user()->username . "_" . $request->date_from . '_' . $request->date_from . '.xlsx';
        return Excel::download($export, $filename);
    }
    
    public function notifications()
    {
        $notifications = Notifications::where('to', Auth::user()->email)
            ->orderBy('created_at', 'desc')->paginate(5);
        // dd($notifications);
        return view('Client::notifications', compact('notifications'));
    }
    
    
    public function view_report(Request $request)
    {
      $clientuser = auth()->user();
      $invoices = Invoice::where('invoices.client_code', Auth::user()->username)
          ->join('users', 'invoices.client_code', '=', 'users.username')
          ->select('invoices.*', 'users.name as client_name')
          ->paginate(5);
      $client = DB::table('clients')
          ->select('clientId', 'clientname', 'username', 'contactName')
          ->where('clientId', '=', $clientuser->id)     
          ->first();
      return view('Client::icount/report/generate_report', compact('invoices', 'client'));
    }
    
    public function generate_report(Request $request)
    {
      $from = "";
      $to = "";
      $dates = "";
      //$data = MealCountDetail::where('client_code', $request->client_code);
      $data = QRScanDetail::where('client_code', $request->client_code);
      if($request->qr_type != 'all'){
          //$data->where('qr_type', $request->qr_type);
        $data->where('meal_category', $request->qr_type);
      }
      if(!isset($request->date_from) && !isset($request->date_to)){
          $time = Carbon::now();
          $data->where('date', $time->toDateString())
              ->orderBy('date', 'asc');
      }
      elseif(isset($request->date_from) && !isset($request->date_to)){
          $data->where('date', '>=', $request->date_from)
              ->orderBy('date', 'asc');
      }
      elseif(!isset($request->date_from) && isset($request->date_to)){
          $data->where('date', '<=', $request->date_to)
              ->orderBy('date', 'asc');
      }
      elseif(isset($request->date_from) && isset($request->date_to)){
          $data->whereBetween('date', [$request->date_from, $request->date_to])
              ->orderBy('date', 'asc');
      }
      $dates = $data->get();
      $client_detail = (object) $request->all();
      if(!empty($request->date_from)) {
        $date_from = $request->date_from;
      }
      if(!empty($request->date_to)) {
        $date_to = $request->date_to;
      }
      return view('Client::icount/report/get_client_report', compact('dates', 'client_detail', 'date_from', 'date_to'));
    }

    public function export_report(Request $request)
    {
        $from = "";
        $to = "";
        $dates = "";
        if(!isset($request->date_from) && !isset($request->date_to)){
            $time = Carbon::now();
            $dates = MealCountDetail::where('client_code', Auth::user()->username)
                ->where('date', $time->toDateString())
                ->join('users', 'meal_count_details.client_code', '=', 'users.username');
        }
        elseif(isset($request->date_from) && !isset($request->date_to)){
            $dates = MealCountDetail::where('client_code', Auth::user()->username)
                ->where('date', '>=', $request->date_from)
                ->join('users', 'meal_count_details.client_code', '=', 'users.username');
        }
        elseif(!isset($request->date_from) && isset($request->date_to)){
            $dates = MealCountDetail::where('client_code', Auth::user()->username)
                ->where('date', '<=', $request->date_to)
                ->join('users', 'meal_count_details.client_code', '=', 'users.username');
        }
        elseif(isset($request->date_from) && isset($request->date_to)){
            $dates = MealCountDetail::where('client_code', Auth::user()->username)
                ->whereBetween('date', [$request->date_from, $request->date_to])
                ->join('users', 'meal_count_details.client_code', '=', 'users.username');
        }
        $dates = $dates->select(
                            'users.name',
                            'meal_count_details.client_code',
                            'meal_count_details.meal_type',
                            'meal_count_details.meal_rate',
                            'meal_count_details.meal_count',
                            'meal_count_details.total',
                            'meal_count_details.date'
                        )
                    ->orderBy('date', 'asc')
                    ->get();
        $fetch_invoice = Invoice::where('id', $request->invoice_id)
            ->where('client_code', Auth::user()->username)
            ->first();
        $empty = ['', '', '', '', '', '', ''];
        $dates->push($empty);
        $invoice_info = ['', '', 'Total Sum', $fetch_invoice->meal_rate_total, $fetch_invoice->meal_count_total, $fetch_invoice->total, $fetch_invoice->created_at];
        $dates->push($invoice_info);
        // dd($request->all(), $dates, $fetch_invoice, $dates->toArray());
        $export = new InvoiceExport([$dates->toArray()]);
        // dd($export);
        $filename = Auth::user()->username . "_" . $request->date_from . '_' . $request->date_from . '.xlsx';
        return Excel::download($export, $filename);
    }
    
    
    public function give_qr_type_detail($qr_type=null, $client_code=null)
    {
        if(isset($qr_type)){
            $qr_codes = QRDetail::where('assigned_emp_id', null)
                ->where('client_code', $client_code)
                ->where('meal_category', $qr_type)
                ->get();
            return $qr_codes;
        }
    }
    
    
    //Dine In Sale Report
    public function alldiningsalereport(Request $request){
      $allClients = MapRole::where('clientId', Auth::user()->id)
                ->join('users', 'map_roles.vendorId', '=', 'users.id')
                ->join('vendors', 'users.id', 'vendors.vendorId')
                ->select(
                    'name',
                    'users.username',
                    'email',
                    'contactNumber',
                    'address',
                    'map_roles.vendorId',
                    'vendors.contactName'
                )
                ->get();
      return view('Client::icount/icount-dining-sale-report/alldiningsalereport', compact('allClients'));
    }
    
    public function generate_diningsale_report(Request $request)
    {
        // dd($request->all(), $request->isMethod('get'), $request->isMethod('post'));
        if($request->isMethod('get')){
          //dd("get");
            $client = (object) $request->all();
            return view('Client::icount/icount-dining-sale-report/generate_dining_report', compact('client'));
        }elseif($request->isMethod('post')){
          $vendorDataPP = Vendor::select('vendorname', 'username')->where('vendorId', $request->client_id)->first();
        // $report_data = Type4QrScanDetail::where('vendor_id', $request->client_id)
        //         ->whereBetween('created_at', [$request->date_from." 00:00:00", $request->date_to." 23:59:59"])
        //         ->get();
        $report_data = Type4QrScanDetail::where('vendor_id', $request->client_id)
            ->whereBetween('created_at', [$request->date_from." 00:00:00", $request->date_to." 23:59:59"])
            ->select('id', 'client_id', 'vendor_id', 'qr_type', 'item_quantity',
                'emp_id', 'item_total_price',
                DB::raw("DATE(created_at) as date,sum(CASE
                            WHEN meal_type = 'breakfast' THEN item_total_price
                            ELSE 0
                            END) as sum_price_breakfast, 
                            sum(CASE
                            WHEN meal_type = 'lunch' THEN item_total_price
                            ELSE 0
                            END) as sum_price_lunch,
                            sum(CASE
                            WHEN meal_type = 'dinner' THEN item_total_price
                            ELSE 0
                            END) as sum_price_dinner,
                            sum(CASE
                            WHEN meal_type = 'others' THEN item_total_price
                            ELSE 0
                            END) as sum_price_others,
                    GROUP_CONCAT(DISTINCT 
                        @item_name := (CASE
                            WHEN meal_type = 'breakfast' THEN concat(item_name,' (',item_quantity,' Quantity)(',item_price,' Rs)')
                            ELSE ''
                            END
                        ) SEPARATOR ', ') as breakfast,
                    GROUP_CONCAT(DISTINCT 
                        @item_name := (CASE
                            WHEN meal_type = 'lunch' THEN concat(item_name,' (',item_quantity,' Quantity)(',item_price,' Rs)')
                            ELSE ''
                            END
                        ) SEPARATOR ', ') as lunch,
                    GROUP_CONCAT(DISTINCT 
                        @item_name := (CASE
                            WHEN meal_type = 'dinner' THEN concat(item_name,' (',item_quantity,' Quantity)(',item_price,' Rs)')
                            ELSE ''
                            END
                        ) SEPARATOR ', ') as dinner,
                    GROUP_CONCAT(DISTINCT 
                        @item_name := (CASE
                            WHEN meal_type = 'others' THEN concat(item_name,' (',item_quantity,' Quantity)(',item_price,' Rs)')
                            ELSE ''
                            END
                        ) SEPARATOR ', ') as others"))
                ->groupBY('emp_id')->orderBy('date')->get();
        foreach($report_data as $key => $data){
          $clientid = isset($data->client_id) ? $data->client_id : '';
        }
        if(!empty($clientid)) {
          $clientDataPP = User::select('name', 'username', 'address')->where('id', $clientid)->first();
        }else{
            $clientDataPP='';
        }
//        echo "<pre>";
//        print_r($vendorDataPP);
//        echo "</pre>";
//        exit;
        $date_from = $request->date_from;
        $date_to = $request->date_to;
        // dd($report_data);
        $client = Client::find($request->client_id);

        return view('Client::icount/icount-dining-sale-report/get_dining_sale_report', compact('client', 'report_data', 'clientDataPP', 'vendorDataPP', 'date_from', 'date_to'));
            
        }
    }
    
    //Client Emp list for Sale Report
    public function client_emp_type4_sale_view_list(Request $request, $search=null){
      $client = array();
      $client["client_id"] = Auth::user()->id;
      $client["client_code"] = Auth::user()->username;
      $client["qr_type"] = "type4";
      $clintid = Auth::user()->id;
      $client_code = Auth::user()->username;
      $qr_type = "type4";
      if($request->ajax()){
          $qr_type = "type4";
          $data = ClientsEmp::where('clients_emps.client_id', $clintid)
              ->join('qr_code_details', function($join) use($client_code){
                  $join->on('clients_emps.id', '=', 'qr_code_details.assigned_emp_id')
                  ->on('clients_emps.client_code', '=', 'qr_code_details.client_code');
              })
              ->where('clients_emps.client_code', $client_code)
              ->where('clients_emps.emp_name', 'LIKE', "%{$search}%");
          if($qr_type){
              $data->where('qr_code_details.meal_category', 'type4');
          }
          $employees = $data->paginate(50);
          return $employees;
      }
      return view('Client::icount/dining-report/client_emp_type4_sale_view_list', compact('client', 'qr_type'));
    }
    
    //Client emp single sale report form
    public function client_emp_sale_report(Request $request)
    {
      $client_emp = ClientsEmp::with('client')->where('client_id', $request->client_id)
          ->where('emp_id', $request->emp_id)->first();
      return view('Client::icount/dining-report/client_emp_sale_report', compact('client_emp'));
    }
    
    //Generate single EMP sale report
    public function generate_emp_diningsale_report(Request $request)
    {
        // dd($request->all(), $request->isMethod('get'), $request->isMethod('post'));
        if($request->isMethod('get')){

        }elseif($request->isMethod('post')){
          //$vendorDataPP = Vendor::select('vendorname', 'username')->where('vendorId', $request->client_id)->first();
        $report_data = Type4QrScanDetail::where('emp_id', $request->emp_database_id)
                ->whereBetween('created_at', [$request->date_from." 00:00:00", $request->date_to." 23:59:59"])
                ->get();
        foreach($report_data as $key => $data){
          $clientid = isset($data->client_id) ? $data->client_id : '';
        }
        if(!empty($clientid)) {
          $clientDataPP = User::select('name', 'username', 'address')->where('id', $clientid)->first();
        }
//        echo "<pre>";
//        print_r($vendorDataPP);
//        echo "</pre>";
//        exit;
        $date_from = $request->date_from;
        $date_to = $request->date_to;
        $saleEmpName = $request->client_contact_name;
        // dd($report_data);
        $client = Client::find($request->client_id);

        return view('Client::icount/icount-dining-sale-report/get_emp_dining_sale_report', compact('client', 'report_data', 'clientDataPP', 'date_from', 'date_to', 'saleEmpName'));
            
        }
    }

    public function viewAIFeedVendor(Request $request){
        $user = json_decode(json_encode(auth()->user()),true);
        $vendorIds = DB::table('map_roles')->where('clientId',$user['id'])
                    ->select('vendorId')->get();
        $i=0;
        $vendorDetails=array();
        while($i<count($vendorIds)){
            $uservendor=(array)$vendorIds[$i];
            $id= $uservendor['vendorId'];
            $client = DB::table('vendors')
                            ->where('vendorId',$id)
                            ->select('id','vendorId','vendorName','contactName','cameraNumber')
                            ->get();
            $vendorDetails[$i] = $client[0];
            $i++;
        }
        return view('Client::aiVendorList',compact('vendorDetails'));
    }

    public function viewAIVendorCameraList(int $id){
        $user = json_decode(json_encode(auth()->user()),true);
        $cameraDetails = DB::table('vendor_cameras')
                        ->where('clientId',$user['id'])
                        ->where('vendorId',$id)
                        ->select('id','cameraId','vendorId','cameraLocation')
                        ->get();
        return view('Client::aiVendorCameraList',compact('cameraDetails'));
    }

    public function viewVendorAIFeeds(string $id){
        $feeds = AIFeed::where('cameraId',$id)
                    ->orderBy('id','DESC')
                    ->get();
        return view('Client::aifeedsvendorview',compact('feeds'));
    }

}
