<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Repository\AdminRepository;
use Illuminate\Http\Request;
use App\Models\Auth\User;
use App\Models\Auth\Currency;
use App\Models\CircleUserTemp;
use App\Models\CircleRoundPayment;
use App\Models\CircleDepositPayment;
use App\Repositories\SiteSettingsRepository;
use App\Repositories\Auth\UserDeviceTokenRepository;
use App\Models\CircleUser;
use App\Models\CircleRound;
use App\Models\Circle;
use App\Models\SiteSettings;
use App\Models\RoundPaymentUser;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Auth;
use Image;
use File;

class CircleController extends Controller {

    protected $userDeviceTokenRepository;

    public function __construct(SiteSettingsRepository $siteSettingsRepository, UserDeviceTokenRepository $userDeviceTokenRepository, AdminRepository $AdminRepository)
    {
        $this->siteSettingsRepository = $siteSettingsRepository;
        $this->userDeviceTokenRepository = $userDeviceTokenRepository;
        $this->dart_email = $AdminRepository->email_to();
    }

    public function index(AdminRepository $CircleRepository) 
    {
        
        $circle = Circle::select('*')
                        ->orderBy('id', 'desc')
                        ->get();

        foreach ($circle as $key => $value) {
            $payment = CircleRoundPayment::where('circle_code', $value->circle_code)->where('payment_type', 2)->get();
            $count = count($payment);
            $circle[$key]->count = $count;
            $circleUser = CircleUser::where('circle_code', $value->circle_code)->where('accept_status', 2)->get();
            $usercount = count($circleUser);
            $circle[$key]->usercount = $usercount;
            
        }
        // dd($circle);
        // dd($this->dart_email[4]['value']);
       return view('admin.pages.circle.list', compact('circle'));
    }


    public function status(AdminRepository $AdminRepository, $id)
    {
        $user_id = base64_decode($id);
        $table = new Circle;


        $userData = $AdminRepository->getById($user_id, $table);

        $userActive = $userData->status;
        
        if($userActive == 1)
        {
            $data = array('status' => 0);                
        }
        else
        {
            $data = array('status' => 1);                 
        }

        $status = $AdminRepository->update($data, $user_id, false, $table);
            if($status)
            {
                session()->flash('success', 'User Status Changed Successfully');
                return redirect()->route('circle.circleList');
            }
            else
            {
                session()->flash('error', 'Sorry, But User Status Was Not Changed Successfully; Please Try Again');
                return redirect()->route('circle.circleList');
            }
    }
    
    public function add(AdminRepository $AdminRepository)
    {
        $user = User::select('users.*')
                     ->where('role_id', 2)
                     ->where('status', 1)
                     ->where('confirmed', 1)
                     ->orderBy('email', 'asc')
                     ->get();

        $today_date = date('Y-m-d');
        $min_date = date('Y-m-d', strtotime($today_date. ' + 10 days'));
        $max_date = date('Y-m-d', strtotime($today_date. ' + 60 days'));

        $curr = Currency::where('status', '=', 1)->where('is_deleted', '=', 1)->get();

        return view('admin.pages.circle.add', compact('user', 'min_date', 'max_date', 'curr'));
    }


    public function store(AdminRepository $AdminRepository, Request $request)
    {
        $curr = Currency::where('curr_code', '=', $request->input('curr'))->first();

        $total_rev = $request->input('tta');
        $per_person_rev = $request->input('rs');
        $total_person = count($request->input('aptts'));
        // dd($request->input('aptts'));
        $device_tokens = [];

        $rev = $total_rev/$per_person_rev;

        $round1 = round($rev);

        if($rev>$round1)
        {
            $round = $round1+1;
        }
        else
        {
            $round = $round1;
        }

        if($request->input('pof') == 'bi-weekly')
        {
            if($per_person_rev<=750)
            {
                $total = $round*14;    
            }
            else
            {
                session()->flash('errors', 'Please Try Again! It Sholud Be Below 750 Euros');
                return redirect()->route('circle.circleAdd');
            }
            
        }
        else if($request->input('pof') == 'monthly')
        {
            if($per_person_rev<=1000)
            {
                $total = $round*30;    
            }
            else
            {
                session()->flash('errors', 'Please Try Again! It Sholud Be Below 1000 Euros');
                return redirect()->route('circle.circleAdd');
            }
            
        }
        else if($request->input('pof') == 'weekly')
        {
            if($per_person_rev<=500)
            {
                $total = $round*7;
            }
            else
            {
                session()->flash('errors', 'Please Try Again! It Sholud Be Below 500 Euros');
                return redirect()->route('circle.circleAdd');
            }
            
        }
        else
        {
            if($per_person_rev<=750)
            {
                $total = $round*10;    
            }
            else
            {
                session()->flash('errors', 'Please Try Again! It Sholud Be Below 750 Euros');
                return redirect()->route('circle.circleAdd');
            }
            
        }


        $start_date = $request->input('wsd');
        $end_date = date('Y-m-d', strtotime($start_date. ' + '.$total.' days'));

        if($total<180)
        {
            $table = new Circle;
            $data = array(
                    'user_id' => $request->input('aptts')[0],
                    'circle_code' => time(),
                    'target_achive' => $total_rev,
                    'round_set' => $per_person_rev,
                    'p_round' => $request->input('pof'),
                    'no_of_member' => $total_person,
                    'reason_for_circle' => $request->input('prftc'),
                    'start_date' => $start_date,
                    'end_date' => $end_date,
                    'estimate_round' => intval($round),
                    'status' => 0

            );

            $circle = $AdminRepository->create($data, $table);
            $p=0;

            foreach ($request->input('aptts') as $value) 
            {

                $table1 = new User;
                $user = $AdminRepository->getById($value, $table1);

                $table2 = new CircleUser;
                $user_data = array(
                        'user_id' => $request->input('aptts')[0],
                        'username' => $user->first_name,
                        'mobile_country_code' => $user->mobile_country_code,
                        'mobile_number' => $user->mobile_number,
                        'circle_code' => $circle->circle_code,
                        'preference' => $p++,
                        'accept_status' => 0,
                        'termination_request_status' => 0
                );

                $circle_temp = $AdminRepository->create($user_data, $table2);

                // $circleUserWhere = array('mobile_number'=>$user->mobile_number, 'circle_code'=> $circle_temp->circle_code);
                // $circleUserDetails = $AdminRepository->getByWhere($table2, $circleUserWhere);
                // if($circleUserDetails != null)
                // {
                //     $tableToken = new SiteSettings;
                //     $whereToken = array('user_id'=>$circleUserDetails->id);
                //     $userDevice = $AdminRepository->getByWhere($tableToken, $circleUserWhere);

                //     if($userDevice != null)
                //     {
                //         if($userDevice->count()>0)
                //         {
                //            array_push($device_tokens, $userDevice->device_tokens);
                //         }
                //     }
                // }
                if($user)
                {
                /*************email********************/
                $to = $user->email;
                $email_text='  <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>'.__('messages.all_mail_before_name').' <span style="">'.$user->first_name.'</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>You are requested to join into a circle.</p>
                                       <p>Please find the follwing circle details:</p>
                                       
                                       <p>Circle Code: '.$circle->circle_code.'</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.all_mail_footer_para2').'</p>
                                        <p>'.__('messages.all_mail_footer_para3').'</p>
                                    </td>
                                </tr>';
                        //echo $email_text; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from($this->dart_email[4]['value'], 'DANT');
                    $message->to($to);
                    $message->subject('Circle joining request mail');
                });
                /*************email********************/
                }
            }
            $table3 = new CircleRound;
            for($i=0; $i<intval($round);$i++){
                if($request->input('pof') == 'weekly') {
                    $payments_date = date('Y-m-d', strtotime($start_date. ' + '.($i*7).' days'));
                    $payments_grace_date = date('Y-m-d', strtotime($start_date. ' + '.(($i*7)+1).' days'));
                } elseif($request->input('pof') == 'bi-weekly') {
                    $payments_date = date('Y-m-d', strtotime($start_date. ' + '.($i*14).' days'));
                    $payments_grace_date = date('Y-m-d', strtotime($start_date. ' + '.(($i*14)+2).' days'));
                } else if($request->input('pof') == 'monthly') {
                    $payments_date = date('Y-m-d', strtotime($start_date. ' + '.($i*30).' days'));
                    $payments_grace_date = date('Y-m-d', strtotime($start_date. ' + '.(($i*30)+4).' days'));
                } else {
                    $payments_date = date('Y-m-d', strtotime($start_date. ' + '.($i*10).' days'));
                    $payments_grace_date = date('Y-m-d', strtotime($start_date. ' + '.(($i*10)+1).' days'));
                }
                $instCircleArr = array(
                                    'circle_code'=>$circle->circle_code,
                                    'round_no'=>$i+1,
                                    'payments_date'=>$payments_date,
                                    'payments_grace_date'=>$payments_grace_date
                                );
                $instCircle = $AdminRepository->create($instCircleArr, $table3);

                // if($instCircle)
                // {
                //     $response = $AdminRepository->notification(implode(',', $device_tokens), $circle_code);
                // }
            }

            if($circle_temp)
            {
                    session()->flash('success', 'New Circle Created Succesfully');
                    return redirect()->route('circle.circleList');
            }
            else
            {
                session()->flash('errors', 'Please Try Again! New Circle Was Not Created Succesfully');
                return redirect()->route('circle.circleAdd');
            }
        }
        else
        {
            session()->flash('errors', 'Please Try Again! Your Created Circle Is Exceed Six Months');
            return redirect()->route('circle.circleAdd');
        }
    }


    public function payment(AdminRepository $AdminRepository)
    {
        $circle_payment = CircleRoundPayment::select('*')
                                            ->whereIn('payment_type', [1,3])
                                            ->get();
                                            // dd($circle_payment);
        foreach ($circle_payment as $key => $value) {
           $circle = Circle::where('circle_code', $value->circle_code)->first();
           if($circle)
           {
               $circle_payment[$key]->start_date = $circle['start_date'];
               $circle_payment[$key]->now_date = date('Y-m-d');
           }
           // dd($circle_payment[$key]->now_date);
        }
        // dd($circle_payment);
        return view('admin.pages.circle.payment', compact('circle_payment'));

    }


    public function payment_status(AdminRepository $AdminRepository, $id)
    {
        $payment_id = base64_decode($id);
        $date = date('Y-m-d H:i:s');
        $table = new CircleRoundPayment;
        $table1 = new CircleUser;
        $table2 = new Circle;
        $table3 = new CircleRound;

        $payment = CircleRoundPayment::find($payment_id);
        $user = CircleUser::find($payment->circle_user_id);

        $name = User::where('mobile_number', $user->mobile_number)->first();

        $paymentdata = array('trn_status' => 1);                
        $paymentstatus = $AdminRepository->update($paymentdata, $payment_id, false, $table);

        $userdata = array('accept_status' => 1, 'status_date' => $date);
        $userstatus = $AdminRepository->update($userdata, $payment->circle_user_id, false, $table1);

        $roundpayment = CircleRoundPayment::where('circle_code', $payment->circle_code)
                                  ->where('round_id', $payment->round_id)
                                  ->where('trn_status', 1)
                                  ->where('payment_type', 1)
                                  ->get();

        $count = count($roundpayment);

        $circle = Circle::where('circle_code', $payment->circle_code)->first();

        $round_number = $circle->completed_round+1;

        if($count == $circle->no_of_member)
        {
            $total_round = $circle->completed_round+1;
            $circledata = array('status' => 1, 'completed_round'=> $total_round);
            // if($total_round < $circle->estimate_round)
            // {
                $circlestatus = $AdminRepository->update($circledata, $circle->id, false, $table2);

                $round = CircleRound::where(['circle_code'=> $payment->circle_code, 'round_no'=>$total_round])->first();

                $rounddata = array('payment_status' => 1);
                $roundstatus = $AdminRepository->update($rounddata, $round->id, false, $table3);


                $all_circle_user = CircleUser::where('circle_code', $circle->circle_code)->get();

                foreach ($all_circle_user as $key => $value) 
                {
                    $all_user = User::where('mobile_number', $value->mobile_number)->first();

                    /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$all_user->id));

                    // dd($userDevice);
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" => 'Hi '.$all_user->first_name.', all users paid from circle('.$value->circle_code.') in ('.$total_round.') round, Please check your next payment date ');

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $value->circle_code, $content);
                    }
                /****************notification**********************/


                }
            // }
        }



        //check completed circle and update status
        $circleUpdatedData = Circle::where('circle_code', $payment->circle_code)->first();
        if($circleUpdatedData->estimate_round == $circleUpdatedData->completed_round)
        {
            $circledata1 = array('status' => 5);
            $AdminRepository->update($circledata1, $circle->id, false, $table2);
        }

        // dd($count);        
        
        if($userstatus && $name)
        {
                /*************email********************/
                $to = $name->email;
                $email_text='  <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>'.__('messages.all_mail_before_name').' <span style="">'.$name->first_name.'</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>Circle Code: '.$circle->circle_code.'</p>
                                       <p>Admin Approved Your Round '.$round_number.' Payment.</p>
                                       
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.all_mail_footer_para2').'</p>
                                        <p>'.__('messages.all_mail_footer_para3').'</p>
                                    </td>
                                </tr>';
                        //echo $email_text; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from($this->dart_email[4]['value'], 'DANT');
                    $message->to($to);
                    $message->subject('Approved Your round payment for your Circle');
                });
                /*************email********************/

                session()->flash('success', 'Payment Status Changed Successfully');
                return redirect()->route('circle.payment');
            }
            else
            {
                session()->flash('errors', 'Sorry, But Payment Status Was Not Changed Successfully; Please Try Again');
                return redirect()->route('circle.payment');
            }
        
    }


    public function circle_details(AdminRepository $AdminRepository, $id)
    {
        $circle_id = base64_decode($id);
        $table = new CircleRound;
        $circle = Circle::find($circle_id);
        $circle_code = $circle->circle_code;
        $round = CircleRound::where('circle_code', $circle_code)->get();

        foreach ($round as $key => $value) {
        $circle_payment = CircleRoundPayment::select('*')
                                ->where('payment_mode', 1)
                                ->where('payment_type',2)
                                ->where('round_id', $value->id)
                                ->count();

        $round[$key]->withdrwal = $circle_payment;


        }

        // dd($round);

        return view('admin.pages.circle.details', compact('round', 'circle_code', 'circle'));
    }


    public function circle_round_edit(AdminRepository $AdminRepository, $id)
    {
        $circle_id = base64_decode($id);
        $table = new CircleRound;
        $round = CircleRound::find($circle_id);
        $circle = Circle::where('circle_code', $round->circle_code)->first();
        // $circle_code = $circle->circle_code;
        // $round = CircleRound::find($circle_id);

        // dd($circle);

        return view('admin.pages.circle.circle_round_edit', compact('round', 'circle'));
    }


    public function circleRoundUpdate(AdminRepository $AdminRepository, $id, Request $req)
    {
        $circle_id = base64_decode($id);
        $table = new CircleRound;

        // $circle_round = CircleRound::find($circle_id);

        // $circle = Circle::where('circle_code', $circle_round->circle_code)->first();



        $date = $req->input('csd');

        $data = array('payments_date' => $date);
        $circle_round_date_update = $AdminRepository->update($data, $circle_id, false, $table);

        if($circle_round_date_update)
        {
            session()->flash('success', 'Circle Round Date Update Successfully');
            return redirect()->route('circle.circle_detail', base64_encode($req->input('ci')));
        }
        else
        {
            session()->flash('errors', 'Sorry, Circle Round Date Update Is Not Changed Successfully, Please Try Again');
            return redirect()->route('circle.circle_detail', base64_encode($req->input('ci')));
        }

    }


    public function circle_user_detail(AdminRepository $AdminRepository, $id)
    {
        $circle_round_id = base64_decode($id);

        $circle_round = CircleRound::find($circle_round_id);
        $round_number = $circle_round->round_no;
        $circle = Circle::where('circle_code', $circle_round->circle_code)->first();
        $circle_id = $circle->id;

        $user_payment = CircleUser::select('*' )
                            ->leftJoin('circle_round_payments', function ($join) use($circle_round_id) {
                                  $join->on('circle_users.id', '=', 'circle_round_payments.circle_user_id');
                                  $join->where('circle_round_payments.round_id', $circle_round_id);
                            })
                            ->where('circle_users.circle_code', $circle->circle_code)
                            ->get();
        // dd($payment);

        return view('admin.pages.circle.user_details', compact('circle_id', 'user_payment', 'round_number'));
    }


    public function payment_withdrwan(AdminRepository $AdminRepository, $id)
    {

        $round_id = base64_decode($id);
        $circle_round = CircleRound::find($round_id);
        $circle = Circle::where('circle_code', $circle_round->circle_code)->first();
        $target_amount = $circle->target_achive;
        $round_amount  = $circle->round_set;
        $member_count  = $circle->no_of_member;
        $round_number  = $circle_round->round_no;
        $total_amount  = $member_count*$round_amount*$round_number; 
        $table = new CircleRoundPayment;
        $countwithdraw = CircleRoundPayment::where('circle_code', $circle->circle_code)
                                  ->where('payment_type', 2)
                                  ->count();
        if(($total_amount-($countwithdraw*$target_amount))>=$target_amount)
        {
            
            $current_user = CircleUser::where('circle_code', $circle->circle_code)
                            ->skip($countwithdraw)->take(1)
                            ->orderBy('preference')
                            ->first();

            $name = User::where('mobile_number', $current_user->mobile_number)->first();

            $userExist = CircleRoundPayment::where('circle_code', $circle->circle_code)
                                  ->where('payment_type', 2)
                                  ->where('circle_user_id', $current_user->id)
                                  ->count();
            if($userExist==0){
                RoundPaymentUser::where(['circle_code'=>$circle->circle_code, 'circle_user_id'=>$current_user->id])->update(['status'=>1,'transfered_date'=>date('Y-m-d'),'transfered_by'=>Auth::guard('admin')->user()->id]);
                $instCircleArr = array(
                                    'circle_code'=>$circle->circle_code,
                                    'circle_user_id'=>$current_user->id,
                                    'round_id'=>$round_id,
                                    'trn_id'=>'withdrawal-'.rand(0,1000),
                                    'trn_status'=>1,
                                    'amount'=>$target_amount,
                                    'payment_mode'=>1,
                                    'payment_type'=>2,
                                );
                $instCircle = $AdminRepository->create($instCircleArr, $table);

                $all_circle_user = CircleUser::where('circle_code', $circle->circle_code)->get();

                foreach ($all_circle_user as $key => $value) 
                {
                    $all_user = User::where('mobile_number', $value->mobile_number)->first();

                    /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$all_user->id));

                    // dd($userDevice);
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" => $name->first_name.' paid by Admin in this circle ('.$value->circle_code.').');

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $value->circle_code, $content);
                    }
                /****************notification**********************/


                }

                session()->flash('success', 'Round payment send to user '.$current_user->username);
            } else {
                session()->flash('errors', 'Sorry, Your Total Round Amount is not Reach Target Amount; Please Try Next Round');
            } 
            if($name)
            {
            /*************email********************/
                $to = $name->email;
                $email_text='  <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>'.__('messages.all_mail_before_name').' <span style="">'.$name->first_name.'</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.pay_target_amount_by_admin_mail_body_para1').' '.$circle->circle_code.'</p>
                                       <p>'.__('messages.pay_target_amount_by_admin_mail_body_para2').'</p>
                                       
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.all_mail_footer_para2').'</p>
                                        <p>'.__('messages.all_mail_footer_para3').'</p>
                                    </td>
                                </tr>';
                        //echo $email_text; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from($this->dart_email[4]['value'], 'DANT');
                    $message->to($to);
                    $message->subject(__('messages.pay_target_amount_by_admin_mail_subject'));
                });
                /*************email********************/
            }
            return redirect()->route('circle.circle_detail', base64_encode($circle->id));
        }
        else
        {   
              
            session()->flash('errors', 'Sorry, Your Total Round Amount is not Reach Target Amount; Please Try Next Round');
            return redirect()->route('circle.circle_detail', base64_encode($circle->id));
        
        }
        
    }


    public function payment_withdraw_details(AdminRepository $AdminRepository, $id)
    {
        $circle_id = base64_decode($id);

        $circle = Circle::find($circle_id);
        // dd($circle);

        $circle_code = $circle->circle_code;

        $withdrawn = CircleRoundPayment::where('circle_code', $circle_code)->where('payment_type', 2)->get();

        return view('admin.pages.circle.withdrawl_details', compact('circle_id', 'withdrawn', 'circle_code'));
    }



    public function reject_details(AdminRepository $AdminRepository, $id)
    {
        $circle_id = base64_decode($id);

        $circle = Circle::find($circle_id);
        // dd($circle);

        $circle_code = $circle->circle_code;

        $reject_user = CircleUser::where('circle_code', $circle_code)->where('accept_status', 2)->get();

        return view('admin.pages.circle.reject_details', compact('circle_id', 'reject_user', 'circle_code'));
    }


    public function user_request(AdminRepository $AdminRepository, $id)
    {
        $circle_id = base64_decode($id);
        $table = new Circle;

        $circleDetails = Circle::find($circle_id);
        $circleuser = CircleUser::where('circle_code', $circleDetails->circle_code)->get();

        $data = array('status' => 3);

        $circle = $AdminRepository->update($data, $circle_id, false, $table);

        if($circle)
        {
            foreach ($circleuser as $key => $value) 
            {
                $user = User::where('mobile_number', $value->mobile_number)->first();
                if($user)
                {
                /*************email********************/
                $to = $user->email;
                $email_text='  <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>'.__('messages.all_mail_before_name').' <span style="">'.$user->first_name.'</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.terminate_request_accept_by_admin_mail_body_para1').' '.$value->circle_code.'</p>
                                       <p>'.__('messages.terminate_request_accept_by_admin_mail_body_para2').'</p>
                                       
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.all_mail_footer_para2').'</p>
                                        <p>'.__('messages.all_mail_footer_para3').'</p>
                                    </td>
                                </tr>';
                        //echo $email_text; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from($this->dart_email[4]['value'], 'DANT');
                    $message->to($to);
                    $message->subject(__('messages.terminate_request_accept_by_admin_mail_subject'));
                });
                /*************email********************/
                /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$user->id));

                    // dd($userDevice);
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" => 'Hi '.$user->first_name.', your circle('.$value->circle_code.') suspended by admin, please check.');

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $value->circle_code, $content);
                    }
                    /****************notification**********************/
                }
            }

            session()->flash('success', 'Circle Is Now Suspended Successfully');
            return redirect()->route('circle.circleList');
        }
        else
        {
            session()->flash('errors', 'Sorry, Circle Status Is Not Changed Successfully, Please Try Again');
            return redirect()->route('circle.circleList');
        }
    }


    public function user_blockrequest(AdminRepository $AdminRepository, $id)
    {
        $circle_id = base64_decode($id);
        $table = new Circle;

        $circleDetails = Circle::find($circle_id);
        $circleuser = CircleUser::where('circle_code', $circleDetails->circle_code)->get();

        $data = array('status' => 2);

        $circle = $AdminRepository->update($data, $circle_id, false, $table);

        if($circle)
        {
            foreach ($circleuser as $key => $value) 
            {
                $user = User::where('mobile_number', $value->mobile_number)->first();

                if($user)
                {
                    /*************email********************/
                    $to = $user->email;
                    $email_text='  <tr>
                                       <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                           <p>'.__('messages.all_mail_before_name').' <span style="">'.$user->first_name.'</span> </p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>'.__('messages.terminate_request_accept_by_admin_mail_body_para1').' '.$value->circle_code.'</p>
                                           <p>'.__('messages.terminate_request_accept_by_admin_mail_body_para2').'</p>
                                           
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>'.__('messages.all_mail_footer_para2').'</p>
                                        <p>'.__('messages.all_mail_footer_para3').'</p>
                                        </td>
                                    </tr>';
                            //echo $email_text; die;
                    $data['email_text'] = $email_text;    
                    Mail::send('mail.email_template', $data, function($message) use ($to)
                    {
                        $message->from($this->dart_email[4]['value'], 'DANT');
                        $message->to($to);
                        $message->subject(__('messages.terminate_request_accept_by_admin_mail_subject'));
                    });
                    /*************email********************/

                    /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$user->id));

                    // dd($userDevice);
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" => 'Hi '.$user->first_name.', your circle('.$value->circle_code.') blocked by admin, please check.');

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $value->circle_code, $content);
                    }
                    /****************notification**********************/
                }
            }
             
            session()->flash('success', 'Circle Is Now Blocked Successfully');
            return redirect()->route('circle.circleList');
        }
        else
        {
            session()->flash('errors', 'Sorry, Circle Status Is Not Changed Successfully, Please Try Again');
            return redirect()->route('circle.circleList');
        }
    }



    public function payment_deposit(AdminRepository $AdminRepository)
    {
        $circle_deposit_payment = CircleDepositPayment::select('*')
                                            ->where('payment_type', '<>', 2)
                                            ->orderBy('id', 'desc')
                                            ->get();
        foreach ($circle_deposit_payment as $key => $value) {
           $circle = Circle::where('circle_code', $value->circle_code)->first();
           $circle_deposit_payment[$key]->end_date = $circle ? $circle['end_date'] : '';
           $circle_deposit_payment[$key]->now_date = date('Y-m-d');
        }
        // dd($circle_deposit_payment);
        return view('admin.pages.circle.deposit_payment', compact('circle_deposit_payment'));

    }


    public function payment_suspend_deposit(AdminRepository $AdminRepository)
    {
        $circle_round_payment = CircleRoundPayment::select('*')
                                            ->where('payment_type', 3)
                                            ->orderBy('id', 'desc')
                                            ->get();
                                            // dd($circle_round_payment);
        foreach ($circle_round_payment as $key => $value) {
            // echo $value->circle_code;
           $circle = Circle::where('circle_code', $value->circle_code)->first();
           // dd($circle);
           if($circle)
           {
              $circle_round_payment[$key]->end_date = $circle->end_date;
              $circle_round_payment[$key]->now_date = date('Y-m-d');
           }
        }
        // dd($circle_deposit_payment);
        return view('admin.pages.circle.deposit_suspend_payment', compact('circle_round_payment'));

    }


    public function payment_deposit_status(AdminRepository $AdminRepository, $id)
    {
        $payment_id = base64_decode($id);
        $date = date('Y-m-d H:i:s');
        $table = new CircleDepositPayment;
        $table1 = new CircleUser;
        $table2 = new Circle;
        // $table3 = new CircleRound;

        $payment = CircleDepositPayment::find($payment_id);
        // dd($payment);
        $user = CircleUser::find($payment->circle_user_id);

        // dd($user);

        $name = User::where('mobile_number', $user->mobile_number)->first();

        // dd($name);

        $paymentdata = array('trn_status' => 1);                
        $paymentstatus = $AdminRepository->update($paymentdata, $payment_id, false, $table);

        $userdata = array('accept_status' => 1, 'status_date' => $date);
        $userstatus = $AdminRepository->update($userdata, $payment->circle_user_id, false, $table1);

        $roundpayment = CircleDepositPayment::where('circle_code', $payment->circle_code)
                                  ->where('round_id', $payment->round_id)
                                  ->where('trn_status', 1)
                                  ->where('payment_type', 1)
                                  ->get();

        $count = count($roundpayment);

        $circle = Circle::where('circle_code', $payment->circle_code)->first();

        if($count == $circle->no_of_member)
        {
            
            $circledata = array('status' => 1);
            // if($total_round < $circle->estimate_round)
            // {
                $circlestatus = $AdminRepository->update($circledata, $circle->id, false, $table2);

                // $round = CircleRound::where(['circle_code'=> $payment->circle_code, 'round_no'=>$total_round])->first();

                // $rounddata = array('payment_status' => 1);
                // $roundstatus = $AdminRepository->update($rounddata, $round->id, false, $table3);
            // }
            $all_circle_user = CircleUser::where('circle_code', $circle->circle_code)->get();

                foreach ($all_circle_user as $key => $value) 
                {
                    $all_user = User::where('mobile_number', $value->mobile_number)->first();

                    /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$all_user->id));

                    // dd($userDevice);
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" => 'Hi '.$all_user->first_name.', all users deposit payment paid from circle('.$value->circle_code.'), Please proceed your first round payment ');

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $value->circle_code, $content);
                    }
                /****************notification**********************/
                }

        }

        // dd($count);        
        
        if($userstatus)
            {
                /*************email********************/
                $to = $name->email;
                $email_text='  <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>'.__('messages.all_mail_before_name').' <span style="">'.$name->first_name.'</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>Circle Code: '.$circle->circle_code.'</p>
                                       <p>Admin Approved Your Deposit Payment.</p>
                                       
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.all_mail_footer_para2').'</p>
                                        <p>'.__('messages.all_mail_footer_para3').'</p>
                                    </td>
                                </tr>';
                        //echo $email_text; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from($this->dart_email[4]['value'], 'DANT');
                    $message->to($to);
                    $message->subject('Approved Your deposit payment for your Circle');
                });
                /*************email********************/


                session()->flash('success', 'Payment Deposit Status Changed Successfully');
                return redirect()->route('circle.deposit_payment');
            }
            else
            {
                session()->flash('errors', 'Sorry, But Payment Deposit Status Was Not Changed Successfully; Please Try Again');
                return redirect()->route('circle.deposit_payment');
            }
        
    }




    public function payment_refund_status(AdminRepository $AdminRepository, $id)
    {
        $payment_id = base64_decode($id);
        $table = new CircleDepositPayment;

        $circledeposit = CircleDepositPayment::find($payment_id);

        // dd($circledeposit);

        $circleuser = CircleUser::find($circledeposit->circle_user_id);

        $user = User::find($circleuser->user_id);

        // dd($user); 
        
        $paymentdata = array('payment_type' => 3);                
        $paymentstatus = $AdminRepository->update($paymentdata, $payment_id, false, $table);

        if($paymentstatus && $user)
        {
            /*************email********************/
                $to = $user->email;
                $email_text='  <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>'.__('messages.all_mail_before_name').' <span style="">'.$user->first_name.'</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.deposit_payment_paid_by_admin_mail_body_para1').' '.$circledeposit->circle_code.'</p>
                                       <p>'.__('messages.deposit_payment_paid_by_admin_mail_body_para2').'</p>
                                       
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.all_mail_footer_para2').'</p>
                                        <p>'.__('messages.all_mail_footer_para3').'</p>
                                    </td>
                                </tr>';
                        //echo $email_text; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from($this->dart_email[4]['value'], 'DANT');
                    $message->to($to);
                    $message->subject(__('messages.deposit_payment_paid_by_admin_mail_subject'));
                });
                /*************email********************/

                /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$user->id));

                    // dd($userDevice);
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" => 'Hi '.$user->first_name.', your circle('.$circledeposit->circle_code.') deposit amount refund by admin, please check.');

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $circledeposit->circle_code, $content);
                    }
                /****************notification**********************/


            session()->flash('success', 'Payment Refund Done Successfully');
            return redirect()->route('circle.deposit_payment');
        }
        else
        {
            session()->flash('errors', 'Sorry, But Payment Refund Was Not Done Successfully; Please Try Again');
            return redirect()->route('circle.deposit_payment');
        }
        
    }


    public function payment_suspend_refund_status(AdminRepository $AdminRepository, $id)
    {
        $payment_id = base64_decode($id);
        $table = new CircleRoundPayment;

        $roundpayment = CircleRoundPayment::find($payment_id);

        $user = CircleUser::find($roundpayment->circle_user_id);

        $name = User::where('mobile_number', $user->mobile_number)->first();
        
        $paymentdata = array('trn_status' => 1);                
        $paymentstatus = $AdminRepository->update($paymentdata, $payment_id, false, $table);

        if($paymentstatus)
        {

            /*************email********************/
                $to = $name->email;
                $email_text='  <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>'.__('messages.all_mail_before_name').' <span style="">'.$name->first_name.'</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>Circle Code: '.$roundpayment->circle_code.'</p>
                                       <p>You refund your excess amount: '.$roundpayment->amount.'</p>
                                       
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.all_mail_footer_para2').'</p>
                                        <p>'.__('messages.all_mail_footer_para3').'</p>
                                    </td>
                                </tr>';
                        //echo $email_text; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from($this->dart_email[4]['value'], 'DANT');
                    $message->to($to);
                    $message->subject('You Refund Your Excess payment to Admin');
                });
                /*************email********************/

                /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$name->id));

                    // dd($userDevice);
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" => 'Hi '.$name->first_name.', your suspended circle('.$roundpayment->circle_code.') excess amount('.$roundpayment->amount.') refund by admin, please check.');

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $roundpayment->circle_code, $content);
                    }
                /****************notification**********************/

            session()->flash('success', 'Payment Suspend Refund Done Successfully');
            return redirect()->route('circle.suspend_deposit_payment');
        }
        else
        {
            session()->flash('errors', 'Sorry, But Payment Suspend Refund Was Not Done Successfully; Please Try Again');
            return redirect()->route('circle.suspend_deposit_payment');
        }
        
    }



    public function circle_of_user_details(AdminRepository $AdminRepository, $id)
    {
        $mobile_number = base64_decode($id);

        $user = User::where('mobile_number', $mobile_number)->first();

        // dd($user->avatar_location);

        return view('admin.pages.circle.userDetails', compact('user'));
    }



    public function circle_terminate_request(AdminRepository $AdminRepository)
    {
        $circle_terminate = CircleUser::select('*')
                            ->where('termination_request_status', '<>', 0)
                            ->orderBy('updated_at', 'desc')
                            ->get();

        // dd($circle_terminate);
        return view('admin.pages.circle.terminate_request_details', compact('circle_terminate'));
    }


    public function circle_terminate_approve(AdminRepository $AdminRepository, $id)
    {
        $id = base64_decode($id);
        $table = new CircleUser;
        $table1 = new Circle;

        $termination_request_where = array('termination_request_status' => 2);                
        $termination_request = $AdminRepository->update($termination_request_where, $id, false, $table);

        $circle_user = CircleUser::find($id);
        $circle = Circle::where('circle_code', $circle_user->circle_code)->first();
        $circle_termination_where = array('status' => 3);
        $circle_terminate = $AdminRepository->update($circle_termination_where, $circle->id, false, $table1);


        $circle_user_email = CircleUser::where('circle_code', $circle_user->circle_code)->get();

        foreach ($circle_user_email as $key => $value) 
        {
                $user_email = User::where('mobile_number', $value->mobile_number)->where('role_id', 2)->first();
                if($user_email) {        
                    /*************email********************/
                    $to = $user_email->email;
                    $email_text='   <tr>
                                       <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                           <p>'.__('messages.all_mail_before_name').' <span style="">'.$user_email->first_name.'</span> </p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>'.__('messages.terminate_request_accept_by_admin_mail_body_para1').' '.$value->circle_code.'</p>
                                           <p>'.__('messages.terminate_request_accept_by_admin_mail_body_para2').'</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>'.__('messages.all_mail_footer_para2').'</p>
                                            <p>'.__('messages.all_mail_footer_para3').'</p>
                                        </td>
                                    </tr>';
                            //echo $email_text; die;
                    $data['email_text'] = $email_text;    
                    Mail::send('mail.email_template', $data, function($message) use ($to)
                    {
                        $message->from($this->dart_email[4]['value'], 'DANT');
                        $message->to($to);
                        $message->subject(__('messages.terminate_request_accept_by_admin_mail_subject'));
                    });
                    /*************email********************/


                    /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$user_email->id));

                    // dd($userDevice);
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" => __('messages.terminate_request_accept_by_admin_notification').'('.$value->circle_code.') '.__('messages.terminate_request_accept_by_admin_notification1').$circle_user->username.__('messages.terminate_request_accept_by_admin_notification2'));

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $value->circle_code, $content);
                    }
                    /****************notification**********************/
                }
        }

        if($circle_terminate && $termination_request)
        {
            session()->flash('success', 'Circle Terminate Successfully');
            return redirect()->route('circle.circle_terminate_request');
        }
        else
        {
            session()->flash('errors', 'Sorry, Circle Terminate Not Successfully; Please Try Again');
            return redirect()->route('circle.circle_terminate_request');
        }
        
    }


    public function circle_terminate_reject(AdminRepository $AdminRepository, $id)
    {
        $id = base64_decode($id);
        $table = new CircleUser;
        
        $user = CircleUser::find($id);
        $name = User::where('mobile_number', $user->mobile_number)->first();
        $termination_request_where = array('termination_request_status' => 3);                
        $termination_request = $AdminRepository->update($termination_request_where, $id, false, $table);


        if($termination_request)
        {
            /*************email********************/
                $to = $name->email;
                $email_text='  <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>'.__('messages.all_mail_before_name').' <span style="">'.$name->first_name.'</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>'.__('messages.terminate_request_reject_by_admin_mail_body_para1').' '.$user->circle_code.'</p>
                                       <p>'.__('messages.terminate_request_reject_by_admin_mail_body_para1').'</p>
                                       
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>Stay connected with us. We appreciate very much your trust in us.</p>
                                       <p>Please do not hesitate to contact us for any other requests.</p>
                                    </td>
                                </tr>';
                        //echo $email_text; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from($this->dart_email[4]['value'], 'DANT');
                    $message->to($to);
                    $message->subject(__('messages.terminate_request_reject_by_admin_mail_subject'));
                });
                /*************email********************/

                /****************notification**********************/
                    $userDevice = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$name->id));
                    if($userDevice->count()>0)
                    {
                        $content = array(
                        "en" =>  __('messages.terminate_request_accept_by_admin_notification').'('.$user->circle_code.') '.__('messages.terminate_request_accept_by_admin_notification1').$name->first_name.__('messages.terminate_request_accept_by_admin_notification2'));

                        $notify_response = $this->siteSettingsRepository->notification($userDevice[0]->device_tokens, $user->circle_code, $content);
                    }
                /****************notification**********************/


            session()->flash('success', 'Circle Termination Reject Successfully');
            return redirect()->route('circle.circle_terminate_request');
        }
        else
        {
            session()->flash('errors', 'Sorry, Circle Termination Reject Not Successfully; Please Try Again');
            return redirect()->route('circle.circle_terminate_request');
        }
        
    }


    public function circle_delete($id)
    {
        $circle_id = base64_decode($id);
        
        $circle = Circle::find($circle_id);
        if($circle)
        {
            Circle::where('id',$circle_id)->delete();
        }
        // dd($circle);
        
        $circle_deposit_payment = CircleDepositPayment::where('circle_code', $circle->circle_code)->get();
        if($circle_deposit_payment)
        {
            CircleDepositPayment::where('circle_code', $circle->circle_code)->delete();
        }
        // dd($circle_deposit_payment);

        $circle_round = CircleRound::where('circle_code', $circle->circle_code)->get();
        if($circle_round)
        {
            CircleRound::where('circle_code', $circle->circle_code)->delete();
        }
        // dd($circle_round);

        $circle_round_payment = CircleRoundPayment::where('circle_code', $circle->circle_code)->get();
        if($circle_round_payment)
        {
            CircleRoundPayment::where('circle_code', $circle->circle_code)->delete();
        }
        // dd($circle_round_payment);

        $circle_user = CircleUser::where('circle_code', $circle->circle_code)->get();
        if($circle_user)
        {
            CircleUser::where('circle_code', $circle->circle_code)->delete();
        }
        // dd($circle_user);
        return redirect()->route('circle.circleList');
    }
     

}
