<?php

namespace App\Http\Controllers\CSD;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Mail;
use App\Models\Admin;
use Hash;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;
use App\Mail\EmailReplyfromCustomerCare;
use App\Mail\SendEmailfromCustomerCare;

class CSDController extends Controller

{
  public function dologin(Request $request)
    {

        $credentials = $request->only('email', 'password');

            if (Auth::guard('csd')->attempt($credentials)) {
                $request->session()->regenerate();

                $user = Auth::guard('csd')->user();

                if ($user->access_type === 'csd' || $user->user_type === 'C') {
                    session([
                        'csd_session.user_id' => $user->id,
                        'csd_session.user_type' => $user->user_type,
                    ]);
                    //  return $all_sessions = session()->all();
                    return redirect()->route('csd.home')->with('success', 'Welcome CSD');
                } else {
                    Auth::guard('csd')->logout();
                    session()->forget('csd_session');

                    return redirect()->back()->with('error', 'Access not permitted.');
                }
            }

            return redirect()->back()->with('error', 'Invalid credentials.');
    }   



    public function logout(Request $request){
        Auth::guard('csd')->logout();
        session()->forget('csd_session');
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('csd.login');
    }

    public function home(Request $request){
        if(Auth::guard('csd')->check()){
            $csdId = session('csd_login_id');
            $csd = \App\Models\AdminLogin::find($csdId);
            $user =  Auth::guard('csd')->user();

            $Queriescontacts = DB::connection('mysql')
                ->table('contacts')
                ->select('sitename as countryName', DB::raw('COUNT(*) as unread'))
                ->where('contact_type', 'Queries')
                ->where('view_status', 0)
                ->groupBy('sitename')
                ->get();


            $Complaintcontacts = DB::connection('mysql')
                ->table('contacts')
                ->select('sitename as countryName', DB::raw('COUNT(*) as unread'))
                ->where('contact_type', 'Complaint')
                ->where('view_status', 0)
                ->groupBy('sitename')
                ->get();
            
            
            // $data = compact('Queriescontacts','Complaintcontacts');
            // return $data;
            return view('csd.home',compact('Queriescontacts','Complaintcontacts','user','csd'));
        }else{
            return redirect()->back()->with('error', 'Login Failed');
        }
    }

    public function sitelabels(Request $request,$query, $sitename){
        if(Auth::guard('csd')->check()){
            $dbname = 'mysql';
            $user =  Auth::guard('csd')->user();

            $perPage = 50;
            $paginatedData = DB::connection($dbname)
                ->table('contacts')
                ->where('sitename', $sitename)
                ->where('contact_type', $query)
                ->where('spam', 0)
                ->orderByDesc('updated_at')
                ->paginate($perPage);

            $search = 0;
            return view('csd.sitelabels', compact('user', 'paginatedData', 'sitename', 'search','query'));
        }else{
            return redirect()->back()->with('error', 'Login Failed');
        }
    }

    public function Searchsitelabels(Request $request){
        if (Auth::guard('csd')->check()) {
            $user = Auth::guard('csd')->user();
            $sitename = $request['sitename'];
            $dbname = 'mysql';
            $search = $request['search_val'];
            $type = $request['query'];
            $perPage = 50;
        
            $queryBuilder = DB::connection($dbname)->table('contacts')->where('contact_type', $type);
        
            if ($search === "open") {
                $queryBuilder->where('is_block', 'N');
            } elseif ($search === "close") {
                $queryBuilder->where('is_block', 'Y');
            } else {
                $queryBuilder->where(function ($query) use ($search) {
                    $query->where('name', 'like', '%' . $search . '%')
                        ->orWhere('email', 'like', '%' . $search . '%')
                        ->orWhere('mobile', 'like', '%' . $search . '%')
                        ->orWhere('ticket_id', 'like', '%' . $search . '%')
                        ->orWhere('is_block', $search);
                });
            }
        
            $paginatedData = $queryBuilder->orderByDesc('updated_at')->paginate($perPage);
            $query = $type;
            return view('csd.sitelabels', compact('user', 'sitename', 'paginatedData', 'search', 'query'));
        } else {
            return redirect()->back()->with('error', 'Login Failed');
        }
        
        
    }

    public function inbox(Request $request){
        if (Auth::guard('csd')->check()) {
            $dbname = 'mysql';
            $user =  Auth::guard('csd')->user();

            $perPage = 50;
            $paginatedData = DB::connection($dbname)
                ->table('contacts')
                ->where('spam', 0)
                ->orderByDesc('updated_at')
                ->paginate($perPage);

            $search = 0;
            return view('csd.inbox', compact('user', 'paginatedData', 'search'));

          } else {
            return redirect()->back()->with('error', 'Login Failed');
          } 
    }

    public function inboxsearch(Request $request){
        if (Auth::guard('csd')->check()) {
            $user = Auth::guard('csd')->user();
            $dbname = 'mysql';
            $search = $request['search_val'];
            $perPage = 50;
        
            if ($search == "open") {
                $searchVal = 'N';
                $paginatedData = DB::connection($dbname)
                    ->table('contacts')
                    ->where('is_block', $searchVal)
                    ->orderByDesc('updated_at')
                    ->paginate($perPage);

            } elseif ($search == "close") {
                $searchVal = 'Y';
                $paginatedData = DB::connection($dbname)
                    ->table('contacts')
                    ->where('is_block', $searchVal)
                    ->orderByDesc('updated_at')
                    ->paginate($perPage);

            } else {
                $searchVal = $request['search_val'];
                $paginatedData = DB::connection($dbname)
                    ->table('contacts')
                    ->where(function ($query) use ($searchVal) {
                        $query->where('name', 'like', '%' . $searchVal . '%')
                            ->orWhere('email', 'like', '%' . $searchVal . '%')
                            ->orWhere('mobile', 'like', '%' . $searchVal . '%')
                            ->orWhere('ticket_id', 'like', '%' . $searchVal . '%')
                            ->orWhere('is_block', $searchVal);
                    })
                    ->orderByDesc('updated_at')
                    ->paginate($perPage);
            }
            return view('csd.inbox',compact('user','paginatedData','search'));

          } else {
            return redirect()->back()->with('error', 'Login Failed');
          } 
    }

    
    public function trash(Request $request){
        if (Auth::guard('csd')->check()) {
            $dbname = 'mysql';
            $user =  Auth::guard('csd')->user();

            $perPage = 50;
            $paginatedData = DB::connection($dbname)
                ->table('contacts')
                ->where('spam', 1)
                ->orderByDesc('updated_at')
                ->paginate($perPage);

            $search = 0;
            return view('csd.trash', compact('user', 'paginatedData', 'search'));

          } else {
            return redirect()->back()->with('error', 'Login Failed');
          } 
    }
    public function Searchtrash(Request $request){
        if (Auth::guard('csd')->check()) {
            $user =  Auth::guard('csd')->user();
            
            $search = $request['search_val'];

            $user = Auth::guard('csd')->user();
            $dbname = 'mysql';
            $search = $request['search_val'];
            $perPage = 50;
        
            if ($search == "open") {
                $searchVal = 'N';
                $paginatedData = DB::connection($dbname)
                    ->table('contacts')
                    ->where('is_block', $searchVal)
                    ->orderByDesc('updated_at')
                    ->paginate($perPage);

            } elseif ($search == "close") {
                $searchVal = 'Y';
                $paginatedData = DB::connection($dbname)
                    ->table('contacts')
                    ->where('is_block', $searchVal)
                    ->orderByDesc('updated_at')
                    ->paginate($perPage);

            } else {
                $searchVal = $request['search_val'];
                $paginatedData = DB::connection($dbname)
                    ->table('contacts')
                    ->where(function ($query) use ($searchVal) {
                        $query->where('name', 'like', '%' . $searchVal . '%')
                            ->orWhere('email', 'like', '%' . $searchVal . '%')
                            ->orWhere('mobile', 'like', '%' . $searchVal . '%')
                            ->orWhere('ticket_id', 'like', '%' . $searchVal . '%')
                            ->orWhere('is_block', $searchVal);
                    })
                    ->orderByDesc('updated_at')
                    ->paginate($perPage);
            }
            // return view('csd.inbox',compact('user','paginatedData','search'));
            //  return $paginatedData->links();
            return view('csd.trash',compact('user','paginatedData','search'));

          } else {
            return redirect()->back()->with('error', 'Login Failed');
          } 
    }

    public function delete_spam(Request $request,$sitename,$id){
        if(Auth::guard('csd')->check()){
            $dbname = 'mysql';
            $id = base64_decode($id);
            DB::connection($dbname)->table('contacts')->where('id', $id)->delete();
            DB::connection($dbname)->table('contact_conversations')->where('contact_id', $id)->delete();
            // return redirect()->Intended('/csd/inbox')->with('success', 'Welcome to CSD Dashboard');
            return redirect()->route('csd.home')->with('success', 'Welcome to CSD Dashboard');
        }else{
            return redirect()->back()->with('error', 'Login Failed');
        }
    }

    public function view(Request $request, $sitename, $id,$siteurl){
        if(Auth::guard('csd')->check()){

            $dbname = 'mysql';
            $id = base64_decode($id);
            $siteurl = base64_decode($siteurl);

            // if ($sitename === 'GBBR') {
            //     $connection = 'mysqlgbbr';
            // } elseif ($sitename === 'GBSG') {
            //     $connection = 'mysqlgbsg';
            // } elseif ($sitename === 'GBFR') {
            //     $connection = 'mysqlgbfr'; 
            // } else {
            //     return 'error'; 
            // }

            $user =  Auth::guard('csd')->user();
            $adminid = $user->id;
            $data = DB::connection($dbname)->table('contacts')->where('id',$id)->first();
            DB::connection($dbname)->table('contacts')->where('id', $id)->update(['view_status' => 1]);
            $conversations = DB::connection($dbname)->table('contact_conversations')->where('contact_id',$id)->get();
            
            return view('csd.view',compact('data','conversations','user','adminid','siteurl'));
        }
        else{
            return redirect()->back()->with('error', 'Login Failed');
        }
    }

    public function view_save(Request $request, $sitename, $id){
        if(Auth::guard('csd')->check()){

            $dbname = 'mysql';
            $id = base64_decode($id);
            $base64 = "";
            //$mail_data = [];

            // if ($sitename === 'GBBR') {
            //     $connection = 'mysqlgbbr';
            // } elseif ($sitename === 'GBSG') {
            //     $connection = 'mysqlgbsg';
            // } elseif ($sitename === 'GBFR') {
            //     $connection = 'mysqlgbfr'; 
            // } else {
            //     return 'error'; 
            // }
            $image = $request->file('img'); // Use file() to get the uploaded file

            // Generate the image name if the image is not null
            $imageName = ($image != null) ? time() . '_' . $dbname . '.' . $image->getClientOriginalExtension() : "";
            
            if ($imageName != "") {
                $image->move(public_path('images'), $imageName);
                $path =  public_path('images/' . $imageName);
                $type = pathinfo($path, PATHINFO_EXTENSION);
                $data = file_get_contents($path);
                $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);     
                //$base64 = base64_encode($path);   
              
            }

            $siteinfo = DB::table('sites')->where(['site_name' => $sitename])->first();

            if($request['status'] == "open"){
                $status = 'N';
            }elseif($request['status'] == 'close'){
                $status = 'Y';
            }else{
                $status = 'N';
            }

            $admin =  Auth::guard('csd')->user();
            $adminid = $admin->id;
            $user = DB::connection($dbname)->table('contacts')->find($id);
            // $med = $request['img'];
            // $imageName = ($med != null) ? time() . '_' . $user->name . '.' . $med->getClientOriginalExtension() : "";
            // $path = ($imageName != null) ? $med->move(public_path('images'), $imageName) : "";            
    
            DB::connection($dbname)->table('contact_conversations')->insert([
                "contact_id" => $id,
                "message" => $request['adminmsg'],
                "dfile" => $base64,
                'created_by'=>$adminid,
                "is_block"=>$status,
                "created_at" => date('Y-m-d H:i:s'),
                "updated_at" => date('Y-m-d H:i:s')
            ]); 

            DB::connection($dbname)->table('contacts')->where('id', $user->id)->update(['is_block' => $status]);

            $getContactsRecord = DB::connection($dbname)->table('contacts')->where(['id' => $id])->first();

            $mail_data['contact_data'] = $getContactsRecord;
            $mail_data['site_data'] = $siteinfo; 
            $userData = $mail_data;

            require_once app_path('Helpers/zeptomail_helper.php');
            try {
                $subject = $mail_data['site_data']->site_domain .' - '. 'Successful submission of enquiry form';
                $htmlbody = view('admin.emails.reply_email_from_customercare', ['data' => $userData])->render();
                $userResponse = sendZeptoMail($getContactsRecord->email, $subject, $htmlbody, $siteinfo);

            } catch (\Exception $e) {
                // return response()->json(['error' => 'Failed to send email', 'details' => $e->getMessage()], 500);
            }

            // try{
            //     Mail::to($getContactsRecord->email)->queue(new EmailReplyfromCustomerCare($mail_data));
            // }catch(\Exception $e){
            //     // Get error here
            // }

            return back();
        }else{
            return redirect()->back()->with('error', 'Login Failed');

        }
    }

    public function markunread($sitename,$id){
        if(Auth::guard('csd')->check()){
            $dbname = 'mysql';
            $id = base64_decode($id);
            DB::connection($dbname)->table('contacts')->where('id',$id)->update([
                'view_status'=>0,
            ]);
            return back()->withSuccess("Updated Successfully");
        }else{
            return redirect()->back()->with('error', 'Login Failed');
        }
    }

    public function movetoinbox($sitename,$id){
        if(Auth::guard('csd')->check()){
            $dbname = 'mysql';
            $id = base64_decode($id);
            DB::connection($dbname)->table('contacts')->where('id',$id)->update([
                'spam'=>0,
            ]);
            return back()->withSuccess("Updated Successfully");
        }else{
            return redirect()->back()->with('error', 'Login Failed');
        }
    }
    

    public function update_status(Request $request){
        $dbname = 'mysql';
        DB::connection($dbname)->table('contacts')->where('id', $request['id'])->update(['is_block' => $request['status']]);  
        return 'done';

    }

    public function spam(Request $request){
        $dbname = 'mysql';
        DB::connection($dbname)->table('contacts')->where('id', $request['id'])->update(['spam' => 1]); 
        DB::connection($dbname)->table('contact_conversations')->where('contact_id', $request['id'])->update(['spam' => 1]);  
        return 'done';
    }

    // public function changepassword(Request $request){
    //     if(Auth::check()){
    //         $user =  Auth::guard('csd')->user();
    //         $oldpass = $request['oldpass'];
    //         $newpass = $request['newpass'];
        
    //         if(Hash::check($oldpass, $user->password)){
    //             $newpassHashed = Hash::make($newpass);
    //             $base64 = base64_encode($newpass);
        
    //             Admin::where('id', $user->id)->update([
    //                 'password' => $newpassHashed,
    //                 'remember_token' => $base64,
    //             ]);
                
    //             return 1;
    //         } else {
    //             return 0;
    //         }
    //     } else {
    //         return 0;
    //     }
        
    // }

    // public function sitewiseContactData($id = null){

    //     $result = [];
    //     $dbname = 'mysql'.$id;
    //     date_default_timezone_set('Asia/Kolkata');
    //     $today = date("Y-m-d");
    //     $from_date = date("Y-m-1");
    //     $to_date = date("Y-m-31");

    //     $result = DB::connection($dbname)->table('contacts')->get();

    //     return $result;
    // }

    public function search(Request $request){
        $dbname = 'mysql';
        $search = $request['search'];
        $result = DB::connection($dbname)
        ->table('contacts') 
        ->where(function ($query) use ($search) {
            $query->where('name', 'like', '%'.$search.'%')
                ->orWhere('email', 'like', '%'.$search.'%')
                ->orWhere('mobile', 'like', '%'.$search.'%')
                ->orWhere('ticket_id', 'like', '%'.$search.'%');
        })->get();

        return $result;
    }

    // public function d_mail(){
    //     if(Auth::check()){
    //         $user =  Auth::guard('csd')->user();
    //         $siteDetails = DB::table('site_details')->get();            
    //         return view('csd.mail',compact('user','siteDetails'));
    //     }
    //     else{
    //         return redirect()->back()->with('error', 'Login Failed');
    //     }
           
    // }

    // public function d_mail_send(Request $request){
    //     if(Auth::check()){
    //         $user =  Auth::guard('csd')->user();
    //         $siteDetails = DB::table('site_details')->where('site_sort_name',$request['site_name'])->first(); 
    //         $dbname = 'mysql'.$siteDetails->site_sort_name;
    //         $image = $request['img'];
    //         $base64 = '';

    //         $id = DB::connection($dbname)->table('contacts')->insertGetId([
    //             "contact_type" => 'Support',
    //             'query_related'=>'Support',
    //             'name'=>"Support",
    //             "mobile"=>"Support",
    //             "subject" => $request['sub'],
    //             "email" => $request['u_email'],
    //             'sitename' => strtoupper($request['site_name']),
    //             "created_at" => date('Y-m-d H:i:s'),
    //             "updated_at" => date('Y-m-d H:i:s'),
    //         ]);

    //         $ticket_id = 'TIC' . mb_substr('Support', 0, 1, 'utf-8') . $id . mt_rand(1000, 9999);

    //         DB::connection($dbname)->table('contacts')->where('id', $id)->update([
    //             'ticket_id' => $ticket_id,
    //         ]);

    //          $imageName = ($image != null) ? time() . '_' . $dbname . '.' . $image->getClientOriginalExtension() : "";
            
    //          if ($imageName != "") {
    //              $image->move(public_path('images'), $imageName);
    //              $path = 'https://admin.rightflorist.org/public/images/' . $imageName;
    //              $type = pathinfo($path, PATHINFO_EXTENSION);
    //              $data = file_get_contents($path);
    //              $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);     
    //              //$base64 = base64_encode($path);   
    //          }

    //         DB::connection($dbname)->table('contact_conversations')->insert([
    //             "contact_id" => $id,
    //             'message'=>$request['mail_body'],
    //             'dfile'=>$base64,
    //             "created_by"=>3,
    //             "created_at" => date('Y-m-d H:i:s'),
    //             "updated_at" => date('Y-m-d H:i:s'),
    //         ]);

    //         Mail::raw($request['mail_body'], function ($message) use ($request, $siteDetails, $imageName) {
    //             $message->from($siteDetails->site_support_email, 'Support Team');
    //             $message->to($request['u_email']);
    //             $message->subject($request['sub']);
    //             $message->attach(public_path('images/' . $imageName));
    //         });
    //         $base64id = base64_encode($id);
    //         $baseUrl = 'https://admin.rightflorist.org/csd/inbox/' . $siteDetails->site_sort_name;
    //         $base64Url = base64_encode($baseUrl);
    //         return redirect('/csd/view/' . $request['site_name'] . '/' . $base64id . '/' . $base64Url);                        
    //     }
    //     else{
    //         return redirect()->back()->with('error', 'Login Failed');
    //     }
    // }

    public function sendmail(Request $request){
        if(Auth::guard('csd')->check()){
            $user =  Auth::guard('csd')->user();
            $siteDetails = DB::table('sites')->get();
            $admin =  Auth::guard('csd')->user();  

            if($request->isMethod('POST')){

                $alertMsg = $alertCss = '';
                $siteDetails = DB::table('site_details')->where(['site_name' => $request->site_name])->first();
                $dbname = 'mysql';
                $image = $request->file('img');
                $base64 = '';
                $siteToken = $siteDetails->zepto_token;
                $id = DB::connection($dbname)->table('contacts')->insertGetId([
                    "contact_type" => 'other',
                    'query_related'=> '',
                    'name'=> $request->u_name,
                    "mobile"=> '0',
                    "subject" => $request->sub,
                    "email" => $request->u_email,
                    'sitename' => strtoupper($request->site_name),
                    "created_at" => date('Y-m-d H:i:s'),
                    "updated_at" => date('Y-m-d H:i:s'),
                ]);

                $ticket_id = 'TIC' . mb_substr('Support', 0, 1, 'utf-8') . $id . mt_rand(1000, 9999);

                DB::connection($dbname)->table('contacts')
                                    ->where('id', $id)->update(['ticket_id' => $ticket_id, 'view_status' => 1]);

                $imageName = ($image != null) ? time() . '_' . $dbname . '.' . $image->getClientOriginalExtension() : "";
            
                if ($imageName != "") {
                    $image->move(public_path('images'), $imageName);
                    $path = 'https://admin.rightflorist.org/public/images/' . $imageName;
                    $type = pathinfo($path, PATHINFO_EXTENSION);
                    $data = file_get_contents($path);
                    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);     
                    //$base64 = base64_encode($path);   
                }

                DB::connection($dbname)->table('contact_conversations')->insert([
                    "contact_id" => $id,
                    'message'    => $request->mail_body,
                    'dfile'      => $base64,
                    "created_by" => $admin->id,
                    "is_block"   => 'N',
                    "created_at" => date('Y-m-d H:i:s'),
                    "updated_at" => date('Y-m-d H:i:s'),
                ]);

                $getContactsRecord = DB::connection($dbname)->table('contacts')->where(['id' => $id])->first();

                $mail_data['contact_data'] = $getContactsRecord;
                $mail_data['site_data'] = $siteDetails;
                $userData = $mail_data;
                require_once app_path('Helpers/zeptomail_helper.php');
                try {
                    $alertMsg = 'Mail Send Successfully...';
                    $alertCss = 'alert-success';
                    $subject = $mail_data['site_data']->site_domain .' - '.$mail_data['contact_data']->subject;
                    $htmlbody = view('admin.emails.send_email_from_customercare', ['data' => $userData])->render();
                    $userResponse = sendZeptoMail($userData['contact_data']->email, $subject, $htmlbody, $siteDetails);
                    // return $userResponse;
                    // $data = compact('email','subject','htmlbody');
                    // return $data;
                    // return "success";
                    // return $userResponse;
    
                } catch (\Exception $e) {
                    $alertMsg = 'Something Wrong! Please try again.';
                    $alertCss = 'alert-danger';
                    DB::connection($dbname)->table('contacts')->where('id', $id)->delete();
                    DB::connection($dbname)->table('contact_conversations')->where('contact_id', $id)->delete();
                    // return response()->json(['error' => 'Failed to send email', 'details' => $e->getMessage()], 500);
                }
               

                // try{
                //     Mail::to($getContactsRecord->email)->queue(new SendEmailfromCustomerCare($mail_data));
                //     $alertMsg = 'Mail Send Successfully...';
                //     $alertCss = 'alert-success';
                // }catch(\Exception $e){
                //     // Get error here
                //     $alertMsg = 'Something Wrong! Please try again.';
                //     $alertCss = 'alert-danger';
                //     DB::connection($dbname)->table('contacts')->where('id', $id)->delete();
                //     DB::connection($dbname)->table('contact_conversations')->where('contact_id', $id)->delete();
                // }

                $request->session()->flash($alertCss, $alertMsg);
                return redirect()->route('csd.sendmail');

            }

            return view('csd.mail',compact('user','siteDetails'));
        }
        else{
            return redirect()->back()->with('error', 'Login Failed');
        }
    }

    // public function getTime(){
    //     date_default_timezone_set('Asia/Kolkata');
    //     $current_time = date('Y-m-d H:i:s');
    //     echo "The current server time is: " . $current_time;
    // }

    // public function MailCheck(){
    //     Mail::raw('Yes I am Working Mail', function ($message) {
    //         $message->from('support@giftbasketssingapore.sg');
    //         $message->to('subhajit.floranet19@gmail.com');
    //         $message->subject('Check Email');
    //         $message->cc('raj.rtech1@gmail.com');
    //         $message->bcc('partha.floranet@gmail.com');
    //     });
        
        
    // }

   
}
