<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\AuthModel;
use App\Models\SettingModel;
use App\Models\UserModel;
use App\Models\EmailModel;
use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

class Auth extends BaseController
{
    public function login()
    {
        helper(['custom', 'form', 'url']);
        $data['validation'] =  \Config\Services::validation();
        if(isset($_POST['submit']))
        {
            $input = $this->validate([
                'mobile' => 'required|numeric|min_length[3]',
                'password' => 'required'
            ]);
            if (!$input) {
                echo view('login', [
                    'validation' => $this->validator,
                    'title' => 'Login'
                ]);
            }
            else
            {
                $auth = new AuthModel();
                $uerData = $auth->get_user_by_mobile($this->request->getVar('mobile'));
                if(!$uerData)
                {
                    session()->set('error', "Invalid Mobile No.");
                    return redirect()->route('admin-login');
                }
                else
                {   
                    $userData = $auth->get_user_by_mobile_and_password($this->request->getVar('mobile'), hash("sha256", $this->request->getVar('password')));

                    if(!$userData)
                    {
                        session()->set('error', "Password Not Match");
                        return redirect()->route('admin-login');
                    }
                    else
                    {
                        $token['user_token'] = token();
                        $auth->update_token($token, $userData->user_id);
                        $ses_data = [
                            'user_id'           => $userData->user_id,
                            'name'              => $userData->user_name,
                            'mobile'            => $userData->user_mobile,
                            'role'              => $userData->user_role,
                            'user_token'        => $token['user_token'],
                            'logged_in'         => TRUE
                        ];
                        session()->set($ses_data);
                        if($userData->user_role != 'Shiva Sanghatak')
                        {
                            return redirect()->to('/admin/dashboard');
                        }
                        else
                        {
                            return redirect()->to('my-account');
                        }
                    }
                }
            }

        }
        else
        {
            if(session()->get('logged_in') == TRUE)
            {
                if(session()->get('role') != 'Shiva Sanghatak')
                {
                    return redirect()->to('/admin/dashboard');
                }
                else
                {
                    return redirect()->to('my-account');
                }
            }
            else
            {
                $setting = new SettingModel();
                $data['title'] = 'Login';
                $data['app_setting'] = $setting->get_application_setting();
                return view('login', $data);
            }
        }
    }
    function check_user_avaliablity()
    {
        $auth = new AuthModel();
        $data = $auth->get_user_by_mobile($this->request->getVar('mobile'));
        if($data)
        {
            echo 4;
        }
        else
        {
            echo 6;
        }
    }
    function login_user_by_phone($email,$username,$token,$provider)
    {
        $auth = new AuthModel();
        $userData = $auth->get_user_by_mobile(substr($email, 3));
        $rand = rand();
        if($userData)
        {
            $ses_data = [
                'user_id'            => $userData->user_id,
                'user_name'          => $userData->user_name,
                'user_mobile'        => $userData->user_mobile,
                'user_role'          => $userData->user_role,
                'logged_in'          => TRUE
            ];
            session()->set($ses_data);
            echo "Login Successfull";
        }
        else
        {
            echo "Failed to Create User";
        }
    }

     function fire_base_request()
    {
        $setting = new SettingModel();
        $app_setting = $setting->get_application_setting(); 
        $email    = $_GET['email'];
        $provider = $_GET['provider'];
        $username = $_GET['username'];
        $token    = $_GET['token'];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=".$app_setting->apiKey."&idToken=" . $token,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => array(
                "Content-length:0"
            )
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $array_response = json_decode($response, true);

        if (array_key_exists("users", $array_response)) 
        {
            $user_res = $array_response["users"];
            if (count($user_res) > 0) 
            {
                $user_res_1 = $user_res[0];
                
                if(array_key_exists("phoneNumber", $user_res_1))
                {
                    if($email==$user_res_1['phoneNumber'])
                    {
                        $this->login_user_by_phone($email,$username,$token,"Phone");
                    }
                    else
                    {
                        echo "Invalid Login Request";
                    }
                }
                else
                {
                    echo "Unknown Bad Request";
                }
            } 
            else 
            {
                echo "Invalid Request User Not Found";
            }
        } 
        else 
        {
            echo "Unknown Bad Request";
        }
    }

    function forgot_password()
    {
        if(session()->get('logged_in') == TRUE) 
        {
            if(session()->get('role') != 'Shiva Sanghatak')
            {
                return redirect()->to('/admin/dashboard');
            }
            else
            {
                return redirect()->to('my-account');
            }
        }
        else
        {
            $setting = new SettingModel();
            $data['app_setting'] = $setting->get_application_setting();
            $data['title'] = 'Forgot Password';
            return view('forgot_password', $data);
        }
    }

    function request_password()
    {
        $user = new UserModel();
        $email = new EmailModel();
        $setting = new SettingModel();
        $data_user = $user->get_user_by_email_id_for_password($this->request->getVar('email'));
        if($data_user)
        {
            $rand = rand();
            $pas['user_password'] = hash("sha256", $rand);
            $user->update_user_password($pas, $data_user->user_id);
            $da['pass'] = $rand;
            $email_id = $data_user->user_email;
            $subject = 'Forget Password Notification';
            $data['details'] = $data_user;
            $data['password'] = $rand;
            $data['app_setting'] = $setting->get_application_setting();
            $msg = view('email/ForgotPassword', $data);
            if($email->send_email($email_id, $subject, $msg, $mailType = 'html'))
            {
                session()->setFlashdata('success', "Password Send to Your Registered Mail ID ");
                return redirect()->route('admin-login');
            }
            else
            {
                session()->setFlashdata('error', "Email Sending Failed");
                return redirect()->route('admin-login');
            }
            
        }
        else
        {
            session()->setFlashdata('error', "Email ID Not Match");
            return redirect()->route('admin-login');
        }
    }

    function register()
    {
        $setting = new SettingModel();
        $data['app_setting'] = $setting->get_application_setting();
        $data['validation'] =  \Config\Services::validation();
        $data['all_package']    = $setting->get_all_packages();
        $data['title'] = 'Register';
        echo view('front/include/header', $data);
        echo view('front/register');
        echo view('front/include/footer');
    }

    function user_login()
    {
        if(session()->get('logged_in') == TRUE)
        {
            if(session()->get('role') != 'Shiva Sanghatak')
            {
                return redirect()->to('/admin/dashboard');
            }
            else
            {
                return redirect()->to('my-account');
            }
        }
        else
        {
            $setting = new SettingModel();
            $data['app_setting'] = $setting->get_application_setting();
            $data['title'] = 'Login';
            echo view('front/include/header', $data);
            echo view('front/user_login');
            echo view('front/include/footer');
        }
    }

    function submit_login()
    {
        helper(['custom', 'form', 'url']);
        $data['validation'] =  \Config\Services::validation();
        if(isset($_POST['submit']))
        {
            $input = $this->validate([
                'mobile' => 'required|numeric|min_length[9]',
                'password' => 'required'
            ]);
            if (!$input) {
                echo view('login', [
                    'validation' => $this->validator,
                    'title' => 'Login'
                ]);
            }
            else
            {
                $auth = new AuthModel();
                $uerData = $auth->get_user_by_mobile($this->request->getVar('mobile'));
                if(!$uerData)
                {
                    session()->set('error', "Invalid Mobile No.");
                    return redirect()->route('login');
                }
                else
                {   
                    $userData = $auth->get_user_by_mobile_and_password($this->request->getVar('mobile'), hash("sha256", $this->request->getVar('password')));

                    if(!$userData)
                    {
                        session()->set('error', "Password Not Match");
                        return redirect()->route('login');
                    }
                    else
                    {
                        $token['user_token'] = token();
                        $auth->update_token($token, $userData->user_id);
                        $ses_data = [
                            'user_id'           => $userData->user_id,
                            'name'              => $userData->user_name,
                            'mobile'            => $userData->user_mobile,
                            'role'              => $userData->user_role,
                            'user_token'        => $token['user_token'],
                            'logged_in'         => TRUE
                        ];
                        session()->set($ses_data);
                        if($userData->user_role != 'Shiva Sanghatak')
                        {
                            return redirect()->to('/admin/dashboard');
                        }
                        else
                        {
                            return redirect()->to('my-account');
                        }
                        
                    }
                }
            }

        }
        else
        {
            if(session()->get('logged_in') == TRUE)
            {
                if(session()->get('role') != 'Shiva Sanghatak')
                {
                    return redirect()->to('/admin/dashboard');
                }
                else
                {
                    return redirect()->to('my-account');
                }
            }
            else
            {
                 return redirect()->to('login');
            }
        }
    }

    function submit_login_checkout()
    {
        helper(['custom', 'form', 'url']);
        $data['validation'] =  \Config\Services::validation();
        if(isset($_POST['submit']))
        {
            $input = $this->validate([
                'mobile' => 'required|numeric|min_length[9]',
                'password' => 'required'
            ]);
            if (!$input) {
                echo view('login', [
                    'validation' => $this->validator,
                    'title' => 'Login'
                ]);
            }
            else
            {
                $auth = new AuthModel();
                $uerData = $auth->get_user_by_mobile($this->request->getVar('mobile'));
                if(!$uerData)
                {
                    session()->set('error', "Invalid Mobile No.");
                    return redirect()->route('checkout');
                }
                else
                {   
                    $userData = $auth->get_user_by_mobile_and_password($this->request->getVar('mobile'), hash("sha256", $this->request->getVar('password')));

                    if(!$userData)
                    {
                        session()->set('error', "Password Not Match");
                        return redirect()->route('checkout');
                    }
                    else
                    {
                        $token['user_token'] = token();
                        $auth->update_token($token, $userData->user_id);
                        $ses_data = [
                            'user_id'           => $userData->user_id,
                            'name'              => $userData->user_name,
                            'mobile'            => $userData->user_mobile,
                            'role'              => $userData->user_role,
                            'user_token'        => $token['user_token'],
                            'logged_in'         => TRUE
                        ];
                        session()->set($ses_data);
                        if($userData->user_role != 'Shiva Sanghatak')
                        {
                            return redirect()->to('/admin/dashboard');
                        }
                        else
                        {
                            return redirect()->to('checkout');
                        }
                        
                    }
                }
            }

        }
    }

    function create_account()
    {
        $user = new UserModel();
        $auth = new AuthModel();
        $setting = new SettingModel();
        $app_setting = $setting->get_application_setting();
        $check = array(
            'secret'        =>  $app_setting->secret_key,
            'response'      =>  $this->request->getVar('g-recaptcha-response')
        );
        $startProcess = curl_init();
        curl_setopt($startProcess, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($startProcess, CURLOPT_POST, true);
        curl_setopt($startProcess, CURLOPT_POSTFIELDS, http_build_query($check));
        curl_setopt($startProcess, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($startProcess, CURLOPT_RETURNTRANSFER, true);
        $receiveData = curl_exec($startProcess);
        $finalResponse = json_decode($receiveData, true);
        if($finalResponse['success'])
        {
            $input = $this->validate([
                'user_name'         => 'required',
                'user_email'        => 'required|valid_email',
                'user_mobile'       => 'required|numeric|max_length[10]',
                'user_password'     => 'required',
                'user_password_c'   => 'required|matches[user_password]'
            ]);
            if (!$input) {
                $data['validation'] = $this->validator;
                $data['app_setting'] = $setting->get_application_setting();
                $data['title'] = 'Register';
                echo view('front/include/header', $data);
                echo view('front/register');
                echo view('front/include/footer');
            }
            else
            {
                $package = $setting->get_package_by_id($this->request->getVar('user_package'));
                if(session()->get('reff_link_id'))
                {
                    $ref_id = session()->get('reff_link_id');
                }
                else
                {
                    $ref_id = 0;
                }
                
                $data = [
                    'user_name'     => $this->request->getVar('user_name'),
                    'user_email'    => $this->request->getVar('user_email'),
                    'user_mobile'   => $this->request->getVar('user_mobile'),
                    'user_package'   => $this->request->getVar('user_package'),
                    'user_package_price'   => $package->pack_price,
                    'user_wallet_bal'       => $package->pack_wallet_bal,
                    'user_password' => hash("sha256", $this->request->getVar('user_password')),
                    'user_role'     => 'User',
                    'user_status'   => 'Active',
                    'created_at'    => date('Y-m-d'),
                    'reff_link'     => str_replace(' ', '', $this->request->getVar('user_name')).'_'.rand(),
                    'refer_by'      => $ref_id,
                ];
                
                if($package->pack_price < 1)
                {
                    if($userID = $user->add_new_user_details($data))
                    {
                        $token['user_token'] = token();
                        $auth->update_token($token, $userID);
                        $ses_data = [
                            'user_id'           => $userID,
                            'name'              => $this->request->getVar('user_name'),
                            'mobile'            => $this->request->getVar('user_mobile'),
                            'role'              => 'User',
                            'user_token'        => $token['user_token'],
                            'logged_in'         => TRUE
                        ];
                        session()->set($ses_data);
                        session()->set('success', 'Registration Successfull Complete');
                        return redirect()->route('my-account');
                    }
                    else
                    {
                        session()->set('error', 'Registration Failed Please Try Again');
                        return redirect()->route('register');
                    }
                }
                else
                {
                    session()->set('user_login_details', $data);
                    $recharge_id = rand();
                    $amount = $package->pack_price;
                    session()->set('rechage_id', $recharge_id);
                    session()->set('amount_recharge', $amount);
                    $app_setting = $setting->get_application_setting();
                    $api = new Api($app_setting->rozar_key_id, $app_setting->rozar_key_secret);
                    $_SESSION['payable_amount'] = $amount;
                    $razorpayOrder = $api->order->create(array(
                        'receipt'         => $recharge_id,
                        'amount'          => $amount * 100, 
                        'currency'        => 'INR',
                        'payment_capture' => 1 
                    ));
                    $amount = $razorpayOrder['amount'];
                    $razorpayOrderId = $razorpayOrder['id'];
                    $_SESSION['razorpay_order_id'] = $razorpayOrderId;
                    $_SESSION['recharge_id'] = $recharge_id;
                    $_SESSION['amount'] = $amount;
                    $raz_pay_data = $this->rozr_pay_prepareData($amount,$razorpayOrderId, $recharge_id);
                    echo view('rezorpay_pack_payment', array('data' => $raz_pay_data)); 
                }  
            }
            
        }
        else
        {
            session()->set('error', 'Please Fill Captcha First');
            return redirect()->route('register');
        }
    }

    function create_account_from_frontend()
    {
        $user = new UserModel();
        $auth = new AuthModel();
        $setting = new SettingModel();
        $app_setting = $setting->get_application_setting();
        $check = array(
            'secret'        =>  $app_setting->secret_key,
            'response'      =>  $this->request->getVar('g-recaptcha-response')
        );
        $startProcess = curl_init();
        curl_setopt($startProcess, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($startProcess, CURLOPT_POST, true);
        curl_setopt($startProcess, CURLOPT_POSTFIELDS, http_build_query($check));
        curl_setopt($startProcess, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($startProcess, CURLOPT_RETURNTRANSFER, true);
        $receiveData = curl_exec($startProcess);
        $finalResponse = json_decode($receiveData, true);
        if($finalResponse['success'])
        {
            $input = $this->validate([
                'user_name'         => 'required',
                'user_email'        => 'required|valid_email',
                'user_mobile'       => 'required|numeric|max_length[10]',
                'user_password'     => 'required',
                'user_password_c'   => 'required|matches[user_password]',
                'refer_by'          => 'required'
            ]);
            if (!$input) {
                return redirect()->route('join-us');
            }
            else
            {
                $package = $setting->get_package_by_id($this->request->getVar('user_package'));
                if(session()->get('reff_link_id'))
                {
                    $ref_id = session()->get('reff_link_id');
                }
                elseif($u_details = $user->check_user_by_ref_link($this->request->getVar('refer_by')))
                {
                    $ref_id = $u_details->user_id;
                }
                else
                {
                    session()->set('error', 'Registration Failed Please Enter Correct Referral Code');
                    return redirect()->route('join-us');
                }
                $user_code = $user->get_shiva_sanghatak_last_code();
                $data = [
                    'user_name'     => $this->request->getVar('user_name'),
                    'user_email'    => $this->request->getVar('user_email'),
                    'user_mobile'   => $this->request->getVar('user_mobile'),
                    'user_stock_point_code'   => $user_code,
                    'user_password' => hash("sha256", $this->request->getVar('user_password')),
                    'user_role'     => 'Shiva Sanghatak',
                    'user_status'   => 'Active',
                    'created_at'    => date('Y-m-d'),
                    'reff_link'     => str_replace(' ', '', $this->request->getVar('user_name')).'_'.rand(),
                    'refer_by'      => $ref_id,
                ];
                
                
                if($userID = $user->add_new_user_details($data))
                {
                    $token['user_token'] = token();
                    $auth->update_token($token, $userID);
                    $ses_data = [
                        'user_id'           => $userID,
                        'name'              => $this->request->getVar('user_name'),
                        'mobile'            => $this->request->getVar('user_mobile'),
                        'role'              => 'Shiva Sanghatak',
                        'user_token'        => $token['user_token'],
                        'logged_in'         => TRUE
                    ];
                    session()->set($ses_data);
                    session()->set('success', 'Registration Successfull Complete');
                    return redirect()->route('my-account');
                }
                else
                {
                    session()->set('error', 'Registration Failed Please Try Again');
                    return redirect()->route('join-us');
                }
                
            }
            
        }
        else
        {
            session()->set('error', 'Please Fill Captcha First');
            return redirect()->route('/');
        }
    }

    function rozr_pay_verify_pack_payment()
    {
        $setting = new SettingModel();
        $app_setting = $setting->get_application_setting();
        $order_id = session()->get('rechage_id');
        $amount_recharge = $_SESSION['amount'] / 100;
        $success = true;
        $error = "payment_failed";
        if (empty($_POST['razorpay_payment_id']) === false) {
            $api = new Api($app_setting->rozar_key_id, $app_setting->rozar_key_secret);
        try {
                $attributes = array(
                    'razorpay_order_id' => $_SESSION['razorpay_order_id'],
                    'razorpay_payment_id' => $_POST['razorpay_payment_id'],
                    'razorpay_signature' => $_POST['razorpay_signature']
                );
                $api->utility->verifyPaymentSignature($attributes);
            } catch(SignatureVerificationError $e) {
                $success = false;
                $error = 'Razorpay_Error : ' . $e->getMessage();
            }
        }
        if ($success === true) 
        {
            $user = new UserModel();
            $auth = new AuthModel();
            $info = session()->get('user_login_details');
            $data = [
                'user_name'     => $info['user_name'],
                'user_email'    => $info['user_email'],
                'user_mobile'   => $info['user_mobile'],
                'user_package'   => $info['user_package'],
                'user_package_price'   => $info['user_package_price'],
                'user_wallet_bal'       => $info['user_wallet_bal'],
                'user_password' => $info['user_password'],
                'user_role'     => 'Shiva Sanghatak',
                'user_status'   => 'Active',
                'created_at'    => date('Y-m-d'),
                'reff_link'     => $info['reff_link'],
                'refer_by'      => $info['refer_by']
            ];
            if($userID = $user->add_new_user_details($data))
            {
                if($info['refer_by'] > 0)
                {
                    $comm_amount = (8 / 100) * $info['user_package_price'];
                    $reg_income = [
                        'reg_income_user_id' => $userID,
                        'reg_income_pack_id' => $info['user_package'],
                        'reg_income_user_pack_price' => $info['user_package_price'],
                        'reg_income_price'  =>  $comm_amount,
                        'reg_income_pay_id' =>  rand(),
                        'reg_income_role'   => 'Shiva Sanghatak',
                        'reg_income_percantage' => 8,
                        'reg_income_date'       => date('Y-m-d'),
                        'reg_income_reff_user_id' => $info['refer_by']
                    ];
                    $user->add_ref_income($reg_income);
                }

                $admin_income = [
                    'reg_income_user_id' => $userID,
                    'reg_income_pack_id' => $info['user_package'],
                    'reg_income_price'  =>  $info['user_package_price'],
                    'reg_income_pay_id' => $_SESSION['razorpay_order_id'],
                    'reg_income_role'   => 'Admin',
                    'reg_income_date'       => date('Y-m-d')
                ];
                $user->add_ref_income($admin_income);


                $token['user_token'] = token();
                $auth->update_token($token, $userID);
                $ses_data = [
                    'user_id'           => $userID,
                    'name'              => $info['user_name'],
                    'mobile'            => $info['user_mobile'],
                    'role'              => 'Shiva Sanghatak',
                    'user_token'        => $token['user_token'],
                    'logged_in'         => TRUE
                ];
                session()->set($ses_data);
                session()->set('success', 'Registration Successfull Complete');
                return redirect()->route('my-account');
            }
            else
            {
                session()->set('error', 'Transaction Done but Registration Failed Please Contact Administrator');
                return redirect()->route('register');
            }
        }
        else 
        {
            $this->session->set_userdata('error', 'Transaction Faild');
            return redirect()->route('register');
        }
    }

    public function rozr_pay_prepareData($amount,$razorpayOrderId, $order_id)
    {
        $info = session()->get('user_login_details');
        $setting = new SettingModel();
        $app_setting = $setting->get_application_setting(); 
        $data = array(
            "key" => $app_setting->rozar_key_id,
            "amount" => $amount,
            "name" => $app_setting->application_name,
            "description" => 'Product Purchase',
            "image" => base_url().'/'.$app_setting->header_logo,
            "prefill" => array(
                "name"  => $info['user_name'],
                "email"  => $info['user_email'],
                "contact" => $info['user_mobile'],
            ),
            "notes"  => array(
                // "address"  => user()->user_address,
                "merchant_order_id" => rand(),
            ),
            "theme"  => array(
                "color"  => "#F37254"
            ),
            "order_id" => $razorpayOrderId,
        );
        return $data;
    }

}
