<?php namespace App\Controllers;



// use App\Models\Dashboard_model;

use App\Models\User_model;

use App\Models\Dashboard_model;

use App\Models\Common_model;

use App\Models\Member_credits_model;

use App\Models\Packages_and_pricing_model;

use App\Models\Credits_usage_tracking_model;

use App\Models\Email_template_model;

use App\Models\Member_model;

use App\Models\Transaction_model;

use App\Models\Rule_model;



class Sendmail_controller extends BaseController

{

	

	public function __construct()

	{

		$this->session = session();

        $this->MemberModel = new Member_model();

		$this->UserModel = new User_model();

		$this->dModel = new Dashboard_model();

		$this->cModel = new Common_model();

		$this->creditsModel = new Member_credits_model();

		$this->PackagesModel = new Packages_and_pricing_model();

		$this->CreditsUsageTrackingModel = new Credits_usage_tracking_model();

		$this->MailModel = new Email_template_model();

        $this->TransactionModel = new Transaction_model();

        $this->RuleModel = new Rule_model();

		helper(['form', 'url']);

	

	}

	public function index($to,$code,$return,$admin_or_user=null)

	{

        try{

		$email = \Config\Services::email();

        $email->setFrom('devbook@mprkv.co.in', 'GolfEvo');

        $email->setTo($to); 

        // login user change passowrd => type 4  

        if($return == 4)

        {

            $data['id'] = '4';

            $mem_data = $this->MemberModel->where('email', $to)->find();

            if ($mem_data) 

            {

                $temp_data = $this->MailModel->where('type' , 4)->where('is_active' , 1)->find();

                if ($temp_data[0]['to'])

                $email->setCC($temp_data[0]['to']);

                if ($temp_data) {

                $data['html'] = str_replace("%name%",$mem_data[0]['name'],$temp_data[0]['html']);

                }

                $message = view('verification_mail_temp',$data);

                if ($temp_data[0]['is_active'] == 1)

                $email->setSubject($temp_data[0]['subject']);
                else

                $email->setSubject('Password change');

            } 

            else 

            {

                $user_data = $this->UserModel->where('email', $to)->find(); 

                $temp_data = $this->MailModel->where('type' , 4)->where('is_active' , 1)->find();

                if ($temp_data[0]['to'])

                $email->setCC($temp_data[0]['to']);

                if ($temp_data) {

                $data['html'] = str_replace("%name%",$user_data[0]['name'],$temp_data[0]['html']);

                }

                $message = view('verification_mail_temp',$data);

            }

            $message = view('verification_mail_temp',$data);

            if ($temp_data[0]['is_active'] == 1)

            $email->setSubject($temp_data[0]['subject']);

            else

            $email->setSubject('Password change');

        }

        // user => type 2   

        else if($return == 3)

        {

            $user_data = $this->UserModel->where('email', $to)->find(); 

            $data['id'] = '3';

            $data['username'] = $to;

            $data['password'] = $code;

            $data['url'] = base_url()."admin";

            $temp_data = $this->MailModel->where('type' , 2)->where('is_active' , 1)->find();

            if ($temp_data[0]['to'])

            $email->setCC($temp_data[0]['to']);

            if ($temp_data) 

            $data['html'] = str_replace("%name%",$user_data[0]['name'],$temp_data[0]['html']);

            $message = view('verification_mail_temp',$data);

            if ($temp_data[0]['is_active'] == 1)

            $email->setSubject($temp_data[0]['subject']);

            else

            $email->setSubject('Username Password');

        }

        // otp  => type 3         

        else if ($return == 2)

        {

            $data['id'] = '2';

            $data['otp'] = $code;

            $mem_data = $this->MemberModel->where('email', $to)->find();

            if ($mem_data) 

            {

                $temp_data = $this->MailModel->where('type' , 3)->where('is_active' , 1)->find();

                if ($temp_data[0]['to'])

                $email->setCC($temp_data[0]['to']);

                if ($temp_data) {

                $html = str_replace("%name%",$mem_data[0]['name'],$temp_data[0]['html']);

                $data['html'] = str_replace("%otp%",$code,$html);

                }

                $message = view('verification_mail_temp',$data);

                if ($temp_data[0]['is_active'] == 1)

                $email->setSubject($temp_data[0]['subject']);

                else

                $email->setSubject('OTP verification');

            } 

            else 

            {

                $user_data = $this->UserModel->where('email', $to)->find(); 

                $temp_data = $this->MailModel->where('type' , 3)->where('is_active' , 1)->find();

                if ($temp_data[0]['to'])

                $email->setCC($temp_data[0]['to']);

                if ($temp_data) {

                $html = str_replace("%name%",$user_data[0]['name'],$temp_data[0]['html']);

                $data['html'] = str_replace("%otp%",$code,$html);

                }

                $message = view('verification_mail_temp',$data);

                if ($temp_data[0]['is_active'] == 1)

                $email->setSubject($temp_data[0]['subject']);

                else

                $email->setSubject('OTP verification');

            }

        }

        // member => type 1    

        else if($return == 1)

        {

            $data['id'] = '1';

            $user_data = $this->MemberModel->where('email', $to)->find(); 

            $data['to'] = $to;

            $data['code'] = $code;

            $data['url'] = base_url();

            $temp_data = $this->MailModel->where('type' , 1)->where('is_active' , 1)->find();

            if ($temp_data[0]['to'])

            $email->setCC($temp_data[0]['to']);

            if ($temp_data) 

            $data['html'] = str_replace("%name%",$user_data[0]['name'],$temp_data[0]['html']);

            $message = view('verification_mail_temp',$data);

            if ($temp_data[0]['is_active'] == 1)

            $email->setSubject($temp_data[0]['subject']);

            else

            $email->setSubject('Verify your email address');

        }

        // payment success => type 5   

        else if($return == 5)

        {

           

            // $temp_data = $this->MailModel->where('type' , $return)->where('is_active' , 1)->find();
            // if ($temp_data[0]['to'])
            // $email->setCC($temp_data[0]['to']);
            $data['id'] = $return;
            $data['TransactionData'] = $this->TransactionModel->where('order_id', $code )->where('member_id', session()->get('logged_user'))->find();
            $memberCredits = $this->creditsModel->where('order_id', $code )
                                                ->where('member_id', session()->get('logged_user'))
                                                ->select('package_name')
                                                ->select('cost')
                                                ->selectSum('credit_points', 'credit_points')
                                                ->selectSum('cost', 'costSum')
                                                ->selectCount('package_name', 'pack_count')
                                                ->groupBy('package_name')->findAll(); 
              
            $Subtotal = 0;
            foreach ($memberCredits as $key => $ele) {
            $Subtotal = $Subtotal + $ele['costSum'];
            }
            $data['memberCredits'] =$memberCredits;
            $data['order_id'] = $code;
            $timestamp = strtotime($data['TransactionData'][0]['created_at']);
            $data['formattedDate']  = date('l, F j, Y', $timestamp);
            $data['Subtotal'] = $Subtotal;
            $data['gst'] = $this->RuleModel->select('value')->where('rule_key', 3 )->get()->getRow()->value;
            $data['pst'] = $this->RuleModel->select('value')->where('rule_key', 4 )->get()->getRow()->value;
            $data['card_brand'] =  json_decode($data['TransactionData'][0]['transaction'] , true)['payment']['card_details']['card']['card_brand'];
            $data['last_4'] =  json_decode($data['TransactionData'][0]['transaction'] , true)['payment']['card_details']['card']['last_4'];
            $data['profile'] = $this->MemberModel->select()->where('id',  session()->get('logged_user'))->find(); 
            $data['html'] = view('success_mail',$data);

        
            $message = view('verification_mail_temp',$data);
           
            // if ($temp_data[0]['is_active'] == 1)
            // $email->setSubject($temp_data[0]['subject']);
            // else
            $email->setSubject('Golf Evolution : Confirmation of your order');

        }

        // mail id changed verification => type 6  
        else if($return == 6)
        {
            $data['id'] = '6';

            $user_data = $this->UserModel->where('email', $to)->find(); 

            $data['to'] = $to;

            $data['new_mail'] = $code;

            $data['url'] = base_url()."verify_update_email/".md5($user_data[0]['id']);

            $temp_data = $this->MailModel->where('type' , 6)->where('is_active' , 1)->find();

            if ($temp_data[0]['to'])

            $email->setCC($temp_data[0]['to']);

            if ($temp_data) 

            $data['html'] = str_replace("%name%",$user_data[0]['name'],$temp_data[0]['html']);

            $message = view('verification_mail_temp',$data);

            if ($temp_data[0]['is_active'] == 1)

            $email->setSubject($temp_data[0]['subject']);

            else

            $email->setSubject('Verify your email address');
        }

                // payment failure => type 7   

                else if($return == 7)

                {
        
                    // $temp_data = $this->MailModel->where('type' , $return)->where('is_active' , 1)->find();
                    // if ($temp_data[0]['to'])
                    // $email->setCC($temp_data[0]['to']);
                    $data['id'] = $return;
                    $data['TransactionData'] = $this->TransactionModel->where('order_id', $code )->where('member_id', session()->get('logged_user'))->find();
                    $data['category'] = json_decode($data['TransactionData'][0]['transaction'] , true)[0]['category'];
                    $data['code'] = json_decode($data['TransactionData'][0]['transaction'] , true)[0]['code'];
                    $data['detail'] = json_decode($data['TransactionData'][0]['transaction'] , true)[0]['detail'];
                    $data['order_id'] = $data['TransactionData'][0]['order_id'];
                    $timestamp = strtotime($data['TransactionData'][0]['created_at']);
                    $data['formattedDate']  = date('l, F j, Y', $timestamp);
                    $data['profile'] = $this->MemberModel->select()->where('id',  session()->get('logged_user'))->find(); 
                    $data['html'] = view('failed_mail',$data);
        
                  
                    $message = view('verification_mail_temp',$data);

                    // if ($temp_data[0]['is_active'] == 1)
                    // $email->setSubject($temp_data[0]['subject']);
                    // else
                    if($admin_or_user == 'admin'){
                        $email->setSubject('Golf Evolution : Order Failed.');
                    }else{
                      $email->setSubject('Golf Evolution : Order Failed. Please try again');
                    }
                   
        
                }

        // member reegistration notification (ADMIN) => type 8   

        else if($return == 8)

        {

            $data['id'] = '8'; 

            $data['to'] = $to;

            $data['member_mail'] = $code;

            $message = view('verification_mail_temp',$data);

            $email->setSubject('New Member Registration');

        }
        
        $email->setMessage($message);
        if ($email->send()) 
        {
            if ($return == 5) 
               return true;
        } 
        else 
        {
            $error = $email->printDebugger();
            //echo 'Email sending failed: ' . $error;
        }
    } catch (EmailException $e) {
        echo 'Email sending failed: ' . $e->getMessage();
    } 
	}



    public function verify_email($verification_code)

    {

        // Get the user data corresponding to the verification code

        $user_data = $this->MemberModel->where('md5(verification_code)', $verification_code)->find(); 

        if($user_data)

        {

            //print_r($user_data);die();

            if($user_data[0]['is_email_verified'] == 0)

            { 

                // Update the users status

                // $update_data = $this->MemberModel->update_status($user_data['id']);

                $data['is_email_verified'] = 1;

                $update_data = $this->MemberModel->where('id', $user_data[0]['id'] )->set($data)->update();

                if($update_data)

                {

                        return redirect()->to(base_url()."set_password/".md5($user_data[0]['id']));

                }

                else 

                {

                    // Show error message

                    echo 'Error in verifying email. Please try again.';

                }

            }

            else

            {

             // Show error message

            //  echo 'Email already verified.';

            if($user_data[0]['password'] == '')
            {
                return redirect()->to(base_url()."set_password/".md5($user_data[0]['id']));
            }
            else
            {
                return redirect()->to(base_url());
            }


            }

        }

        else

        {

            // Show error message

            echo 'Invalid verification code.';

        }

    }

    public function verify_update_email($verification_code)

    {

        // Get the user data corresponding to the verification code

        $user_data = $this->UserModel->where('md5(id)', $verification_code)->find(); 

        if($user_data)

        {

            //print_r($user_data);die();

            if($user_data[0]['is_email_verified'] == 0)

            { 

                // Update the users status

                // $update_data = $this->MemberModel->update_status($user_data['id']);


                $data['is_email_verified'] = 1;

                $data['email'] = 1;

                $update_data = $this->UserModel->where('id', $user_data[0]['id'] )->set(array( 'email' => $user_data[0]['new_mail'] ))->update();

                if($update_data)

                {

                        return redirect()->to(base_url());

                }

                else 

                {

                    // Show error message

                    echo 'Error in verifying email. Please try again.';

                }

            }

            else

            {

             // Show error message

            //  echo 'Email already verified.';

             return redirect()->to(base_url()."set_password/".md5($user_data[0]['id']));

            }

        }

        else

        {

            // Show error message

            echo 'Invalid verification code.';

        }

    }



    public function forgot_password()

    {

      $this->session->setTempdata('user',"member",3);

      if($this->request->getmethod() == 'get')

      {

         return view('forgot_password_otp.php');

      }

      else if($this->request->getmethod() == 'post')

      {         

  

        $email = $this->request->getVar('email');

        $user_data = $this->MemberModel->where('email', $email)->where('is_email_verified', 1 )->find();

        if ($user_data) 

        {

          $otp = rand(1000 , 9999);

          $this->index($this->request->getVar('email') , $otp , 2 ); 

          $data['status'] = 'success';

          $data['otp'] = $otp;

          echo json_encode($data);

        } 

        else 

        {

          $data['status'] = 'failed';

          echo json_encode($data);

        }

         

      }

    }



   

}