<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Site extends CI_Controller
{
    public function index()
    {
        redirect('menu');
        //    renderView($this, 'site/index');
    }

	public function signup()
	{
		if (isset($_POST) && $_POST) {
		    
   $google_recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
   $recaptcha_secret_key =  @$this->session->merchantInfo['recaptcha_secret_key'];
   $set_recaptcha_response = $_POST['recaptcha_response'];

 


   $ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $google_recaptcha_url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
	    'secret'   => $recaptcha_secret_key,
	    'response' => $set_recaptcha_response,
	]));
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$response = curl_exec($ch);

	if (curl_errno($ch)) {
	    // Handle cURL error
	    die('cURL error: ' . curl_error($ch));
	}
	curl_close($ch);

    $get_recaptcha_response = json_decode($response);
   
     if ($get_recaptcha_response->success == true && $get_recaptcha_response->score >= 0.5) {
       

		    
            $this->form_validation->set_rules('first_name', 'First Name', 'required');
            $this->form_validation->set_rules('last_name', 'Last Name', 'required');
            $this->form_validation->set_rules('password', 'Password', 'required');
            $this->form_validation->set_rules('cpassword', 'Password Confirmation', 'required');
            $this->form_validation->set_rules('email_address', 'Email', 'required');
            if ($this->form_validation->run() == TRUE) {
                $getloc = json_decode(file_get_contents("http://ipinfo.io/"));
                $coordinates = explode(",", $getloc->loc);
                $data = [
                    'first_name' => $_POST['first_name'],
                    'last_name' => $_POST['last_name'],
                    'contact_phone' => $_POST['contact_phone'],
                    'email_address' => $_POST['email_address'],
                    'password' => $_POST['password'],
                    'cpassword' => $_POST['cpassword'],
                    'lat' => $coordinates[0],
                    'lng' => $coordinates[1],
                ];
                $response = apiCall('createAccount', '', $data);

                if($response['details']['next_step']=="verification_phone"){
                	//renderView($this, 'site/verification-phone');
                    $this->session->set_userdata('client_id', $response['details']['customer_id']);
                	redirect('site/verification_phone');
                }

                if($response['details']['next_step']=="verification_email"){
                	//renderView($this, 'site/verification-phone');
                    $this->session->set_userdata('client_id', $response['details']['customer_id']);
                	redirect('site/verification_email');
                }





                

                if ($response['code'] == 1) {
                    $this->session->set_flashdata('success', 'signup successfully');
                    redirect('signup');
                } else {
                    $this->session->set_flashdata('error', $response['msg']);
                    redirect('signup');
                }
            }else {

                $this->session->set_flashdata('form_msg', 'Something Went to wrong');
                redirect('signup');
            }
		} else {
			if (!$this->session->userdata('user')) {
				renderView($this, 'site/signup');
			} else {
				redirect();
			}
		}
		
		}else{
if (!$this->session->userdata('user')) {
				renderView($this, 'site/signup');
			} else {
				redirect();
			}
		}
	}


	public function verification_phone()
{


    // Check if form was submitted
    if (isset($_POST) && $_POST) {

        $client_id = $_POST['client_id'] ?? '';
        $code = $_POST['code'] ?? '';

         $data = [
                    'client_id' => $client_id ,
                    'code' => $code,
                    
                ];



       $response = apiCall('verifyMobileCode', '', $data);
        // Call your backend API to verify the code
       
       

        if ($response['code'] == 1) {
            // Successful verification: log user in
            $user = $response['details']['client_info'];
            $this->session->set_userdata('user', $user);
            $this->session->set_userdata('user_name', $user['first_name']);
            $this->session->set_userdata('token', $user['token']);

            $this->session->set_flashdata('success', 'Phone verified and logged in.');
            redirect(); // go to homepage or dashboard
        } else {
            // Verification failed
            
            $this->session->set_flashdata('error', $response['msg']);
            redirect('site/verification_phone');
        }
    } else {
        // GET request: just render the verification form view
        if (!$this->session->userdata('client_id')) {
            // Fallback if no client_id found in session
            $this->session->set_flashdata('error', 'Session expired. Please sign up again.');
            redirect('signup');
        }

        renderView($this, 'site/verification-phone');
    }
}


public function verification_email()
{


    // Check if form was submitted
    if (isset($_POST) && $_POST) {

        $client_id = $_POST['client_id'] ?? '';
        $code = $_POST['code'] ?? '';

         $data = [
                    'client_id' => $client_id ,
                    'code' => $code,
                    
                ];



       $response = apiCall('verifyEmailCode', '', $data);
        // Call your backend API to verify the code
       
       

        if ($response['code'] == 1) {
            // Successful verification: log user in
            $user = $response['details']['client_info'];
            $this->session->set_userdata('user', $user);
            $this->session->set_userdata('user_name', $user['first_name']);
            $this->session->set_userdata('token', $user['token']);

            $this->session->set_flashdata('success', 'Phone verified and logged in.');
            redirect(); // go to homepage or dashboard
        } else {
            // Verification failed
            
            $this->session->set_flashdata('error', $response['msg']);
            redirect('site/verification_email');
        }
    } else {
        // GET request: just render the verification form view
        if (!$this->session->userdata('client_id')) {
            // Fallback if no client_id found in session
            $this->session->set_flashdata('error', 'Session expired. Please sign up again.');
            redirect('signup');
        }

        renderView($this, 'site/verification-email');
    }
}




public function resendmobilecode()
{
    $client_id = $this->input->post('client_id');

    

    // Call backend API
    $response = apiCall('resendMobileCode', '', [
        'client_id' => $client_id
    ]);

   

    if ($response['code'] == 1) {
        $this->session->set_flashdata('success', $response['msg']);

    } else {
        $this->session->set_flashdata('error', $response['msg']);
    }

       echo json_encode($response);
}


public function resendEmailcode()
{
    $client_id = $this->input->post('client_id');

    

    // Call backend API
    $response = apiCall('resendEmailcode', '', [
        'client_id' => $client_id
    ]);

   

    if ($response['code'] == 1) {
        $this->session->set_flashdata('success', $response['msg']);

    } else {
        $this->session->set_flashdata('error', $response['msg']);
    }

       echo json_encode($response);
}





	public function login()
	{
        $this->form_validation->set_rules('username', 'User Name', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');
            if ($this->form_validation->run() == TRUE) {
                $response = apiCall('customerLogin', [
                    'user_mobile' => $_POST['username'],
                    'password' => $_POST['password']
                ]);

                
            
                if ($response['code'] == 1) {
                    $user = $response['details']['client_info'];
                    $this->session->set_userdata('user', $user);
                    $this->session->set_userdata('user_name', $user['first_name']);
                    $this->session->set_userdata('token', $user['token']);
                    $this->session->set_flashdata('success', 'login Ok');
                    if ($this->input->post('redirect')) {
                        redirect('order/payment_option');
                    } else {
                        redirect();
                    }
                } else {
                    $this->session->set_flashdata('error', $response['msg']);
                    if ($this->input->post('redirect')) {
                        redirect('order/checkout');
                    } else {
                        redirect('signup');
                    }
                }
            }else {
                $this->session->set_flashdata('form_msg', 'Something Went to wrong');
                redirect('signup');
            }
	}


	public function forgotpassword()
	{
        $this->form_validation->set_rules('username-email', 'User Name', 'required');
            $data = ['user_mobile' => $_POST['username-email']];

            if ($this->form_validation->run() == TRUE) {
                $response = apiCall('forgotPassword', $data);
                if ($response['code'] == 1) {
					$this->session->set_flashdata('success', $response['msg']);
					redirect('site/resetpassword');
                } else {
					$this->session->set_flashdata('error', $response['msg']);
					redirect('site/signup');
                }
                
            }else{
                $this->session->set_flashdata('form_msg', 'Something Went to wrong');
                redirect('site/resetpassword');
            }
        }
	public function resetpasswordpost()
	{

		$response = apiCall('retrievePassword', $_POST);
		if ($response['code'] == 1) {
			$this->session->set_flashdata('success', $response['msg']);
			redirect('site/signup');
		} else {
			$this->session->set_flashdata('error', $response['msg']);
			redirect('site/resetpassword');
		}
	}

	public function resetpassword()
	{
		renderView($this, 'site/resetpassword');
	}

	public function profile()
	{

		if ($this->session->userdata('user')) {
		$response = apiCall('GetProfile');
		$user = $response['details']['data'];

		$this->session->set_userdata('user', $user);
		
			$settings = apiCall('getSettings');
			
			$settings=$settings['details']['settings'];
			
			$this->session->set_userdata('settings',$settings);
			
		$getloc = @json_decode(file_get_contents("http://ipinfo.io/"));
		$coordinates = @explode(",", $getloc->loc);
		if (isset($_POST) && $_POST) {
			$data = [
				'first_name' => $_POST['first_name'],
				'last_name' => $_POST['last_name'],
				'contact_phone' => $_POST['contact_phone'],
				'lat' => $coordinates[0],
				'lng' => $coordinates[1],
				'user_token' => $this->session->userdata('token'),
			];
			$response = apiCall('UpdateProfile', '', $data);

			if ($response['code'] == 1) {
				$this->session->set_userdata('user_name', $response['post']['first_name']);
				$this->session->set_flashdata('success', 'profile changed successfully');
				redirect('profile');
			} else {
				$this->session->set_flashdata('error', $response['msg']);
				redirect('profile');
			}
		}

        $addressbook = apiCall('AddressBookList');
        $credit = apiCall('CrediCartList');
		$OrderList = apiCall('OrderList');
		$BookingList = apiCall('BookingList',['tab'=>'all']);
		renderView($this, 'site/profile', ['bookingList'=>$BookingList['details'],'creditlist' => $credit['details'],'response' => $response, 'OrderList' => $OrderList['details'],'addresslist' => $addressbook['details']]);
		}else{
			redirect();
		}
	}

	public function Changepassword()
	{
        $this->form_validation->set_rules('current_password', 'Current Password', 'required');
        $this->form_validation->set_rules('password', 'New Password', 'required');
        $this->form_validation->set_rules('cpassword', 'Confirm Password', 'required');
		$data = [
			'current_password' => $_POST['current_password'],
			'new_password' => $_POST['password'],
			'cnew_password' => $_POST['cpassword'],
			'user_token' => $this->session->userdata('token'),
		];
        if ($this->form_validation->run() == TRUE) {
            $response = apiCall('ChangePassword', '', $data);
            if ($response['code'] == 1) {
                $this->session->set_flashdata('success', $response['msg']);
                redirect('profile');
            } else {
                $this->session->set_flashdata('error', $response['msg']);
                redirect('profile');
            }
        }else{
            $this->session->set_flashdata('error', 'something went to wrong');
            redirect('profile');
        }
	}


	public function getfavritelist()
	{
		$favrite = apiCall('FavoriteList');
		if ($favrite['code'] == 1) {
			foreach ($favrite['details']['data'] as $key => $row) {
				$favrite['details']['data'][$key]['action'] = '<a href="site/deletefav?id=' . $row['id'] . '" class="delete_fav"><i style="font-size: 25px;" class="ion-ios-trash"></i></a>';
			}
		}

		echo json_encode($favrite['details']);
	}


	public function uploadprofile()
	{
		$data = [
			'user_token' => $this->session->userdata('token')
		];
		$response = apiCall('UploadProfile', '', $data, $_FILES['file']);
		return 1;
	}

	public function deletefav()
	{
		$data = [
			'id' => $_GET['id']
		];
		$response = apiCall('RemoveFavorites', $data, '');
		redirect('profile');
	}


	public function logout()
	{
		apiCall('logout', []);
		$this->session->unset_userdata('user');
		$this->session->unset_userdata('token');
		$this->session->unset_userdata('cartData');
		$this->session->unset_userdata('transaction_type');
		redirect();
	}


}
