<?php
namespace App\Http\Controllers;
use App\Models\MessageDate;
use App\Models\SAASACCNAV;
use App\Models\User;
use App\Models\DTMsgEXT;
use Illuminate\Support\Facades\Auth;
use App\Models\addgrp;
use App\Models\DefPhone;
use App\Models\profilegrpviewer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Models\SasAccount;
use App\Models\sasmsgconfig;
use App\Models\profileclientview;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use App\Models\prefUser;
use App\Models\userPrefrences;
use Illuminate\Support\Facades\DB;
use App\Models\Session as SessionModel;
use App\Models\templateMessages;
use App\Models\userMsgGroups;
use App\Models\userPrefBin;
use App\Models\dataCustomer;

use App\Models\defaultphone;
use App\Models\isLoginAcc;
use App\Models\logsending;
use App\Models\savemsgs;
Use App\Models\Session;
use App\Models\ReqDataStorData;

use App\Models\sasaccountnavigator;
use App\Models\SasAccNavigator;
use App\Models\tempmessagesview;
use Carbon\Carbon;
use DataCustomer as GlobalDataCustomer;
use Exception;
use Facade\FlareClient\Http\Response;
use Illuminate\Support\Facades\Http;

class SAASAddControllers extends Controller
{
    public $arrAccs;
    public $storedaccName;
    public function __construct()
    {
        $this->arrAccs = [];
        $this->storedaccName = "";
        
    }
    public function sessionView(){

    }
    public function dashboardindex(){

        $user = Auth::user();
        $columnid = $user->id;
        $rgrps = DB::table('addgrps')->where('idIdentity', $columnid)->count();
        $customers = DB::table('data_customers')->where('idIdentity', $columnid)->count();
        $messages =  DB::table('savemsgs')->where('idIdentity', $columnid)->count();
        
return view('index', ['groups' => $rgrps, 'customers' => $customers, 'messages'=> $messages]);

    }
   
    public function store(Request $request)
    {

        $mname = $request->mname;
        $validatedData = $request->validate([
        
            'name' => 'required|string|max:255',
            'password' => 'required|string|max:255',
            'adminName' => 'required|string|max:255',
        ]);
        $user = Auth::user();
        $columnValue = $user->id;   
        $sasAccount = SasAccount::create([
            'name' => $validatedData['name'],
            'SAAS_Link' => "a",
            'password' => $validatedData['password'],
            'adminName' => $validatedData['adminName'],
            'idIdentity' => $columnValue,

        ]); 

        $sasAccounts = SasAccount::all();
        $arrAccs = $sasAccounts->toArray();
        Log::info('All SAS Accounts: ', $arrAccs);
        session(['sasAccounts' => $arrAccs]);

        return view('saas-accounts', ['name' => $sasAccount->name, 'sasAccounts' => $arrAccs]);
    }

    public function showSasAccounts()
    {
        $user = Auth::user();
        $columnValue = $user->id;   

        $sasAccounts = SasAccount::where('idIdentity', $columnValue)->get();
        return view('saas-accounts', ['sasAccounts' => $sasAccounts]);
   
    }
   
    public function ReceivePhone(Request $req){
        $dbPhoneDefault = DefPhone::first();
        $dbPhoneDefault->def_phone = $req->input('whatsapp'); 
        Log::info(" num: $req->whatsapp");
        $dbPhoneDefault->save();
    }
    
    public function delsasacc(Request $req){
        $name = $req->name;


        SasAccount::where('name', $name)->delete();

      
    }
    public function showAddedmessages(){
        $user = Auth::user();
        $id = $user->id;
        $grps = addgrp::select('name')->where('idIdentity',$id )->get();
        $sessions = session::where('status', 'Online')->get(['name']);

        return view('message-group', ['datas' => $grps, 'sessions'=> $sessions]);

    }
 
    public function customerData(Request $req){

        $user = Auth::user();
        $columvalue = $user->id;
        
        SasAccount::create(['name' => $req->input('name'), 'phone' => $req->input('phone'), 'comments' =>  $req->input('comments'), 'option' => $req->input('option'), 'idIdentity' => $columvalue]);
        
    }

    public function SendMessage(Request $req)
    {
        try {
            $phone = $req->phone;
            $message = $req->message;
            $DefPh = DefPhone::first();

            $ea = Http::withOptions(['verify' => false])->post("https://whatsapp.habib.cloud/api/+20101036/THISISMYSECURETOKEN/generate-token");
                $data = $ea->json(); 
                $token = $data["token"];
                if ($ea->successful()){
                    Log::info($token);

                    $responseStartServer =Http::withOptions(['verify' => false])->withHeaders(['Authorization' => "Bearer $token"])->post("https://whatsapp.habib.cloud/api/$req->whatsapp/start-session");
                    if($responseStartServer->successful()){
                        Log::info('successfully started session');
                    };
                };
                
       
            DTMsgEXT::create([
                'phone' => $phone,
                'message' => $message,
                'token' => $DefPh->token,
            ]);
    
    
            if (!$DefPh) {
                return response()->json(['status' => 'error', 'message' => 'Default phone not found'], 404);
            }
            if($req->apiToken == 'zwXu6adbtfAtvR8sjG/w33+8bKTsF+Ha8jAmnevH+mg='){
$response = Http::withOptions([
    'verify' => false,
])
->withHeaders([
    'Authorization' => "Bearer $token",
    'Content-Type' => 'application/json'
])
->post("https://whatsapp.habib.cloud/api/+20101036/send-message", [
    'phone' => $phone,
    'message' => $message,    
    "isGroup" => false,
    "isNewsletter" => false,
]);
            }
            else {
                response()->json(['UNAUTHORIZED']);
                }
if ($response->successful()){
            $responseStartServer =Http::withOptions(['verify' => false])->withHeaders(['Authorization' => "Bearer $token"])->post("https://whatsapp.habib.cloud/api/+20101036/start-session");
            if($responseStartServer->successful()){
                Log::info('successfully started session');
            };
        };
    
            if ($response->successful()) {
                return response()->json(['status' => 'success', 'data' => $response->json()]);
            } else {
                Log::error('API request failed', ['response' => $response->body(), 'status' => $response->status()]);
                return response()->json(['status' => 'error', 'message' => 'API request failed'], $response->status());
            }
        } catch (\Exception $e) {
            Log::error('Error in SendMessage', ['error' => $e->getMessage()]);
            return response()->json(['status' => 'error', 'message' => 'An error occurred'], 500);
        }
    }
    public function viewclient(Request $request){
        
    }
    public function editsasaccount(Request $request){
$linksas = $request->saasLink;
$name = $request->name;
$nameedit = $request->ename;
$passwordsas = $request->password;
$usernamesas = $request->saasLink;
$foundededition = SasAccount::where('name', $name)->first();
 $foundededition->name = $nameedit;
  $foundededition->password = $passwordsas;
   $foundededition->SAAS_Link = $linksas;
    $foundededition->adminName = $usernamesas;
     $foundededition->save();

    }
    public function makeDefault(Request $req){
        $defaultPhone = $req->whatsapp;
        Log::info($defaultPhone);

     $response = Http::withOptions(['verify' => false])->post("https://whatsapp.habib.cloud/api/$defaultPhone/THISISMYSECURETOKEN/generate-token");
     $data = $response->json();
     Log::info(message: $data['token']);
     if ($response->successful())
     {
        if ($response->successful()){
            Log::info("Successfully Started Session for deault phone of $defaultPhone");};
        $dphone = DefPhone::first();
        $dphone->token = $data['token'];
        $dphone->def_phone = $defaultPhone;
        $dphone->save();    
     }; 
    
    }
        public function showCustomers(Request $request){
            $user = Auth::user();
            $columvalue = $user->id;
        $alldata = SasAccount::where('idIdentity', $columvalue)->get();

        return view('user-clients', ['alldata' => $alldata]);
    }
    public function showGroup(){
        
        $user = Auth::user();
        $columnValue = $user->id;   
        $alldata = addgrp::where('idIdentity', $columnValue)->get();
        return view('user-groups',['allData'=> $alldata]);
    }
    public function delsessions(Request $req){
        $sessions = $req->phones;
        $deletedCount = SessionModel::whereIn('name', $sessions)->delete();
    }
    public function deletemessageu(Request $req){
        $phones = $req->phones;
        $deletedCount = savemsgs::whereIn('message', $phones)->delete();
    }
    public function viewprofilemessage(Request $req){
        Log::info($req->all());
        $name = $req->message;
        $from = $req->from;
        $to = $req->to;
        $created = $req->created_at;
        return view('messageprofile',['name'=> $name, 'from'=> $from, 'to'=> $to, 'created' => $created]);

    }
    public function configsas(Request $request){
        $codeCnt = $request->input('codeinput');
        $savebgrp = $request->input('savebygrp');
        
        $userPrefBn = userPrefBin::first();
        
        if ($userPrefBn) {
            $userPrefBn->userCountryCode = $codeCnt;
            $userPrefBn->savebygroup = $savebgrp;
            $userPrefBn->save();
            
        } else {
            $userPrefBn = new userPrefBin();
            $userPrefBn->userCountryCode = $codeCnt;
            $userPrefBn->savebygroup = $savebgrp;
            $userPrefBn->save();
        }
        
        Log::info($request->input('savebygrp'));
        
        return response()->json(data: ['message' => 'Operation successful']);
        
        
    }
    public function savemessages(Request $req){
       $msg  = $req->msg;
       $phn = $req->phone;
       $tophone = $req->toPhone;
       Log::info($tophone);
       $msg = $req->msg;
       $user = Auth::user();
       $columnValue = $user->id;      
        Log::info("received");
        savemsgs::create([
         "phone" => $phn,
         "message" => $msg,
         "fromphone" => $tophone,
         "IdIdentity" => $columnValue,
        ]);
        
        
    }
    
    public function tempmessagesview(Request $req){
        $existingRow = tempmessagesview::first();
    
        if ($existingRow) {
            $existingRow->temp = $req->tname;
            $existingRow->message = $req->tmessage;
            $existingRow->save();
        } else {
            $prfgrp = new tempmessagesview();
            $prfgrp->temp = $req->tname;
            $prfgrp->message = $req->tmessage;
            $prfgrp->save();
        }
    }
public function viewmessages(Request $req){
    $user = Auth::user();
    $columnValue = $user->id;
    $alldta = savemsgs::where('idIdentity', $columnValue)->get();


    return view('user-messages', ['alldta'=> $alldta]);
}

    public function handleprofilegroupdata(Request $req)
    {
        $existingRow = profilegrpviewer::first();
    
        if ($existingRow) {
            $existingRow->name = $req->name;
            $existingRow->customertype = $req->customertype;
            $existingRow->created_at = $req->created_at;
            $existingRow->save();
        } else {
            $prfgrp = new profilegrpviewer();
            $prfgrp->name = $req->name;
            $prfgrp->customertype = $req->customertype;
            $prfgrp->created_at = $req->created_at;
            $prfgrp->save();
        }
    }
    public function editgrpdata(Request $req){
        $prfgrp = addgrp::where("name", $req->name)->first();
        Log::info($req->name);
        Log::info($req->uname);
        
        if (empty($req->uname)) {
            if ($req->has('deletekeyuse')) {
                Log::info('saw delete key');
                $prfgrp->delete();
            }
        } else {
            if ($req->has('deletekeyuse')) {
                Log::info('saw delete key');
                $prfgrp->delete();
            } 
            else 
            {

                $prfgrp->name = $req->uname;
                $prfgrp->comment = $req->notes;
                $prfgrp->save();
            }
        }
   

    }
    public function deletecustomersrows(Request $req){
        $phones = $req->phones;
        Log::info($phones);
        $user = Auth::user();
        $col = $user->id;
       $deletedcount = SasAccount::whereIn('name', $phones)->where("idIdentity", $col)->delete();
        
    }

    public function viewprofile(){
        $prfgrp = profilegrpviewer::first();
        $name = $prfgrp->name;
        $ctype = $prfgrp->customertype;
        $created = $prfgrp->created_at;

        return view('profilegroup', ['name'=> $name, 'ctype' => $ctype, 'created'=> $created]);


    }
    public function viewtempprofile(){
        $prfgrp = tempmessagesview::first();

        $name = $prfgrp->temp;
        $message = $prfgrp->message;
        return view('profile-message-template', ['tname' => $name, 'message'=> $message]);
    }
public function updclient(Request $req){
    $drow = addgrp::where('name', $req->name)->first();
    if ($drow){
        $drow->name = $req->name;
        $drow->comment = $req->comment;
    }
}
public function viewprfgrps(Request $req){

   $alldata =  $req->all();

   return view('profile-group', ['alldata' => $alldata]);
}
    public function showsmsgs(){
        $getall = savemsgs::all();
        return view('',['user-messages']);
    }
    public function showSessions()
    {
        $user = Auth::user();
        $col = $user->id;
        $alldata = SessionModel::where('idIdentity', $col)->get();
        return view('user-sessions', ['sessions'=> $alldata]);
    }
    public function disconnectSession(Request $req)
    {
        $phone = $req->mphone;
        $session = SessionModel::where('phone', $phone)->first();
    
        if (!$session) {
            return response()->json(['error' => 'Session not found'], 404);
        }
    
        $response = Http::withOptions([
            'verify' => false,
            'headers' => ['Authorization' => "Bearer {$session->token}"]
        ])->post("https://whatsapp.habib.cloud/api/{$phone}/close-session");
    
        Log::info('Attempting to close session');
    
        if ($response->successful()) {
            $session->status = "Offline";
            $session->save();
            Log::info("Session closed successfully for phone: {$session->phone}, status: {$session->status}");
            Log::info($response->body());
            return response()->json(['message' => 'Session closed successfully']);
        } else {
            Log::error("Failed to close session: " . $response->body());
            return response()->json(['error' => 'Failed to close session'], 500);
        }
    }
    public function messageshandler(Request $reqe){
       
       try {
        $name = $reqe->name;
        $comment = $reqe->comment;
        $note = $reqe->note1;
        $note2 = $reqe->note2;
        $user = Auth::user();
        $columnValue = $user->id;    
        Log::info("em");  
 
        
        addgrp::create([
            'name'=> $name,
            'comment' => $comment,
            'idprimary' => $columnValue,
            'idIdentity' => $columnValue,

        ]);
     
       }
       catch (Exception $e){
        Log::info($e);
       }
 
    
    }

    public function changeGroup(Request $req){ 
        $this->storedaccName;
        $option = $req->choice;
        $name = $req->name;
        $group = dataCustomer::where('name', $name)->first();

        if ($group){
            $group->option = $option;
            $group->save();
        }
        else{
            Log::info('not found');
        }
        Log::info($req->all());
        Log::info($this->storedaccName);
        if ($option == 'allclient'){
            Log::info('allclients');
        }
    }
public function showMessages(){
    $allgroups = addgrp::all();
}

    public function delrowsessions(Request $request){

    }
   
    public function SendMessageGroup(Request $req)
{
    $alldata = $req->all();
    $phone = $req->phone;

    $sessionDB = Session::where('phone', $phone)->first();

    if (!$sessionDB) {
        Log::error("Session not found for phone: $phone");
        return response()->json(['error' => 'Invalid session'], 400);
    }

    $token = $sessionDB->token;
    $tophone = $req->toPhone;
    Log::info($alldata);

    $data = [
        "phone" => $tophone,
        "message" => $req->msg,
        "apiToken" => $req->apiToken,
        "countryCode" => $req->country_code,
    ];

    $delaySeconds = 0;
    $result = DB::transaction(function () use ($phone, &$delaySeconds) {
        $createdatRecord = MessageDate::lockForUpdate()->first();
        $now = Carbon::now();

        if ($createdatRecord) {
            $lastSentAt = Carbon::parse($createdatRecord->created_atdate);
            $diffInSeconds = $now->diffInSeconds($lastSentAt);
            if ($diffInSeconds < 35) {
                $delaySeconds =  35 - $diffInSeconds;
                Log::info("Waiting for {$delaySeconds} seconds before sending the message.");
                sleep($delaySeconds);
            }
        }
        $currentTime = Carbon::now();
        if ($createdatRecord) {
            $createdatRecord->created_atdate = $currentTime;
            $createdatRecord->save();
        } else {
            $createdat = new MessageDate();
            $createdat->created_atdate = $currentTime;
            $createdat->save();
        }

        return true;
    });

    if ($result) {
        $res = Http::withOptions(['verify' => false])
            ->withHeaders(['Authorization' => "Bearer $token"])
            ->post("https://whatsapp.habib.cloud/api/{$phone}/send-message/", $data);

        if ($res->successful()) {
            Log::info($res->json());
            Log::info("success");
            $user = Auth::user();
            $columnValue = $user->id;      
     
            $newmsg = new savemsgs();
            $newmsg->created_at = Carbon::now();
            $newmsg->phone = $phone;
            $newmsg->fromphone = $data['phone'];
            $newmsg->message = $data['message'];
            $newmsg->IdIdentity = $columnValue;
            $newmsg->save();
            return response()->json(['status' => 'Message sent successfully'], 200);
        } else {
            Log::info($res->json());
            Log::info("unsuccess");
            return response()->json(['error' => 'Failed to send message'], 500);
        }
    }

    return response()->json(['error' => 'An unexpected error occurred'], 500);
}

public function disconnectsesion(Request $req){
    $phones = $req->input('phones');
    
    foreach ($phones as $phone){
        $sessions = SessionModel::where('phone', $phone)->first();
        $token = $sessions->token;
      $res = Http::withOptions(['verify' => false])
        ->withHeaders(['Authorization' => "Bearer $token"])
        ->post("https://whatsapp.habib.cloud/api/$phone/close-session");
      

        if ($res->successful()){
            $sessions->status = "Offline";
            $sessions->save();
            return Response(['success']);
         
        }
    }
}
 public function deleterow(Request $request)
{
    $phones = $request->input('phones', []);

    if (empty($phones)) {
        return response()->json( [
            'success' => false,
            'message' => 'No phone numbers provided for deletion'
        ]);
    }
foreach ($phones as $phone){
    $model=  SessionModel::where('phone', $phone)->first();
    $token = $model->token;
    Log::info($token);
    $res = Http::withOptions(['verify' => false])->withHeaders(['Authorization' => "Bearer . $token"])->post("https://whatsapp.habib.cloud/api/$phone/close-session");
    $res = Http::withOptions(['verify' => false])->withHeaders(['Authorization' => "Bearer . $token"])->post("https://whatsapp.habib.cloud/api/$phone/logout-session");

if ($res->successful()){
    Log::info($res->json());
}
else{
    Log::info($res->json());
}
}
    try {
        $deletedCount = SessionModel::whereIn('phone', $phones)->delete();

        return response()->json([
            'success' => true,
            'message' => "$deletedCount row(s) deleted successfully"
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => "Error deleting rows: " . $e->getMessage()
        ], 500);
    }
}

public function deletetempmessage(Request $req){
    $ntemp = templateMessages::where('name', $req->name)->delete();
    return $ntemp;
}
public function edittemplate(Request $req){
    Log::info($req->all());
    $tempmes = templateMessages::where("name", $req->name)->first();
    $tempmes->name = $req->y;
    Log::info($req->templateName);
    $tempmes->message = $req->s;
    $tempmes->save();
}
public function disconectSession(Request $req){
    $session = $req->aphone;
}
public function deleterowgroup(Request $request){
    $phones = $request->input('phones', []);
    try {
        $deletedCount = addgrp::whereIn('name', $phones)->delete();

        return response()->json([
            'success' => true,
            'message' => "$deletedCount row(s) deleted successfully"
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => "Error deleting rows: " . $e->getMessage()
        ], 500);
    }

}
    public function viewgroup(Request $request){
        $data = $request->all();
        return view ('');
    }
    public function syslogs(){
        $alldata = logsending::all(); 

        return view('system-log',  ['logs' => $alldata]);
    }
    public function deleteAccount(Request $request){
        $name = $request->input('user');
        $db = SasAccount::where('name', $name )->first();
        $db->delete();
        $sasAccounts = sasAccount::all();
        $arrAccs = $sasAccounts->toArray();
        $e = session(['sasAccounts' => $arrAccs]);

        
        return view('saas-accounts', ['sasAccounts' => $e]);
    }
    public function profileview(Request $req){
        $allrecords  =  User::where('isTrue', 'true')->first();

if ($allrecords){

    $name = $allrecords->name;
}


    }
    public function profilevew(){

        $isLogin = isLoginAcc::first();
        $email = $isLogin->email;
        $accUser = User::where('email', $email)->first();
        $emailse = $accUser->email;
        return response()->json(['email'=> $emailse, 'name'=> $accUser->name]);
    }
    public function getRequestDataPref(Request $request)
    {
        $data = $request->json()->all();
    
        $model = new userPrefrences();
        $tableName = $model->getTable();
    
    
        try {
            foreach ($data as $key => $prop) {
                if (!Schema::hasColumn($tableName, $key)) {
                    Schema::table($tableName, function (Blueprint $table) use ($key) {
                        $table->string($key)->nullable();
                    });
                    Log::info("Added column $key to table $tableName.");
                } else {
                    Log::info("Column $key already exists in table $tableName.");
                }
            }
    
            $modelInstance = userPrefrences::firstOrCreate();
    
            foreach ($data as $key => $prop) {
                $modelInstance->$key = $prop;
            }
    
            $modelInstance->save();
            $columns = Schema::getColumnListing($tableName);
        foreach ($columns as $column) {
            $isEmpty = userPrefrences::whereNotNull($column)->count() === 0;
            if ($isEmpty && !in_array($column, ['id', 'created_at', 'updated_at'])) {
                Schema::table($tableName, function (Blueprint $table) use ($column) {
                    $table->dropColumn($column);
                });
                Log::info("Deleted empty column $column from table $tableName.");
            }
        }

            return response()->json(['message' => 'Schema updated and data processed successfully.'], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Error updating schema and processing data: " . $e->getMessage());
            
            return response()->json(['error' => 'An error occurred while processing the request.'], 500);

        }
    }
    public function recCustomer(Request $request){
        $userpref = new userPrefBin();
        $userpref->UserCustomerCode = "3";
        $userpref->save();
    }
    public function showclient(Request $req)
    {
        $client = profileclientview::first();
        $this->storedaccName = $req->phone;


        if (!$client) {
            $e = new profileclientview();
            $e->phone = $req->phone;
            $e->name = $req->name;
            $e->option = $req->opton;
            $e->save();
        } else {
            $client->phone = $req->phone;
            $client->name = $req->name;
            $client->option = $req->opton;
            $client->save();
        }
    
        return response()->json($client, $client->wasRecentlyCreated ? 201 : 200);
    }
    public function profileclient(){ 
        $data = profileclientview::first();
        $name = $data->name;
        $option = $data->option;
        $phone = $data->phone;

        return view('profile-client', ['name' => $name, 'option'=> $option, 'phone' => $phone]);
    }
    public function editsasprofile(Request $request){

    }
    public function editprofileclient(Request $req){
        Log::info($req->all());
        $name = $req->name;
        $ename = $req->ename;
        $option = $req->option;
        $phone = $req->phone; 
        $comment = $req->comments; 
        Log::info($option);

        $data = SasAccount::where('name', $name)->first();
        if ($data){
            $data->name =  $ename;
            $data->phone = $phone; 
            $data->comments = $comment;
            $data->save();
        }

    }
    
    public function addtemplate(Request $request){
        $user = Auth::user();
        $col = $user->id;
        $ntemplate = new templateMessages();
        $ntemplate->idIdentity = $col;
        $ntemplate->name = $request->tempname;
        $ntemplate->message = $request->msgtemp;
        $ntemplate->save(); 
    }

    public function sasmessageconfig(Request $request)
    {
        $allData = $request->all();
        $tableName = 'sasmsgconfigs';
    
        $configId = $request->input('config_id', 'default_config');
    
        DB::beginTransaction();
    
        try {
            if (!Schema::hasColumn($tableName, 'config_id')) {
                Schema::table($tableName, function (Blueprint $table) {
                    $table->string('config_id')->unique();
                });
            }
    
            Schema::table($tableName, function (Blueprint $table) use ($allData) {
                foreach ($allData as $key => $value) {
                    if ($key !== 'config_id' && !Schema::hasColumn('sasmsgconfigs', $key)) {
                        if (is_numeric($value)) {
                            $table->float($key)->nullable();
                        } elseif (is_bool($value)) {
                            $table->boolean($key)->nullable();
                        } elseif (is_array($value)) {
                            $table->json($key)->nullable();
                        } else {
                            $table->text($key)->nullable();
                        }
                    }
                }
            });
    
            $processedData = array_map(function ($value) {
                return is_array($value) ? json_encode($value) : $value;
            }, $allData);
    
            $processedData['config_id'] = $configId;
    
            $sasmsgconfig = Sasmsgconfig::updateOrCreate(
                ['config_id' => $configId],
                $processedData
            );
    
            DB::commit();
            return response()->json(['message' => 'Configuration updated successfully'], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
 
    public function showtemplates(){
        $user = Auth::user();
        $col = $user->id;
        $alldata = templateMessages::where('idIdentity', $col)->get();
        
        Log::info($alldata);
        return view('temp-messages', ['alldata' =>  $alldata]);
        }
    public function saastempmessage(Request $request){
        $name = $request->input('nameTemplate');
        $msgData = $request->input(key: 'templateMessage');
        templateMessages::create([
            'message' => $msgData,
            'name' => $name,
        ]);
      

        return view('temp-messages', ['alldata' => $this->arrAccs]);
        }

        
        public function viewpost(Request $req){

            $sasacc = SAASACCNAV::first();
            $name = $sasacc->accountname;

            $findacc = SasAccount::where('name', $name)->first();
$saaslink = $findacc->SAAS_Link;
$password = $findacc->password;
            $adminName = $findacc->adminName;
            return view('profile-sas-account', ['name' => $name,  'adminName' => $adminName, 'saaslink' => $saaslink, 'password'=> $password]);
        }
    public function storePost(Request $req){
        $validatedData = $req->validate([
            'accountName' => 'required|string|max:255',
            'createdAt' => 'required|date',
        ]);

        $newtable = SAASACCNAV::first();
        
        if ($newtable){

            $newtable->accountname = $validatedData['accountName'];
            $newtable->save();

        }
        else {
            Log::info("Doesnt exist");
            $newt = new SAASACCNAV();
            $newt->accountname = $validatedData['accountName'];
        $newt->save();
        }

    }}
add logging for all operations there and make it add the record to the operation column in logsendings model entitling the operation incident like added group, edited group, added client