<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Data;
use App\Models\Lead;
use Hash;
use Log;
class DataController extends Controller
{
    
    public function getWhatsappMsgId($number){
        
        $jsondata =[];
        $data = Data::where('from', $number)->get();
        $jsondata = $data;
        
        return response()->json(['success'=> true, 
        'message'=> 'Whatsapp on behalf of from number', 
        'data' =>$jsondata]);
    }

    public function receiveData(Request $request)
    {
        if(!is_null($request->all())) {
        $newData = Data::updateOrcreate(
            [ 'customerPhone' =>$request->customerPhone ],
            [
                'customerName' =>$request->customerName,
                'customerPhone' =>$request->customerPhone,
                'from' =>$request->from,
                'to' =>$request->to,
                'newLead' =>$request->newLead,
                'LeadSource' => 'Whatsapp'
                
            ]
        );
       }
        #return $newData->id;
        $data = Data::where(['id'=>$newData->id])->first();
        
        $jsondata= ['name'=>$data->customerName, 'email'=>'', 
        'phone'=>$data->customerPhone, 
        'country'=>'', 'username'=>$data->customerPhone, 
        'password'=>Hash::make($data->customerPhone)];
        
        //leads data entry

        $LeadsData = new Lead;
        $LeadsData->patient_name =  $data->customerName;
        $LeadsData->patient_phone = $data->customerPhone;
        $LeadsData->platform = 'Whatsapp';
        $LeadsData->save();  
        
       // Log::info($LeadsData);
        return response()->json(['message' => 'Data received and saved', 'LeadsData'=>$LeadsData], 200);
    }
    
    public function getWhatsapp(){
        
        $jsondata =[];
        $data = Data::all();
        $jsondata = $data;
        
        return response()->json(['success'=> true, 
        'message'=> 'All message', 
        'data' =>$jsondata]);
    }
    
}